I am confused about using data
objects in my AJAX submit.
Here’s my submit AJAX script:
$.ajax({
url:'/library/php/triggers.php',
type:'POST',
data:data,
cache:false,
dataType:'json',
processData:false,
contentType:false,
success:function(result){console.log(result);}
});
This data
works:
var data=new FormData(this);
data.append('hello','my friend');
But this data
does not work:
var data={"hello":"my friend"};
Aren’t these both JSON objects? What’s the difference between these?
I also tried changing contentType:false
to contentType:'application/json'
without success.
2
Answers
The
processing:false
is because browsers internally process FormData object the same way they do when submitting a<form>
.You want jQuery to process the plain object. It uses
$.param()
internally to create a form encoded stringTo recieve in php:
What jQuery does internally with the object:
To address the difference between the two:
If you just did
And then check your dev tools you would notice that:
Form.data()
has a lot of other properties in constructor associated with methods that you can use on it, so browser treats it differently.Last function :
function entries() <prototype>: Object { … }
is the same as regular object where data is being stored with getters and setters:Also take notice that you last creation of object converted your string
'hello'
into keyhello:
while form data converts all keys and values into string.So, in short this two are not the same objects.