Javascript - Send Javascript Variable to PHP - javascript

I want to send the value of a JavaScript variable (variableToSend) to a PHP variable ($latLong) which then gets posted to MySQL. The JavaScript variable is capturing the value of an HTML textbox outside of a form listed below:
<input type="text" id="latLng" value="Working"/>
The textbox value passes to the Javascript variable just fine (I've tested via an alert with the variable's value):
<script language="JavaScript">
setTimeout(function(){
var variableToSend = document.getElementById("latLng").value;
$.post('html/index.php', {$latLong: "variableToSend"});
}, 10000);
</script>
However, the $.post method is not firing. I'm thinking one of a couple of things were happening. One, the text field was not in a form which is why it didn't pass to the PHP variable. I tested this by throwing the text field back in a form tag, but that didn't work. Second, the $.post method is written incorrectly. Third, the $.post method is not firing at all after the 10 second interval. I'm thinking it's the third case but would like some direction if at all possible.
Any help is greatly appreciated.

You can use a QueryString appended to the script. Another better option would be to use the FormData object.
Here is a sample from MDN:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
// HTML file input user's choice...
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like object...
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

Related

Escaping xsrf in Tornado with javascript POST

I have a simple form I would like to submit to a Tornado POST and I am running xsrf in tornado. The following produces the known error: '_xsrf' argument missing from POST
Has anyone solved how to submit the xsrf (like {% module xsrf_form_html() %}) in a regular HTML form using javascript? Here is the code:
<form action="#" id="form_field">
{% raw xsrf_form_html() %} # DOES NOT WORK!
<p><input type="text" id="field1" value=""></p>
</form>
<button id="button">UPDATE</button>
<script>
button.onclick = function changeField() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/chatdata", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: document.getElementById("field1").value
}))
};
</script>
xsrf_form_html is for traditional html forms using x-www-form-urlencoded. It won't be recognized if you submit your form as JSON. To use non-form-based encodings with Tornado's XSRF protection, pass the XSRF token as a X-XSRF-Token X-XSRFToken HTTP header.
According to the documentation page you would just create a request that has a _xsrf request field, for example a x-www-urlencoded string of _xsrf=yourtoken. The way you had it you were sending just some JSON that had a value property, ie {"value":"token"}.
Now you can get the token in a couple ways from what I have seen, either through a set cookie or from the field that is generated from the xsrf_form_html() call.
From cookie
//helper function to read cookie, from http://www.tornadoweb.org/en/stable/guide/security.html sample
function getCookie(name) {
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
}
var data = "_xsrf="+getCookie('_xsrf');
//note using this method you don't set the content-type,
//you want it to default to x-www-urlencoded
xhr.send(data);
Note you would have to build up the string to contain your other input form fields, either directly or through library methods like jQuery's serialize()
If want to just use the data straight from the form without the hassle of grabbing each input and generating a proper x-www-urlencoded string yourself; Then continue using xsrf_form_html() and create a FormData object from that form and send that. When you pass a form element to FormData() it will collect all the input values for you.
var data = new FormData( document.getElementById('form_field') );
//again no need to set the content-type as it will be automatically set internally
xhr.send(data);
//You could also use library methods like jQuery's serialize()
var data = jQuery('#form_field').serialize();
xhr.send(data);
Using FormData helps if you don't know how to get a reference to the generated field directly. Though it would more than likely have name="_xsrf" so a selector like input[name="_xsrf"] should find it. Though you would have to look at the generated html to find out.
var data = "_xsrf="+document.querySelector('input[name="_xsrf"]').value

mod_wsgi: Reading POSTed file content remains empty

I don't get it, I don't understand.
In a self-developed Python web framework I'm posting a file form element to the server using JavaScript.
var formData = new FormData();
formData.append('file', document.getElementById('file').files[0]);
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.send(formData);
The server, sporting mod_wsgi, receives the request like so:
if environ['REQUEST_METHOD'] == 'POST':
post_env = environ.copy()
post_env['QUERY_STRING'] = ''
form = cgi.FieldStorage(
fp=environ['wsgi.input'],
environ=post_env,
keep_blank_values=True)
Then, when I want to access the form field's content to save it to a file, the following will return an empty result:
form['file'].file.read()
(All code has been edited for simplicity)
What puzzles me is that the form field will show the correct file name and MIME type, only file.read() remains empty.
Also all other information from other input text fields comes through and is accessible.
I also checked that environ['REQUEST_METHOD'] is actually POST.
As to HTTP Headers for encoding (such as multipart/form-data), I thought that the XMLHttpRequest object will take care of that, once formData.append() receives a file input as the value.
Okay, here's the solution:
I can't explain it, but the file form fields get emptied on first read, which I found out by accident. Maybe a bug, who knows.
I assumed that they would stay intact (like any other variable) and can be read multiple times.
What I ignored was that I had in fact addressed them several times.
So the solution was to first store the file's content in a variable, and then use that multiple times.

In PHP how to use $_REQUEST to retrieve an array of inputs to enter into a database

I am using AJAX to send inputs from a webpage to a PHP file to then be entered into a database. Here is my JavaScript file:
var pageLoaded = function () {
var submitButton = document.getElementById("submit");
if (submitButton) {
submitButton.addEventListener("click", submit, true);
}
};
var submit = function () {
var xhr, changeListener;
var form = document.getElementById('item_form');
var inputs = form.getElementsByTagName('input');
// create a request object
xhr = new XMLHttpRequest();
// initialise a request, specifying the HTTP method
// to be used and the URL to be connected to.
xhr.open("POST", "../php/add_item.php", true);
console.log(inputs[0].value); // debugging
// Sends the inputs to the add_item.php file
xhr.send(inputs);
};
window.onload = pageLoaded;
Here I am trying to send inputs from a form to a PHP file called add_item.php located "../php/add_item.php" in my file system.
I am pretty sure this code works and sends the inputs to the PHP file in an array.
My question is, how do I then use $_REQUEST within that file to be able to use the inputs within the array to send to a database? Or, what is the best way of doing this?
The xhr.send() method only accepts a string. If you want to send an array you have to flatten it into a string before posting. You can do this easily using the JSON.stringify() method in javascript, then use json_decode() function in PHP on receiving it.
Also for PHP to receive the data properly in the $_POST[] variable (or $_REQUEST if you must, but not recommended) you need to set a name for the POST variable and URL-encode your JSON text like this:
var json_array = JSON.stringify(inputs);
xhr.send('myJSONData=' + encodeURIComponent(json_array));
On the PHP side you shouldn't need to use urldecode() because the server stack expects to receive POSTed name-value pairs url-encoded. But you will need to use json_decode on the posted variable to get the array back, e.g.:
php_array = json_decode($_POST["myJSONData"]);
You will see other methods to do this, including setting the xhr POST content-type header to JSON, but in my experience this is the path of least resistance.
Also note whilst it is possible to send an "array" of objects in an HTML form like this:
<input type="text" name="myArray[]" value="val1">
<input type="text" name="myArray[]" value="val2">
<input type="text" name="myArray[]" value="val3">
<input type="text" name="myArray[]" value="val4">
which will result in an array being available within PHP in the variable $_POST["myArray"], there is no easy equivalent of this using the XHR object (AJAX method). JSON.stringify() is IMO the easiest way to go.
The variables inside the $_REQUEST are stored as an array. To access them you would do something similar to this:
echo $_REQUEST['input_1'];
To view all the variables (in a nice format) sent by the JS you could use this code:
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
You can't do it in the way you are doing it. You send "input" array which is incorrect. You should prepare array of input values. Morover, I'd recommend you to use JQuery.
$(function (){
$("#submit").click(function (){
//the way to get input values and names
var arr = [];
$("input").each(function (index,value){});
arr.push([$(value).attr('name'), $(value).val()];
});
// it can be replaced also via serialize() funciton
//ajax
$.post( "../php/add_item.php", arr)
.done(function( data ) {
//data has been send response is in data object
});
});
});
In PHP you can get these values via $_POST. $_REQUEST is not needed here because you use POST method. For example if you have input
<input name="xxx" value="test">
to print value of this input in PHP you need use this code
echo $_POST['xxx'];
If you don't want to use JQuery then you still need loop through inputs and prepare proper array to send it via XHR.

Can't build a FormData object out of existing form

I'm trying to build a FormData object out of a form on my page. I'm getting the form element like this:
var form = document.forms['upload_form'];
And then I'm building the FormData object like this:
var fd = new FormData(form);
Since you cannot log values in a FormData object (as described here), I'm sending the formdata to '/' just so I can see its contents in my Network Inspector. The contents of the request payload are simply:
------WebKitFormBoundaryKAgAjii8IMLyJFcB--
and nothing else! If I manually append a value to the form like this:
fd.append("username", "Groucho");
it works:
------WebKitFormBoundaryZikgEBo7sTzvlndC
Content-Disposition: form-data; name="username"
Groucho
I've also tried selecting the form element in other ways, such as with jQuery:
var form = $(".upload_form");
var fd = new FormData(form[0]);
No matter how I select the form element, the form variable certainly does have the form in it (it's not null or empty), but constructing the FormData object with it as a parameter just does not seem to work. Can anyone help?
PS I'm using Chrome 31.0.1650.57. I've also tried this in Safari 7.0 with the same results.
Another thing: The inputs in this form are nested inside a number of divs. Could this be a problem?
This was happening because I didn't have name attributes set on my inputs. Apparently, new FormData() and $.serialize() will ignore any inputs without names.

Where are the JavaScript field definitions?

I have a PHP form that includes javascript js_qty.js. Js_qty_.js has this function called xhrGetValue.
I am in my NetBeans IDE and it shows the field definitions for f.job_id, f.item_id, etc. I have looked in the JavaScript and the HTML portion of the PHP and I cannot find the field definitions.
Where else could I look to find the field definitions?
function xhrGetValue(field) {
//eval('document.forms[0].'+field+'.value=document.forms[0].'+field+'_value.value');
var r='GetValue';
var url = "job_qty_xhrr.php"; // The server-side script
var f=document.forms[0];
var param = 'p_id='+f.p_id.value+'&job_id='+f.job_id.value+'&r='+r+'&field='+field+'&item_id='+f.item_id.value+'&sub_id='+f.sub_id.value+'&qty_id='+f.qty_id.value;
http.open("GET", url+'?'+param, true);
http.onreadystatechange = handleHRGetValue
http.send(null);
}
var f=document.forms[0];
Tells you p_id and job_id are coming from the first form in your document (page). Check the html again or check to see if the fields are being generated by javascript.

Categories

Resources