Originally I was trying to send a Javascript JSON Object to a PHP page, without success. Using the following test code:
var testobj = {
"test1":"test1data",
"test2":"test2data",
"test3":"test3data"
};
alert(testobj.test1);
$.ajax({
type: "POST",
url: "ajaxtest.php",
dataType: "json",
data: testobj
})
.error(function( msg ) {
alert( "Error: " + msg );
})
.success(function( msg ) {
alert( "Success: " + msg );
});
Never sends the data, and always returns an error.
Removing the 'dataType' attribute or defining it as anything other than 'json' returns 'success', but still no data is sent.
I can use the exact same Object code as the 'data:' value and it DOES get sent, but not when I use the JSON Object.
So I send an Array, instead:
var testobj = new Array();
testobj = {
"test1":"test1data",
"test2":"test2data",
"test3":"test3data"
};
alert(testobj.test1);
$.ajax({
type: "POST",
url: "ajaxtest.php",
data: testobj
})
.error(function( msg ) {
alert( "Error: " + msg );
})
.success(function( msg ) {
alert( "Success: " + msg );
});
Exactly the same code, except (a) I defined the variable as an Array instead of a JSON Object and (b) I removed the 'dataType' attribute from the .ajax call.
Grab the Array elements on the target page using the $_POST array.
I never much cared for JSON as a method for passing data, anyway, so this doesn't exactly worry me. But I do wonder about the current state of jQuery (v.1.9.1)
Is there something wrong with my JSON construction? What's the deal with sending a JSON Object via jQuery AJAX? And why is there a problem with the 'dataType: "json"' attribute?
testobj = {...}
replaces whatever was intestobj
with an object.dataType: "json"
is the data type of the data returned from the server. You get an error because the server is not returning JSON, and jQuery is trying to parse it. – Rocket Hazmat Nov 7 '13 at 22:40