The data parameter expects key=value type definitions just like typical
URLs. So if you have simple data you might do
$.ajax({
// ...
data: "item1=1&item2=2",
// ...
});
And build up that string however you need to.
If your data is in a form, you can use .serialize() or .serializeArray()
to do this quicker.
i.e.
$.ajax({
// ...
data: $("#myForm").serialize(),
// ...
});
If you have more complex data, but still relatively simple (i.e. would
fit a simple key=value situation where "value" is not another complex
object), then you can do something like:
var myData = {
name: $("#name").val(),
address: $("#address").val()
}
$.ajax({
$.ajax({
// ...
data: myData,
// ...
});
The $.ajax() method will convert your object to an appropriate string.
If you need more complex data - like say an array of objects, then your
best bet (IMO) is to create a custom JSON string to pass to your server.
// multiline for readability....
var myJson = '{ [
{ "name": "' + $("#name1").val() + '",
"address: "' + $("#address1").val() + '"
},
{ "name": "' + $("#name2").val() + '",
"address: "' + $("#address2").val() + '"
}
]}";
$.ajax({
// ...
data: "json=" + myJson,
// ...
});
While the $.ajax() method will handle a simple object nicely, it fails
when you have more complex objects - in my experience... I end up
getting an array of "[object Object]" strings, rather than the objects
themselves. So I end up having to create my own JSON string, or using
the "array" method of passing elements with the same name
(i.e. <input name="person[]"> ), which I find to be hit and miss for
back end language support. PHP works fine, but ColdFusion doesn't like
it (at least not when I tried). So the JSON approach is "cleaner" in
that it works better with all back end servers - they just need to
decode the json string to an object and you can use it there. (I'm
actually hoping someone can tell me a better way to do this....).
For the JSON approach, if it is a one off type thing, I'd say just code
the string manually. If you are doing this over and over, grab the JSON
libraries and let IT build your string for you. It is up to you to
decide if you want/need the extra libraries loaded loaded though....
Hope that helps.
Shawn
jb007nd wrote:
Do i need to encode my data send through AJAX post?
Ex.
var name = $("input#name").val();
var dataString = 'name='+ name;
///////////////////////////////////////////////
$.ajax({
type: "POST",
url: "mail.ajax.php",
data: dataString,
dataType: "html"
});
///////////////////////////////////////////////
How can I do an URLecode?
thanks!