Daniel Kats
Daniel Kats

Reputation: 5554

How to trigger the "error" callback in JQuery AJAX call using in PHP

I have PHP code snippet the following:

if (!($result = mysql_query($query, $link))) {
   die("Invalid SQL query: " . $query);
}

And I have JQuery code snippet the following:

$.ajax({
        url: "....search.php", 
        data: ...,

        async: false, //to trigger error alert

        success: function(xml) {
            ...
        },

        error: function(xml) {
            foundError = true;
        },

        dataType: "xml"
    });

if(foundError) {
        setProgress("Could not complete the search because an error was found", ProgressBar.ERROR);
}

Is it possible to have the die call trigger JQuery error function callback? If not, how would I trigger it otherwise?

Upvotes: 6

Views: 4538

Answers (3)

jeroen
jeroen

Reputation: 91734

You cannot access the ajax error like that as there was no ajax error. What you could do, is check your xml variable in the success section; if it starts with Invalid SQL query you know there was a php error.

To tidy things up, you probably want to return some more information (xml / json) in case of an error instead of just a string.

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77956

Try this:

if (!($result = mysql_query($query, $link))) {
   header("HTTP/1.1 404 Not Found");
}

Choose the error appropriate for your application

Upvotes: 9

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15369

You cannot signal client-side code from the server (at least, not in the way you're expecting).

When using AJAX, best to use proper HTTP response codes and have jQuery act upon those in the error: callback.

Upvotes: 0

Related Questions