How to do a POST of a variable and receive it as an object in PHP using AJAX?

1

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"}
    
asked by Victor Alvarado 07.08.2017 в 20:21
source

2 answers

0

Reviewing several (many) pages I found this way of doing a POST of the variable content in its entirety, and not only treating it as an array or failing to only obtain the values of POST of a key:

Javascript code :

// Pasamos el objeto , podemos usar "nombre" o nombre, igual funcionara
var dato = { 
    "nombre":"victor",
    "apellido":"alvarado",
    "edad":14
};

$.ajax({
    type:"POST",
    url:"cargar.php",
    data: dato,
    dataType:"json",
    success: function(data) {},
    error: function() {}
});

PHP code :

<?php
// Obtenemos todos los datos del POST, no únicamente del campo
$return = $_POST; 

// Luego eligiremos como deseamos trabajar el valor recibido:

// Forma 1, Array Asociativo:

foreach($return as $valor){
    echo $valor."<br>";
}


// Forma 2, Convertilo en JSON

$return= json_encode($return);
echo json_encode($return);

?>

In this way we will have two ways to receive the data:

Form 1 :

victor
alvarado
14

Form 2 :

"{\"nombre\":\"victor\",\"apellido\":\"alvarado\",\"edad\":\"14\"}"

Now if we want to receive these values with GET, they will not work to work as JSON unless: we encode the type of data that will be received :

$.ajax({
    type:"GET",
    url:"cargar.php",
    dataType:"json",
    success: function(data) {
        alert(JSON.stringfy(data));
    },
    error: function() {
    }
    });

Getting this:

{"nombre":"victor","apellido":"alvarado"}

And to access its properties we use either data.nombre or data.apellido

    
answered by 07.08.2017 / 22:16
source
3

What you must keep in mind is that AJAX is used to transmit information from one resource to another, in the form of an object but simplified to the Javascript notation (JSON = JavaScript Object Notation ). Therefore, to use JSON, you need to create an object with at least one property that will contain the value you want. The notation requires you to have a%% share% ( clave:valor ) or use an array ( {clave: 'valor'} ).

On the other hand, the same PHP structure tells you that ['Posición 0'] receives an array, be it this indexed numeric ( $_POST ) or a associative array ( $_POST[0] ).

Therefore, the answer to your question

  

How should I send the variable to obtain an object like in case 3, but without having to place that object inside another?

is: you can not , if you want to receive an object then you must send an object, the only variation could be:

JS   >> var variable = [{nombre: "Victor", apellido: "Stack"}]
PHP  >> $_POST[0]
    
answered by 07.08.2017 в 20:55