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:

JavaScript

campbdgtedit.php:

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement