How to return via PHP several JSON messages, each of which is fired at different times?

Asked

Viewed 1,407 times

4

I am building a system and at a certain stage it saves 3 sets of information filled in the form by the system operator:

  • Set 1: student information;
  • Set 2: student guarantor information;
  • Set 3: Student Enrollment Information.

I am making the requests to the code that saves the information via AJAX (using jQuery), and on the server side the script PHP does some checks and returns some messages.

For example, the system checks the existence of the student record and warns the operator, then checks and can alert that the guarantor’s CPF is invalid (if it passes the js validation).

What happens is that as are two series of messages he makes it:

Ajax answer giving error inserir a descrição da imagem aqui

In PHP code I’m doing so:

Warnings for set 1 of information

// encontrou Registros do Aluno 
if($busca_aluno['sys'] === '002' && $aguardando_usuario === false){ 
$retorna['msg'] = 'Este Aluno foi reconhecido pelo sistema';

//verifica status da matrícula do aluno
if($busca_aluno['situacao_pessoa'] === 1){ //ativa, identifica rematrícula

    $operacao_aluno = 'rematricula'; //updt
    $retorna['msg'] .= '<p>A matricula do Aluno esta ativa e sera realizada a <strong>REMATRICULA</strong> dele. Aguarde...</p>';

}elseif($busca_aluno['situacao_pessoa'] === 0){ //inativa, identifica que o aluno passou um certo período sem se matricular

    $operacao_aluno = 'matricula'; //insert
    $retorna['msg'] .= '<p>A matricula do aluno estava inativa, ele sera matriculado normalmente.</p>';

}else{ // situação desconhecida

    $operacao_aluno = 'matricula'; //insert
    $retorna['msg'] .= "<p>O codigo retornado pelo sistema para a situacao do aluno, e um codigo invalido de acordo com as diretrizes.</p>";
    $retorna['msg'] .= "<p><strong>Informe a matrícula do aluno ao suporte. O cadastro do aluno sera continuado como MATRICULA.</strong></p>";

}

// adiciona os dados de código do sistema ao array de mensagem
$retorna = array_merge($busca_aluno, $retorna); 
echo json_encode($retorna); // aviso na tela
}

The warning structure of the other sets follow the same structure, the warnings appear one after the other.

1 answer

7


If I understand correctly, you use three instructions to return the JSON:

echo json_encode($retorna1);
echo json_encode($retorna2);
echo json_encode($retorna3);

Each json_encode is generating an associative array ({ ... }) and by concatenating the three answers, you have a poorly formed JSON. As you want to return three things, you must return a list, which in JSON is represented by [ ... ], with elements separated by commas.

The solution is then to create an array to serve as a list, add each answer and at the end return the json_encode of that list:

$lista_retorna = array();
$lista_retorna[] = $retorna1;
$lista_retorna[] = $retorna2;
$lista_retorna[] = $retorna3;

echo json_encode($lista_retorna);

The result JSON will be valid in the format [{...}, {...}, {...}], where each {...} is an answer.

  • Excellent! I hadn’t thought of that. My warning structure has shown this annoyance mainly because the processing is not time consuming, and the time that each message appears on the user screen is probably not enough. I think I’m going to erase the messages and show only the really necessary ones. Unless some more interesting user interaction architecture arises.

Browser other questions tagged

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