Reputation: 297
I cannot pass data as a variable when using Ajax.
The following code works fine:
$.ajax({
type: 'GET',
url: 'test10.php',
data: { name:'Donald', town:'Ducktown' },
});
The code below does not work:
var new_names = ("name:'Donald', town:'Ducktown'") ;
$.ajax({
type: 'GET',
url: 'test10.php',
data: { new_names },
});
Your help is highly appreciated.
Upvotes: 1
Views: 905
Reputation: 219097
It doesn't work because it's not the same thing. The first example has this as the data object:
{ name:'Donald', town:'Ducktown' }
Which is a valid object. If we re-factor the second example, we can simplify it down to essentially a syntax error. Starting with what you have:
var new_names = ("name:'Donald', town:'Ducktown'");
//...
{
data: { new_names }
}
First remove the parentheses, since they don't actually do anything here:
var new_names = "name:'Donald', town:'Ducktown'";
//...
{
data: { new_names }
}
Then remove the use of a variable as temporary storage:
{
data: { "name:'Donald', town:'Ducktown'" }
}
And you can see why it becomes a problem. This is just a string literal in brackets, and not a valid object (or even valid syntax, though the use of the variable as temporary storage may somehow get it to pass the parser). You could make the string itself a value on an object:
{ someValue: "name:'Donald', town:'Ducktown'" }
But I doubt that's what you want. If you just want to store the object in a variable, then why change the notation? Just store it as a variable like you already use it:
var new_names = { name:'Donald', town:'Ducktown' };
Then use the variable:
data: new_names
There's no reason to modify the notation or throw in extra quotes or brackets. A literal object is a literal object, as-is. Whether you use it in-line or store it in a variable and use the variable, the notation to define the literal object itself doesn't change.
Upvotes: 1
Reputation: 587
replace '(' for '{'
var new_names = {name:'Donald', town:'Ducktown'} ;
and remove '{' in data
data: new_names
Upvotes: 0
Reputation: 346
The mistake here is you need to pass an object, check the correct code:
var new_names = {name:'Donald', town:'Ducktown'};
$.ajax({
type: 'GET',
url: 'test10.php',
data: new_names,
});
or you can do this:
$.ajax({
type: 'GET',
url: 'test10.php',
data: {name:'Donald', town:'Ducktown'},
});
Upvotes: 0
Reputation: 11
You need to pass the data as an object instead of a string:
var new_names = {name:'Donald', town:'Ducktown'} ;
$.ajax({
type: 'GET',
url: 'test10.php',
data: new_names,
});
Upvotes: 0
Reputation: 382464
2 errors:
var new_names = {name:'Donald', town:'Ducktown'}; // create a proper literal
$.ajax({
type: 'GET',
url: 'test10.php',
data: new_names, // don't put braces here
});
Upvotes: 0