How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax()
model, instead they go straight to $.get()
. For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent()
in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data
value is encoded automatically via $.param()
). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Put your params in the
data
part of theajax
call. See the docs. Like so:The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
At server side receive it using $_GET variable.
You can use the
$.ajax()
, and if you don't want to put the parameters directly into the URL, use thedata:
. That's appended to the URLSource: http://api.jquery.com/jQuery.ajax/
Had the same problem where I specified
data
but the browser was sending requests to URL ending with[Object object]
.You should have
processData
set totrue
.Try adding this:
Depends on what datatype is expected, you can assign
html, json, script, xml
Use data option of ajax. You can send data object to server by
data
option in ajax and thetype
which defines how you are sending it (eitherPOST
orGET
). The default type isGET
methodTry this
And you can get the data by (if you are using PHP)
In aspx, I believe it is (might be wrong)