Reputation: 603
How can I use JSON-like variable in my function like this?
$.ajax({
type:"POST",
-->data:{this_var:this_value}
});
Upvotes: 0
Views: 51
Reputation: 493
Use JSON.stringify() to create JSON object.
$.ajax({
type: "POST",
url: urlAction,
dataType: "json",
contentType: "application/json",
data: JSON.stringify({variable1: value1, variable2: value2})
});
Upvotes: 1
Reputation: 23893
Try this
formData = {
param1: $("#param1").val(),
param2: $("#param2").val()
}
$.ajax({
type: "POST",
url: "http://example.com/create.php",
data: formData,
dataType: "json",
success: function(data) {
alert("Add success");
},
error: function() {
alert("Add failure");
}
});
Upvotes: 0
Reputation: 672
Your code:
$.ajax({
type:"POST",
-->data:{this_var:this_value}
});
Then to use the object as you mentioned would be:
var myObj = {this_var:this_value};
myObj.this_var();
That is if this_var is a function. Otherwise the value can be consumed such as:
var myObj = {this_var:this_value};
var myVal = myObj.this_var;
You may also need to pass the data in as a string and then parse it as JSON after getting the string from the ajax call.
var myObj = JSON.parse(data);
var myVal = myObj.this_var(); // if this is a function
Upvotes: 0