Question :
The following Ajax call would send to PHP the parameters corresponding to the form that called the function:
var foo = "bar";
var bar = "foo";
function register(){
$.ajax({
method: "post",
url: "meu_script.php",
data: $("#form").serialize(),
});
}
And it would be accessible in PHP through id
s of HTML form components:
$campo = $_POST['id_campo'];
$senha = $_POST['id_senha'];
My question: what if instead of using a form, I wanted to pass the values of the variables foo
and bar
, what would be the data
parameter of my Ajax call?
Answer :
Just specify a javascript object:
var foo = "bar";
var bar = "foo";
function register(){
$.ajax({
method: "post",
url: "meu_script.php",
data: {foo: foo, bar: bar},
});
}
To get a little less confused, I would give a different name to the variables. Something like this:
var _foo = "bar";
var _bar = "foo";
function register(){
$.ajax({
method: "post",
url: "meu_script.php",
data: {foo: _foo, bar: _bar},
});
}
Use $.post
documentation: link
jQuery
var foo = "bar";
var bar = "foo";
$.post('meu_script.php',{
parametro_qualquer_nome1:foo,
parametro_qualquer_nome2:bar
},function(){
// ação quando for concluída a solicitação
})
PHP
$foo = $_POST['parametro_qualquer_nome1'];
$bar = $_POST['parametro_qualquer_nome2'];