The value of variable is deleted when passing it from js to php

1

I'm doing a shipment by ajax from js to php.

I am sending an array of objects using angular, here my code.

$scope.updateRecipe = function()
{
    //Se hace petición ajax para agregar el producto
    $http(
    {
        //Se elige el metodo de la consulta
        method: 'POST',

        //Cabecera
        headers:{'X-CSRF-TOKEN':$('input[name="_token"]').val()},

        //Data
        data:$scope.arrayObject,

        //Se ingeresa la ruta de la consulta
        url: './ruta'
    })

    //Si hay una respuesta positiva
    .then(function (response)
    {
      //Respuesta
    });

};

The array is as follows

[
 {"idItem":68,"item":"salsa piña","quantity":1,"unit":"Gramo","idProduct":80,"deletable":false,"isNew":false}
 ,{"idItem":71,"item":"salsa mostaza","quantity":1,"unit":"Gramo","idProduct":80,"deletable":false,"isNew":false}
 ,{"idItem":79,"item":"","quantity":2,"unit":"Kilogramo","idProduct":0,"deletable":false,"isNew":true}
]

The problem is that when it arrives at php it is shown in the following way

[0] => stdClass Object
    (
        [idItem] => 68
        [item] => salsa piña
        [quantity] => 1
        [unit] => Gramo
        [idProduct] => 80
        [deletable] => 
        [isNew] => 
    )

[1] => stdClass Object
    (
        [idItem] => 71
        [item] => salsa mostaza
        [quantity] => 1
        [unit] => Gramo
        [idProduct] => 80
        [deletable] => 
        [isNew] => 
    )

[2] => stdClass Object
    (
        [idItem] => 79
        [item] => 
        [quantity] => 2
        [unit] => Kilogramo
        [idProduct] => 0
        [deletable] => 
        [isNew] => 1
)

The values of some variables disappear ...

They know why this can happen

    
asked by Alejo Florez 19.01.2018 в 23:35
source

1 answer

2

How about, when you serialize and deserialize data, you must code them correctly.

In Javascript you have the functions JSON.stringify and JSON.parse to serialize and deserialize respectively.

In PHP you have the functions json_decode and json_encode as counterpart.

Before sending your array by ajax you must prepare it:

let datos = JSON.stringify($scope.arrayObject);
...
    Cabecera
    headers:{'X-CSRF-TOKEN':$('input[name="_token"]').val()},

    //Data
    data:datos,
...

In PHP you receive the encoded JSON and you must decode them:

... 
$datos_en_php = json_decode($datos_desde_ajax); 
echo $datos_en_php[0]->idItem . '<br /> . $datos_en_php[0]->item;

In turn, when you send your answers from PHP to Javascript, you use the other two functions:

$resultado = json_encode($algun_resultado);
echo $resultado;

In Javascript you receive the answer and you must parse it:

...
.then($data){
    let datos = JSON.parse($data);
    console.log(datos.alguna_propiedad);   
}

I hope it serves you.

    
answered by 20.01.2018 / 15:44
source