Jose Marques
Jose Marques

Reputation: 748

AJAX it's not receiving the data back from the php file

I'm trying to send some values ​​through ajax and after being treated in the test.php, send the data back to be used.

The database part is correct. My problem is in the re-sending of the data: The Json coding part does not give error, but when I try to check the data, many of them do not appear.

I think this can be caused by:

The way I am resending the data;

The way I encode Json.

My code.

ajax main.php:

$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
    url: teste.php,
    type:'post',
    data:
        {
            limite: num_Limite_rows,
            tipologia: tipologia_val,
            ordenar_por: ordenar_por_val
        },
    success: function(data, num_rows, num_actual_rows, mensagem_erro)
    {

    }
});

PHP teste.php:

if(pg_num_rows($result1) > 0)
{
  $data = array[];
  $data = $result1;
  $out = array_values($data);
  echo json_encode($out);
  echo pg_num_rows($result1);
  echo $filtro_limit;
  echo "Não existem erros";
}
else
{
  $data = array[];
  echo json_encode($data);
  $numero_rows = 0;
  echo $total_rows;
  echo $filtro_limit;
  echo "Não existem valores a serem mostrados";
}

Please some help needed. Thank you for the future help.

Upvotes: 1

Views: 33

Answers (2)

Imanuel
Imanuel

Reputation: 3667

Your success function is wrong. The parameter data will contain all the output of your php script. You can't automatically split the output by using different parameters in the function definition.

function success(data, textStatus, jgXHR) {
    console.log(data);
}

Check your console and you'll see your data.

You'll probably want to change your php code:

$result = [
  'out' => json_encode($out),
  'result1' => pg_num_rows($result1),
  'filtro_limit' => $filtro_limit,
  'message' => "Não existem erros",
]
echo json_encode($result);
exit;

and

$result = [
  'total_rows' => $total_rows,
  'filtro_limit' => $filtro_limit,
  'message' => "Não existem valores a serem mostrados",
];
echo json_encode($result);
exit;

That way, you'll have a much easier time to parse the data in JavaScript. For example:

function success(data, textStatus, jgXHR) {
    var message = data.message;
}

Upvotes: 1

Abanoub Makram
Abanoub Makram

Reputation: 461

you have to return all data in one statement in php like this :

echo json_encode(array(
'out'=>$out,
'num_rows'=>pg_num_rows($result1),
'filtro_limit'=>$filtro_limit,
'msg'=>"Não existem valores a serem mostrados"
));

and ajax code like this:

$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
    url: 'teste.php',
    type:'post',
    dataType: 'json',
    data:
        {
            limite: num_Limite_rows,
            tipologia: tipologia_val,
            ordenar_por: ordenar_por_val
        },
    success: function(data)
    {
        $num_rows=data['num_rows'];
    }
});

Upvotes: 1

Related Questions