How to pass parameters in jquery
I am supposed to submit 2 values called str and name to another page.But only 1value is getting returned in the next page. When I include name and on next page if I say print_r($_POST)
,then even the first value is not getting printed. I have written a function as follows,which works because there is only one parameter.
function sendValue(str)
{
$.post(
"newsletter/subscribe.php", //Ajax file
{
sendValue: str
},
function(data){
开发者_开发问答$('#display').html(data.returnValue);
},
"json"
);
}
But if I pass 2 values in that function and in $.post
, I do sendValue:str,name
then I am not getting even 1 value.
You can post 2 values like this:
function sendValue(str, name) {
$.post("newsletter/subscribe.php",
{ 'string': str, 'name' : name },
function(data){
$('#display').html(data.returnValue);
},
"json");
}
The format for the data argument of $.post()
is like this:
{ 'varName' : variable, 'var2Name', variable2, 'var3Name' : variable3 }
You cannot assign comma separated values to the same key within an object, as it breaks Javascript syntax. You will need two pairs, e.g.:
function sendValue(str)
{
$.post(
"newsletter/subscribe.php", //Ajax file
{
sendValue: str, anotherValue: anotherStr
},
function(data){
$('#display').html(data.returnValue);
},
"json"
);
}
Then in your PHP script, you can access anotherValue
as $_POST['anotherValue']
, and it will correctly show up in print_r($_POST)
.
If you prefer, you can send a single string with key value pairs as follows:
$.post( "newsletter/subscribe.php", "theValue=something&anotherValue=somethingelse",
function(data){
$('#display').html(data.returnValue);
},"json");
精彩评论