Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery post .fail even when php succeed

I have a problem with my jQuery post request :

$.post(
  'http://localhost/***/ajax_bdd-change.php',
    {'id': _id, 'id_key': id_key, 'table': table, 'data': data})
    .fail(function(jqXHR, textStatus, errorThrown){
      alert('Erreur: '+jqXHR.responseText);
    })
    .done(function(data){
      alert($(data).text());
    });

And my PHP :

<?php
$id     = json_decode($_POST['id']);
$id_key = json_decode($_POST['id_key']);
$table  = json_decode($_POST['table']);
$data   = json_decode($_POST['data']);

foreach ($_POST as $k=>$v) {
  unset($_POST[$k]);
}
$rlt = array(
  'erreur' => false,
  'request' => 'none'
  ); 
$tmp = 0;
$request = 'UPDATE '.$table.' SET';

foreach ($data as $target => $value) {
  if ($tmp++>0)
    $request = $request.',';
  $request = $request.' '.$target.' = "'.$value.'"';
}
$request = $request.' WHERE '.$id_key.' LIKE "'.$id.'"';

$rlt['request'] = $request;

require('BDD_connexion.php');
if (!$rlt_bdd = mysqli_query($link, $request)){
  $rlt['erreur'] = 'Erreur: Update not done';
}
$link->close();

echo json_encode($rlt);
exit();

?>

Everytime I run my code, it follow the same path :

  • PHP is correctly executed
  • jQuery run .fail()
    • jqXHR.responseText is empty

I have try to force php to fail and at that time, the jQuery correctly run the done(function).

  • PHP have some error
  • jQuery run .done()
    • the alert show the php error

I have try many thing like force an UTF8 encode to each php string variable. I even try to impose a simple string like json_encode('hello world');

After many test, it seem my previous informations :

Maybe it is useful to explain that:

  • my javascript is inside a laod() php page.

So it must have a structure like:

  • main.php --jQuery-->load(second.php into a div)
    • second.php --jQuery-->$.post(ajax_bdd-change.php)
    • ajax_bdd-change.php --return $rlt -->second.php(jQuery part)

I do not mention it because I do not find it pertinent.

Is the cause of this problem. I have try a call of my php by post from a new html page without a .load and it is working perfectly.

like image 932
Lolette Avatar asked May 02 '16 13:05

Lolette


1 Answers

The response code, if nothing bad occurred on the server, should be 200.

It's highly likely, based off the observations you've made, that the response code is something other than 200. Also note, jQuery, or any other framework, doesn't know whether custom code, written on the server, was executed coherently. Usually, the only indication to the client is the response code.

jQuery source

like image 113
Alex Avatar answered Oct 26 '22 14:10

Alex