receive ajax json POST in php and return on success

3

What am I doing wrong?

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script><script>$(document).ready(function(){$('#btn1').click(function(){vartmp={"Proc":3236470};
            $.ajax({
              type: 'POST',
              url: 'test.php',
              data: {'rel':tmp},
              success: function(data) {
                $('body').append(data);
                //alert(data);
              }
            });
        });
    });
    </script>
</head>
<body>
    <button id="btn1">
        teste
    </button>
</body>

test.php

<?php
header('Cache-Control: no-cache, must-revalidate'); 
header('Content-Type: application/json; charset=utf-8')

$aDados = json_decode($_POST['rel'], true);

echo $aDados["Proc"];
?> 

ERROR: Parse error: syntax error, unexpected '$ aData' (T_VARIABLE)

    
asked by anonymous 13.05.2014 / 15:35

3 answers

2

To receive the ajax data, just use the (POST) method and the correct key (rel) as indicated in your code

data: {'rel': tmp},

To turn json into an array in php use json_decode ()

p>
header('Content-Type: text/html; charset=utf-8');// para formatar corretamente os acentos

$arr = json_decode($_POST['rel'], true);

echo  '<pre>';
print_r($arr);

output:

Array
(
    [0] => Array
        (
            [Proc] => 3236470
            [Envio] => 08/05/2014
            [Usuário Digitalizador] => CSC TI
            [Tp Doc] => Serviços
            [Unidade] => CSC-TI
        )

)
    
13.05.2014 / 15:54
0

For your PHP (relatorio.php) generate a response of type JSON:

<?php
//Alteramos o cabeçalho para não gerar cache do resultado
header('Cache-Control: no-cache, must-revalidate'); 
//Alteramos o cabeçalho para que o retorno seja do tipo JSON
header('Content-Type: application/json; charset=utf-8')
//Convertemos o array em um objecto json
echo json_encode(array('erro' => '0','msg' => 'Executado com sucesso'));
?> 

It is important that the header be called before any output, otherwise a warning will be returned, to understand, try putting a echo > before the header.

In your php (relatorio.php), to work with the array sent in the AJAX request, just do the following:

<?php
header('Cache-Control: no-cache, must-revalidate'); 
header('Content-Type: application/json; charset=utf-8')

$aDados = json_decode($_POST['rel'], true);
$nProc = $aDados["Proc"];

echo json_encode(array("erro" => "0", "proc" => $nProc));
?> 

Notice that we use an associative array, that is, instead of using numbers as index, we use names, in the example above, "error" and "proc". These names will be available in the function that is executed in the "success" parameter of your AJAX call.

To work with the json that will be returned, change the function that is executed in the "success" parameter:

$('#btn').click(function(){  
    var tmp = {"Proc":3236470,"Envio":"08/05/2014","Usuário Digitalizador":"CSC TI","Tp Doc":"Serviços","Unidade":"CSC-TI"};
    $.ajax({
      type: 'POST',
      url: 'relatorio.php',
      data: {rel:tmp},
      dataType: 'json',
      success: function(data) {
        //$('body').append(data);
        alert("O processo número "+data["proc"]+" foi enviado com sucesso");
     }
 });

});

    
13.05.2014 / 16:05
0

Comrade, I circled your code here and with the header tags really was not working. When I removed them, it started to make a mistake because you were passing json directly and using json_decode, it happens that the json_decode function expects a string. Then you can pass as string and use json_decode in php or pass as json and do not use json_decode in php.

Following working code :

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script><script>$(document).ready(function(){$('#btn1').click(function(){vartmp={"Proc":3236470};
            //var tmp = '{"Proc":3236470}'; // se usar json_decode, tem que passar como string

            $.ajax({
              type: 'POST',
              url: 'test.php',
              data: {
                  'rel':tmp,
              },
              success: function(data) {
                $('body').append(data);
                // alert(data);
              }
            });
        });

    });
    </script>
</head>
<body>
    <button id="btn1">
        teste
    </button>
</body>
<html>

test.php page:

<?php

//$aDados = json_decode($_POST['rel'], true);

$aDados = $_POST['rel'];    //se for passar como json direto, não usar json_decode

var_dump($aDados);
    
08.12.2016 / 18:53