receive ajax json POST in php and return to success

Asked

Viewed 44,020 times

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(){
            var tmp = {"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 '$aDados' (T_VARIABLE)

  • 2

    If you can explain better the problem you have in particular and, if possible, show code you have done where this problem is. Your question is too broad, see Help Center How to Ask.

  • my question is simple, receive this $_POST in the report.php

  • Ajax is a request literally equal to the request a form makes to your php file, you work the $_POST in the same way that would work with a form. The Success in ajax represents success when making the request, it means q has not expired the request time, that the requested page exists and etc.

  • Okay, I get it, I use $.ajax with constantly. net mvc4, however, in php I’m having difficulties, I did everything I informed and q passed me here, but nothing works..

  • Display an error message on the Chrome console or firebug (firefox) ?

  • 2

    That last mistake, unexpected '$aDados' (T_VARIABLE) happened because a ; in the second header(....).

Show 1 more comment

3 answers

2


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

data: {'rel': tmp},

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

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

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

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

exit:

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

)
  • Thanks for the attention Lost, but wanted to return this on an Alert, or console.log, in ajax’s Success, can help?

  • I do the processing and an echo in the message you want, this text output will be accessible on sucess by the variable data, success: function(data) {&#xA; alert(data);&#xA; }

1

For your PHP (report.php) to generate a JSON-like response:

<?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 it will be returned a "Warning", to understand, try to put a echo('test'); before the header.

In your php (.php report), 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));
?> 

Note 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");
     }
 });

});

  • Felipe, I did as reported, however continues without returning anything, neither Alert nor console.log.. my ajax is correct?

  • @Jhonatan I do not know if the way it was done works, change its tmp variable, try like this: var tmp = {"Proc":3236470,"Shipping":"05/08/2014","Digitizing User":"CSC TI","Tp Doc":"Services","Unit":"CSC-TI"}; I just removed the []

0

Buddy, I ran your code here and the header tags weren’t really working. When I removed them I started to make a mistake because you were passing json directly and using json_decode, the json_decode function expects a string. Then you can pass as string and use json_decode in php or pass as json and not use json_decode in php.

Still 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()
        {
            var tmp = {"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>

Page test.php:

<?php

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

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

var_dump($aDados);
  • it only shows the date in Alert, in php page it is null

Browser other questions tagged

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