Lolette Lolette - 6 months ago 18
PHP Question

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.

Answer

I have find a resolution. In fact, my code is more complex, and the jQuery .post is done in a .submit of a <form> inside the script part of an jQuery DialogBox. So the form was finished to submit before the php response when this on have a Database Query.

In resolution I change this submit with just a .click, and I manualy close when I recive a response from the server.

Comments