How to send an object array type variable via AJAX?

Asked

Viewed 1,161 times

2

I have the following object:

var pessoas = [];

pessoas = {

  nome: "julio",
  sobrenome: "Henrique",
  idade: 18,
  amigos : ["Pedro", "João", "Isabella"]

}

I send the friends array via ajax like this:

$.ajax({
    url:'retira_falsos_amigos.php',
    type: "post",
    data: { amigos: pessoas.amigos },

    complete: function (response) {
        $('#output').html(response.amigosVerdadeiros);
    },
    error: function () {
        $('#output').html('Bummer: there was an error!');
    },
});

and makes no mistake.

But in my code, the array amigos turns an array of objects and making the same request results in error.

when it turns an array of objects looks like this:

itensAmigos[0] = {

  name: data[0][0],
  intervalo: intervalo,
  Start: Date.UTC(ano,mes,dia,hora,minuto),
  data: data[0][1],
  tooltip: {
     valueSuffix: " -"
  }

};

pessoas = {

  nome: "julio",
  sobrenome: "Henrique",
  idade: 18,
  amigos : itensAmigos

}

This is the error that appears:

inserir a descrição da imagem aqui

  • I didn’t quite understand the problem. Could put the snippet of the PHP code where you handle the received data and which error is appearing?

  • I supplemented my question with error, but the error that appears does not make sense with my code

  • I found the solution, if I was sending an array() I must inform that the variable that will carry the data tbm is an array, hence the need for by date: { 'friends[]': people.friends }, in quotation marks. after that no more error

3 answers

2


Submit your full formatted object and handle it in php with json_decode(). To send the data use the function JSON.stringify() that will convert it into a string.

$.ajax({
    url:'retira_falsos_amigos.php',
    type: "post",
    data: { dados: JSON.stringify(pessoas) },

    complete: function (response) {
        $('#output').html(response.amigosVerdadeiros);
    },
    error: function () {
        $('#output').html('Bummer: there was an error!');
    },
});

remove_falsos_friends.php

$amigos = isset($_POST['dados']) ? $_POST['dados'] : null;
$objAmigos = json_decode($amigos);
foreach($objAmigos->amigos as $key=>$obj){
    echo "Amigo ".$key." - Nome: ".$obj."<br>";
}

The answer is based on the example given in the question

  • could show me how to get the variables of this object in php with json json_decode().

  • I edited the answer, if I get confused I can explain better how each passage works

  • yes I got it, it was lovely! however this error request as shown in the question

  • The error at the end of the question doesn’t seem to be related to ajax, it looks like an undefined property within highstock.js line 458, I’m not sure how this library works, but there might be something missing in the html it uses of reference, an id, class or even canvas.

1

The first thing is you set the property dataType of ajax as json so that you can receive the return of PHP as an object.

Instead of using the complete of ajax, use the success. The complete will always be run independently if any error occurs in the processing of the request or not, already the success only if everything goes right.

Follow a functional example:

index php.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            $(function () {

                var pessoas = {
                    nome: "Julio",
                    sobrenome: "Henrique",
                    idade: 18,
                    amigos: ["Pedro", "João", "Isabella"]
                };

                function enviaFalsosAmigos() {
                    $.ajax({
                        url: "retira_falsos_amigos.php",
                        type: "post",
                        dataType: "json",
                        data: {amigos: pessoas.amigos},
                        success: function (response) {
                            var listaDeAmigosVerdadeiros = response.listaDeAmigosVerdadeiros;
                            for (var i = 0; i < listaDeAmigosVerdadeiros.length; i++) {
                                alert(listaDeAmigosVerdadeiros[i] + " é um amigo verdadeiro!");
                            }
                        },
                        complete: function () {
                            alert("A requisição foi finalizada.");
                        },
                        error: function (erro) {
                            alert("Ocorreu um erro ao processar a requisição.");
                        }
                    });
                }

                $("button").click(function (event) {
                    enviaFalsosAmigos();
                });
            });
        </script>
    </head>
    <body>
        <button>Clique para enviar os falsos amigos</button>
    </body>
</html>

remove_falsos_friends.php

<?php
$listaDeAmigosFalsos = $_POST["amigos"];
$listaDeAmigos = ["Pedro", "João", "Isabella", "Diego"];

$listaDeAmigosVerdadeiros = array_diff($listaDeAmigos, $listaDeAmigosFalsos);

echo json_encode(["listaDeAmigosVerdadeiros" => array_values(listaDeAmigosVerdadeiros)]);

-3

The first step is to define the type of request in your ajax call:

$.ajax({
url:'retira_falsos_amigos.php',
type: "post", // Defina aqui o tipo da requisição
data: { amigos: pessoas.amigos },

complete: function (response) {
    $('#output').html(response.amigosVerdadeiros);
},
error: function () {
    $('#output').html('Bummer: there was an error!');
},

});

With this your javascript will make a request of the post type for the php file remove_falsos_friends.php. and to get your array in php you must use the global variable $_POST['friends']:

$amigos = isset($_POST['amigos']) ? $_POST['amigos'] : null;
  • Hi Hiago, I edited the question showing better which error causes in which situation. the friends array, becomes an array of objects and then the error when I make this request, with or without the type declaration

  • The error that happens is in the return of ajax? you are using other scripts besides jquery?

  • posted what happens on the question

Browser other questions tagged

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