user2718671
user2718671

Reputation: 2976

How to filter for php error in ajax response?

I want to save some form data in a database via ajax. This ajax function sends the data to my php script:

$('#save_meta').click(function () {
  //some code to get and validate my form values
  "update_meta": {
            "title": new_title,
            "des": new_desc,
            "tags": tag_string,
            "id": id
        }
    };
    $.ajax({
        type: "POST",
        url: base_url + "/wp-content/plugins/my_plugin/my_save_form_content_script.php",
        dataType: "json",
        data: data
    }).complete(function (jqXHR) {
        if (jqXHR.readyState === 4) {
            console.log('success');            
        }
    });
});

This is my php script. It's part of a wordpress plugin so it uses $wpdb functions.

require_once('../../../wp-load.php');
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    if(isset($_POST['update_meta'])){

         $title=$_POST['update_meta']['title'];
         $des=$_POST['update_meta']['des'];
         $tags=$_POST['update_meta']['tags'];
         $id=$_POST['update_meta']['id'];
         global $wpdb;
         $table_name = $wpdb->prefix .'my_database_table';
         $sql = "UPDATE $table_name
         SET des='$des', title='$title', tags='$tags'
         WHERE id=$id";
         $wpdb->query($sql);           

    }
}

That works just fine so far. But there is no feedback when an error occurs. So for example if I would remove the quotation marks in the $sql string around the php variables an error would occur, the data will not be saved. But how could I pass the error as ajax response?

Upvotes: 0

Views: 229

Answers (2)

user2718671
user2718671

Reputation: 2976

I guess I found a way:

When a wpdb query was successful int 0 will be returned. So I added this to the php script:

if($wpdb->query($sql)==0){
    echo "success";
}

And I changed my ajax complete function to this:

...}).complete(function (text) {
    if ($.trim(text.responseText) == "success") {
        alert('success');
    }
});

I had to use trim because there were whitespaces or linebreaks or whatever in the response text. But with this it works.

Upvotes: 0

Matthijn
Matthijn

Reputation: 3234

You don't really. You could expect a certain response (the correct one) and if it is anything other than that. An error has occurred.

Most frameworks will set the HTTP header to 500 if a non-compile error happens. So you could check for that. But if a compilation error occurs that would not work.

Of course in production you shouldn't have compile time errors.

Upvotes: 1

Related Questions