Why Is My Ajax Post Function Not Working With Button Click?
I am trying to post variables to my PHP file when a button is clicked using AJAX, but when I check my PHP page loads, I am not receiving the variables. $(document).ready(function()
Solution 1:
May be it is because you are not declaring content type.
Change your script as follows.
$(document).ready(function(){
$("#qryBtn").click(function(){
// post qry //
var qry = query();
$.ajax({
type: "POST",
url: "favourites.php",
data: {
qry: qry
},
contentType: 'application/json',
success: function (html) {
console.log (qry);
}
});
});
});
Default jquery ajax content type is application/x-www-form-urlencoded; charset=UTF-8
while your are posting your data in json
format so that you have to explicitly tell ajax that your are sending json
content by declaring content type as application/json
EDIT
Then send data as string content. Try following script. (please note I have removed contentType
option.
$(document).ready(function(){
$("#qryBtn").click(function(){
// post qry //
var _data= JSON.stringify({qry:query()});
$.ajax({
type: "POST",
url: "favourites.php",
data: _data,
success: function (html) {
console.log (qry);
}
});
});
});
Solution 2:
$(document).ready(function(){
$("#qryBtn").click(function(){
// post qry //
var qry = query();
qry = JSON.stringify(qry); // added this line
$.ajax({
type: "POST",
url: "favourites.php",
data: {
qry: qry
},
success: function (html) {
console.log (qry);
}
});
});
});
Post a Comment for "Why Is My Ajax Post Function Not Working With Button Click?"