Practicing AJAX, the following question arose:
When we want to do a POST towards PHP, we put in the attribute data
of the AJAX object, the variable that we want its content to be sent.
Then in the PHP file we must make a POST of said variable.
I wanted to try different values and I got this:
1) POST of a variable with a primitive value:
$(function() {
var variable ="victor";
$.ajax({
url:"cargar.php",
type:"POST",
data:variable,
success: function(data) {},
error: function() {}
});
});
});
PHP code :
<?php
include "conexion.php";
$data= $_POST["variable"];
echo var_dump($data);
?>
Returns NULL
2) Doing POST of an object :
var variable = {nombre:"victor",edad:22};
$.ajax({
url:"cargar.php",
type:"POST",
data:variable,
success: function(){},
error: function(){}
});
});
PHP code :
<?php
include "conexion.php";
$data1= $_POST["nombre"];
$data2= $_POST["edad"];
echo var_dump($data1);
echo var_dump($data2);
?>
Return Victor 22
3) Doing POST of an object inside another object :
var variable = {variable: {nombre:"victor", apellido:"stack"}};
$.ajax({
url:"cargar.php",
type:"POST",
data:variable,
success: function(data) {
$("#id").html(data);
},
error: function() {
$("#id").html("ERROR");
}
});
PHP code :
<?php
include "conexion.php";
$data= $_POST["variable"];
echo var_dump($data);
?>
Return array (2) {["name"] = > string (6) "victor" ["last name"] = > string (5) "stack"}
My question is: How should I send the variable to get an object like in case 3, but without having to place that object inside another?
Example:
AJAX >>> var variable = {nombre:"victor", apellido:"stack"};
PHP >>> $_POST["variable"];
>>> {nombre:"victor", apellido:"stack"}