how to get value from java script function to perl - perl

I want to get the value of check box selected and pass it to a query for deleting the value from database.
java script code
function deleteRows(){
isTable = document.getElementById('dataTbl');
nBoxes = document.getElementsByName('delBox');
for (i=nBoxes.length-1; i>=0; i--)
{
if (nBoxes[i].checked === true)
{
var a =nBoxes[i].value;
alert("Do you want to delete this row?"+a);
isTable.deleteRow(i+1);
}
}
}
i need the var a value in perl so that i can pass it to the delete query and delete the selected row.
html code
<Table id='dataTbl' border='1' >
<tr>
<td><input type=checkbox name='delBox' value=#data></td>
<td bgcolor=#0099FF>$pid</td>
<td bgcolor=#99CCFF>$project_name</td>
<td bgcolor=#3399FF> $variant_no</td>
<td bgcolor=#99CCFF> $variant_name</td>
<td bgcolor=#3399FF>$vehicle_class</td>
<td bgcolor=#99CCFF> $vc_no</td>
</table>
<input type=button value="Delete Rows" onclick="deleteRows()" id="delbtn">
perl query
my $sth = $dbh->prepare("delete form table name col1,col2,col3 where id='$a'");
$sth->execute() or die "$!";

You have to do POST request (or DELETE to be precise) towards server where your perl script runs.
e.g.
After you get a variable set (let's say you are using jquery):
$.ajax({
type: "POST",
url: url, // where your script lives
data: {'a' : a},
success: function(data) {
console.log(data);
}
dataType: 'json'
});
in your script you will then get 'a' variable from post request.

Sample scenario:
JS working on Your Client PC. Users selected some id.
JS sends selected id to server side Perl CGI script.
Perl parses GET request get id.
Perl checks if id is number not some string to hack your server.
Perl executes delete in MySQL.
Resourses:
JS send GET request with Param:
HTTP GET request in JavaScript?
Perl Read GET Parameter
How can I read the URL parameter in a Perl CGI program?
Perl MySQL Tutorial:
http://perl.about.com/od/perltutorials/a/perlmysql_3.htm

Related

Secure SQL update in PHP

As part of a job I want to update a database using a form. Since the database is large and is used by many users, I hope that this manipulation is at least secure for more safety.
HTML script :
<form action="http://localhost/modifier_infos_signaletique.php" method=POST >
<div class="id_sign">
<h5>Id "Signalétique" :</h5>
<input type="text" name="id_sign" id="id_sign"/><br>
</div>
<h5>Infos "Signalétique" : </h5>
<input class="comment" type="text" id="maj_infos" name="maj_infos" required maxlength='140'/><br>
<input type="submit" value="Submit" />
</form>
PHP script:
<?php
$user = 'xxxx';
$pass = 'xxxx';
try{
$dbconn = new PDO('pgsql:host=localhost;port=5432;dbname=xxxx',$user, $pass);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$maj = $_POST['maj_infos'];
$id = $_POST['id_sign'];
$query = $dbconn->prepare("UPDATE signaletique SET infos = ':infos' WHERE id = ':id'");
$query->bindParam(':infos', $maj, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
echo 'Données mises à jour';
}
catch(PDOException $e){
echo "Erreur : " . $e->getMessage();
}
?>
However, when I use this script this error appears:
**Erreur : SQLSTATE[HY093]: Invalid parameter number: :infos **
The error would be due to the parameter used for the bindParam function.
However, I have in the properties of my PostgreSQL database, info in "character varying". I tried to change this parameter to "text", but the error remains the same.
Forgive me for this question but I am new to PHP and my SQL skills are thin since I use pgAdmin and its tools a lot to build and interact with my databases.
Here is a screenshot of my database :
The info parameter is in "text" on the screenshot but basic this property was in "character varying" (140).
Thank you for your help.
In your query string you put single quotes around your placeholders. This makes them strings, not placeholders. You do not need quotes when using placeholders.
This should work:
$query = $dbconn->prepare("UPDATE signaletique SET infos = :infos WHERE id = :id");
See https://stackoverflow.com/questions/10966251/sqlstatehy093-invalid-parameter-number-parameter-was-not-defined for more information.

Element tree: .tail() always returns NONE

parser = etree.HTMLParser()
tree = etree.parse(StringIO(input), parser)
for target in tree.findall("//tr[#class='error']"):
print target.tail
I want to execute the code above on this an fetch everything after
trclass="error"id="Testcase_5">
<tr class="error" id="Testcase_5"><td>Hello</td><td>test</td><td>test</td> <td>test</td><td>Failed</td><td></td><td></td></tr>
However all I get is NONE
tail, by definition from lxml, is:
the text that directly follows the element, up to the next element in the XML tree
Since your tr class does not have any text beyond the <tr> .... </tr> and we just have one element, it returns None.
Let's say the input is:
'<tr class="error" id="Testcase_5"><td>Hello</td><td>test</td><td>test</td> <td>test</td><td>Failed</td><td></td><td></td></tr>i am the tail'
then the output would be i am the tail
Coming back to your question, if you want to extract all the text within the <tr> node you could do something like this:
parser = etree.HTMLParser()
tree = etree.parse(StringIO(input), parser)
for target in tree.findall(".//tr[#class='error']"):
#print target.tail
print target.xpath("//text()")
This will print:
['Hello', 'test', 'test', ' ', 'test', 'Failed']
Check lxml docs

create folder using a form with a given name

Im trying to make a html form that can create a folder on the server with a given name in the html form. So fare I have this code:
<?
if (isset($_POST['createDir'])) {
//get value of inputfield
$dir = $_POST['dirname'. var_dump($_POST)];
//set the target path ??
$targetfilename = PATH . '/' . $dir;
if (!file_exists($dir)) {
mkdir($dir, 0777, true); //create the directory
}
}
print_r($_POST); exit;
?>
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>" name="myform" id="myform">
<input name="dirname" id="dirname" >
<input type="submit" name="dirname" value="dirname" title="Continue to the next step">
</form>
The debug say: Array ( )
the script is nothing i have wrote but trying to put thing together to get it working but have not fix this for days now. Please advice.
Don't use PHP short opening tags (<?). Use the long form (<?php). You risk getting tangled up in the wrong language processor.
You're looking for $_POST['createDir'] coming back from the form, but I don't see a form element with name="createDir".
What is $_POST['dirname'. var_dump($_POST)] supposed to do?
What is PATH?
Play it safe by giving a type= for dirname input element.

xpath query to parse html tags

I need to parse the following sample html using xpath query..
<td id="msgcontents">
<div class="user-data">Just seeing if I can post a link... please ignore post
http://finance.yahoo.com
</div>
</td>
<td id="msgcontents">
<div class="user-data">some text2...
http://abc.com
</div>
</td>
<td id="msgcontents">
<div class="user-data">some text3...
</div>
</td>
The above html may repeat n no of times in a page.
Also sometimes the ..... portion may be absent as shown in the above html blocks.
What I need is the xpath syntax so that I can get the parsed strings as
array1[0]= "Just seeing if I can post a link... please ignore post ttp://finance.yahoo.com"
array[1]="some text2 htp://abc.com"
array[2]="sometext3"
Maybe something like the following:
$remote = file_get_contents('http://www.sitename.com');
$dom = new DOMDocument();
//Error suppression unfortunately, as an invalid xhtml document throws up warnings.
$file = #$dom->loadHTML($remote);
$xpath = new DOMXpath($dom);
//Get all data with the user-data class.
$userdata = $xpath->query('//*[contains(#class, \'user-data\')]');
//get links
$links = $xpath->query('//a/#href');
So to access one of these variables, you need to use nodeValue:
$ret = array();
foreach($userdata as $data) {
$ret[] = $data->nodeValue;
}
Edit: I thought I'd mention that this will get all the links on a given page, I assume this is what you wanted?
Use:
concat(/td/div/text[1], ' ', /td/div/a)
You can use instead of the ' ' above, whatever delimiter you'd like to appear between the two strings.

dojo file upload using zend framework problem

I am struggling with a bit of dojo that is needed to upload a file. Now the file upload form sits within a dojo dialog box, so is hidden until the user selects an 'upload file' button.
This button can be clicked on anywhere on the site, so I've created a controller to handle the upload.
At the moment I am just trying to get it to work, and in my head script I have the following:
<?php $this->headScript()->captureStart(); ?>
function sendForm(){
//Hide the file input field
dojo.style('inputField',"display","none");
//Show the progress bar
dojo.style('progressField',"display","inline");
dojo.byId('preamble').innerHTML = "Uploading ...";
dojo.io.iframe.send({
url: "<?php echo $this->baseUrl(); ?>/fileprocssing/loadfile/",
method: "post",
handleAs: "text",
form: dojo.byId('StartFrm'),
handle: function(data,ioArgs){
var fileData = dojo.fromJson(data);
if (fileData.status == "success"){
//Show the file input field
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.byId('fileInput').value = '';
//Hide the progress bar
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('uploadedFiles').innerHTML += "success: File: " + fileData.details.name
+ " size: " + fileData.details.size +"<br>";
dojo.byId('preamble').innerHTML = "File to Upload: ";
}else{
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('preamble').innerHTML = "Error, try again: ";
}
}
});
}
<?php $this->headScript()->captureEnd() ?>
With the the basic upload for like this
<form id="StartFrm" enctype="multipart/form-data"
name="cvupload"
action="<?php echo $this->baseUrl();?>/fileprocssing/loadfile/"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<!-- wrapping these in spans to be able to modify
parts of this form depending on what the
dojo.io.iframe.submit() does -->
<span id="preamble">File to Upload:</span><br>
<span id="inputField">
<input type="file" id="fileInput" name="uploadFile">
</span>
<span id="progressField" style="display:none;">
<div dojoType="dijit.ProgressBar" style="width:200px" indeterminate="true"></div>
</span>
<br/>
<button value="upload" dojoType="dijit.form.Button"
onclick="sendForm()">Upload</button>
</form>
What I would like to know is how I can get the JSON data object from /fileprocssing/loadfile/ that contains upload data information if the form is called from /somecontroller/someaction/ ?? and when the file has been processed automatically redirect to something like /fileprocesing/reviewdata/
At the moment the action that I have looks like this
public function loadfileAction() {
$log = Zend_Registry::getInstance()->get('log');
$log->log('in loadfileaction', Zend_Log::DEBUG);
$log->log($_FILES['uploadFile']['name'], Zend_Log::DEBUG);
$uploadedFile = array(
'details' => $_FILES['uploadFile'],
'status' => 'success'
);
$log->log($fileUploadData->toJson(), Zend_Log::DEBUG);
$foo = "{'status':'success',details: {name:'".
$_FILES['uploadFile']['name'].
"',size:".
$_FILES['uploadFile']['size'].
"}}";
$log->log($foo, Zend_Log::DEBUG);
$this->view->fileData = $foo;
}
I've handcrafted the JSON data for the time being but will use Zend_Dojo_Data but at the moment I am just trying to get this working.
I have to confess that I don't know dojo that well, but trying to get my head around it in the shortest possible time.
Thanks in advance.
dojo.io.iframe.send requires the response data to be wrapped in a TEXTAREA tag. This is the only/easiest cross browser way to successfully access and load the response data, and is a requirement. It looks like you are sending plain JSON back from the action.
You can also adjust your handleAs to be "json" and skip the intermediate dojo.fromJson(data) call, it will be passed to you as a JSON object (provided the response is wrapped in the aforementioned TEXTAREA)