How to send string variables as parameter to call Ajax?

Asked

Viewed 17,667 times

4

The following Ajax call would send 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 would be accessible in PHP through ids of the 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, how the parameter would look data of my call Ajax?

2 answers

6


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 be a little less confusing, 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},
  }); 
}

2

Use $.post documentation: https://api.jquery.com/jQuery.post/

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'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.