Skip to content
Advertisement

AJAX: How to send back a success/error message

This is my first baby step with Ajax and I’m already struggling. I have a request that inserts into the DB but my code for the moment is behaving like all the requests are successful, but I want to be able to handle the errors when updating the DB. I want to alert() a success/error message depending on the MYSQL response.

My Ajax call:

$("a.bgbtb").click(function(){
  var btnid = $(this).attr("id").split('newbudbtn-')[1]; 
  var newbudget = $("INPUT[id=newbud-"+btnid+"]").val(); 
  var platform = $("span#"+btnid).text(); 
  $.ajax({
    url:"campbdgtedit.php", 
    method:"POST",  
    data:{platform:platform, btnid:btnid, newbudget:newbudget},  
    success:function(data){
        myAlertTop();
    }
  });
});

campbdgtedit.php:

$query = "INSERT INTO campaigns (camp_budget, camp_campaignid) VALUES ('".$_POST['newbudget']."', '".$_POST['btnid']."')";

if ($conn->query($query) === TRUE) {
    echo "Success<br/>";
} else {
    echo "Error: " . $query . "<br>" . $conn->error;
}

How can I catch if there is an error in the query and handle my alerts accordingly? I’ve tried many solutions I’ve found here but I can’t seem to make them work.

Advertisement

Answer

I would recommend returning JSON from your PHP code, this can be interpreted directly as an object in the JavaScript if you use dataType: 'json' on your ajax call. For example:

if ($conn->query($query) === TRUE) {
    echo json_encode(array('success' => true));
} else {
    echo json_encode(array('success' => false, 
                           'message' => "Error: Insert query failed"
                           )
                     );
}

Note that in general it’s not secure to pass back query details and connection errors to the end user, better to pass back a generic message and log the actual error to a file or other location.

In your JavaScript:

$("a.bgbtb").click(function(){
  var btnid = $(this).attr("id").split('newbudbtn-')[1]; 
  var newbudget = $("INPUT[id=newbud-"+btnid+"]").val(); 
  var platform = $("span#"+btnid).text(); 
  $.ajax({
    url:"campbdgtedit.php", 
    method:"POST",  
    data:{platform:platform, btnid:btnid, newbudget:newbudget},  
    dataType: 'json',
    success:function(data){
        if (data.success) {
            // all good!
            myAlertTop();
        }
        else {
            // problems
            alert(data.message);
        }
    }
  });
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement