Pass an array of objects via AJAX via POST and read the properties of objects in PHP

Asked

Viewed 2,037 times

1

I’m having some problems solving this situation. I’m trying to pass my object array via AJAX to another PHP page and read the properties that are inside each object within that array. For you to try to understand better I will post the code here...

My Javascript is mounting the object and returning this data (example values):

[{"horario":"14:00","id_bus_rota_parada":"1","id_bus_rota":"0","id_bus_parada":"22"},{"horario":"15:00","id_bus_rota_parada":"1","id_bus_rota":"0","id_bus_parada":"23"}];

These objects are inside the "data array[]"...

So I try to pass this array of objects to PHP already transformed into JSON.

$.ajax({
        url: "../actions/rota_inserir.php",
        type: "post",
        contentType: 'application/json',
        data: JSON.stringify(dados),
        dataType: 'json',
        success: function (data) {
            if (data.sucesso == true) {
                var n = noty({
                    text: "Rota cadastrada com sucesso!",
                    type: 'success'
                });
            }
        },
    });

Now I don’t know how to receive this data in PHP, I did a line of code but it didn’t work...

$horarioParada = $_POST['horario'];

  • Ah, if I try to visualize the object by the browser using data[0]. id_bus_stop for example, it returns the value correctly.

  • The Ajax date attribute must be an object is not a string!

  • Ta, and how I would read the properties of the object in PHP, instead of using $scheduleParada = $_POST['horario'];

  • I see that your script is assembling an array with 2 objects and you want to insert the data of these objects massively! Is that right? In the example, there are 2 objects, can be more or only 2 in all situations?

2 answers

3


Assign a reference to the data you want to send pedido, and remove header setting contentType: 'application/json'.

$.ajax({
    url: "../actions/rota_inserir.php",
    type: "post",
    data: {pedido: JSON.stringify(dados)},
    dataType: 'json',
    success: function (data) {
        if (data.sucesso == true) {
            var n = noty({
                text: "Rota cadastrada com sucesso!",
                type: 'success'
            });
        }
    },
});

In php, set the output to json, and checks whether the request has been made, and then converts the data sent through pedido for an array, and returns a json status:

header("Content-Type: application/json");
if(isset($_POST['pedido'])){
  $dados = json_decode($_POST['pedido'], true);
  print json_encode(['sucesso'=>true]);
}

At the end, on the client, you can receive or not the return as json, That depends on what you really want to do.

Examples: Ajax - _POST

  • That’s exactly what I wanted, json_decode was missing for me, now I can access the values in PHP using for example $data[0]["time"], thank you very much!

  • @Matheuscavallini You can vary in the way you do it, just go exploring the method $.ajax, and if you want to use object instead of array just remove the true at the end of json_decode.

1

You don’t need to make this conversion to json to send by post, it would basically pass the object with the data

$.post('../actions/rota_inserir.php', {horario: '14:00'}, function (retorno) {
    // trata o retorno
}); 

If you want to return a php object, also gives, basically you would have to do a json_encode on the object and give an echo

<?php 
$obj = new stdClass();
$obj->success = true;
echo json_encode($obj);

Ai in this case Voce has to convert from when it gets there in the post

$.post('../actions/rota_inserir.php', {horario: '14:00'}, function (retorno) {
  try {
    retorno = $.parseJSON(retorno);
    if(retorno.success) {
      alert("Rota cadastrada com sucesso!");
    } 
  } catch (ex) {
    console.log(ex); 
  }
}); 
  • Thank you very much for your help, your answer is also correct, but Edilson understood what I really wanted, but thank you anyway!

Browser other questions tagged

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