Reputation: 13
I want to ajax post data which is dependent on my variables. I tried the following but no luck..
var datastring = "name:name,price:price,specialprice:specialprice,desc:desc,descs:descs,cat:cat,pictures:pictures,choiceimg:choiceimg,weight:weight,gtin:gtin,brand:brand,attid:attid";
if($("#color").val()) {
var color = $("#color").val();
datastring = datastring + ",color:color"
}
$.ajax({
type: 'POST',
data:{ datastring },
success: function() { },
error: function(){ },
url: 'insert.php',
cache:false
});
This posts as a string
datastring
name:name,price:price,specialprice:specialprice,desc:desc,descs:descs,cat:cat,pictures:pictures,choiceimg
:choiceimg,weight:weight,gtin:gtin,brand:brand,attid:attid
Any ideas / solutions ?
Upvotes: 1
Views: 737
Reputation: 12025
Assuming at the parameters are defined, this is how you need to create the object:
var name = ....;
var price = ....;
.....
var datastring = {
name: name,
price: price,
specialprice: specialprice,
'three words property': 'value',
......
};
You can ADD/Change a property to the object (after it was declared) like this
datastring.myNewProperty = "myString"; // ADD
datastring.name = "New Name"; // UPDATE
datastring['three words property'] = "New Value"; // UPDATE
And you pass this to the server:
$.ajax({
type: 'POST',
data: datastring, // Note - I removed the wrapping "{" and "}"
success: function() { },
error: function(){ },
url: 'insert.php',
cache:false
});
Upvotes: 1
Reputation: 171679
That is not a valid form encoded string and the syntax used for data
property is invalid.
The simplest is to use an object and let jQuery encode it for you from that object:
var postData = {
name: // name value ,
...
desc: // desc value
...
attid: // attid value
}
if($("#color").val()) {
postData.color = $("#color").val();
}
Then pass that object to $.ajax
$.ajax({
type: 'POST',
data: postData ,
success: function() { },
error: function(){ },
url: 'insert.php',
cache:false//redundant since POST will never be cached
});
Upvotes: 1