I'm trying to send the value itest via ajax to myfile.php but $_POST['itest']; is not retrieving any data.
the html :
<form name=test>
<input name=itest>
<button>Send</button>
</form>
the js :
$(document).ready(function() {
$("form[name='test']").submit(function(e) {
e.preventDefault();
var itest = $("input[name=itest]").val();
$.ajax({
type:'POST',
url:'myfile.php',
data:itest
});
});
});
myfile.php
<?php
echo $_POST['itest'];
/* no data on $_POST['itest']; !!! why ? */
?>
Tiny tweak needed ! help !
The problem is, your data param is wrong. You need to send an application/x-www-form-urlencoded
string (eg a=1&b=2
) or an object literal, eg {a: 1, b: 2}
. You are sending a single string value.
Try this instead
var formData = $(this).serialize();
$.post('myfile.php', formData);
And make your button a submit type
<button type="submit">Send</button>
I'd even go so far as to make your JS much more portable
<form action="myfile.php" method="post" id="test">
<input name="itest">
<button type="submit">Send</button>
</form>
and the JS
$('#test').on('submit', function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize());
});
You are not sending the post data as an object.
The data
parameter needs to be an object. You are only passing a single value.
jQuery.ajax states:
data Type: PlainObject or String Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You need to replace itest
with a object.
var itest = $("input[name=itest]").val();
$.ajax({
type:'POST',
url:'myfile.php',
data: {'itest' : itest}
});
If we intend to POST all values in the form, which we generally what to do, we can improve on the previous code, by replacing an awkward object literal with some jQuery $(this).serializeArray()
. $(this)
refers to the form and serializeArray() creates a JavaScript array of objects, ready to be consumed by jQuery.ajax.
$(document).ready(function () {
$("form[name='test']").submit(function (e) {
e.preventDefault();
// This line added intentionally to show the data/data format used
console.log(JSON.stringify($(this).serializeArray()));
$.ajax({
type: 'POST',
url: 'myfile.php',
data: $(this).serializeArray()
});
});
});
$(document).ready(function() {
$("form[name='test']").submit(function(e) {
e.preventDefault();
var itest = {'itest' : $("input[name=itest]").val()};
$.ajax({
type:'POST',
url:'myfile.php',
data:itest
});
});
});