I’m trying to post data with AJAX and insert it into a database table.
The problem is, half of the data is missing and I don’t know why. I have checked all the names of parameters etc. because it seemed I had a typo somewhere (I was missing some characters but I fixed that) but still it won’t work.
Even console.log() and alerts give me the full data I want to post but it never arrives, the php outputs empty parameters. When deactivating the JavaScript or removing “return false;” the php script is opened as expected and works perfectly well, no data is lost (as expected).
Maybe I’m really just missing one single character somewhere …
I also tried escaping (escape()) the strings but it didn’t change anything.
Here’s the code and some logs/alerts/echos
$("#itemspeichern").click(function(){
setVisible("#item-process");
var itemname = escape($("#itemname").val());
if ($("#itemneu").is(":checked")) {
var itemneu = $("#itemneu").val();
} else {
var itemneu = 0;
}
var itembild = escape($("#itembild").val());
var itemkurzb = escape($("#itemkurzb").val());
var theset = escape($("#theset").val());
console.log("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild" + itembild + "&itemkurzb" + itemkurzb + "&theset=" + theset,
success: function(result){
alert("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
document.getElementById("item-process").innerHTML = result;
}
});
return false;
});
What this does is:
– output the data of all fields on the console
– showing all the data in the alert
but when it is done saving it the database is missing the values of itembild and itemkurzb. Getting the query as response from the php file showed that indeed the parameters are empty for those fields. Here’s what I did in php (I shortened it a bit, don’t comment on SQL injection and stuff :P)
$ergebnis = mysql_query("INSERT INTO mk7_items(id, de, neu, kurzbeschreibung, bild) VALUES(DEFAULT, '".$_POST["itemname"]."', ".$_POST["itemneu"].", '".$_POST["itemkurzb"]."', '".$_POST["itembild"]."')");
the last two fields are empty when I get the response and nothing is saved into the db.
As I said, setting JS to OFF and running it on php only works perfectly well.
Any ideas? Any stupid mistakes I did there?
You’re missing a couple
=in yourdata, it should be this:Or better, stop using
escape(which is deprecated in favor orencodeURIComponentdue toescapenot handling non-ASCII data very well) and use an object for yourdataparameter:That way
$.ajaxwill take care of converting your data to the proper POST (or GET or …) format and you don’t have to worry about the details.