0

I have a PHP script that breaks if a variable is not populated and it isn't added to the database, but jQuery handles this as a success and I get this error:

TypeError: Result of expression 'data' [null] is not an object.

Here's the jQuery script:

$.ajax({
    type: "POST",
    url: "/clase/do-add",
    data: $("#adauga").serialize(),
    dataType: "json",
    error: function (xhr, textStatus, errorThrown) { 
        alert('Try again.');
    },
    success: function(data) {
        var dlHTML = '<dl id="' + data.id + '"> [too long] </dl>';
        $('form#adauga').after(dlHTML);
        $('#main dl:first').hide().fadeIn();

        adaugaClasaSubmit.removeAttr('disabled');
        adaugaClasa.removeAttr('readonly');
        adaugaClasa.val("").focus();
    }
});
1
  • What is your question? What does your PHP script do when it fails? Commented Dec 24, 2010 at 16:52

2 Answers 2

3

The problem is that jQuery's concept of "error" is an HTTP error, not an error that you have noted yourself. If the HTTP response code is <400, jQuery will use your success callback. Your options are (a) to use PHP to give an error in your HTTP response

header("HTTP/1.0 500 Internal Server Error");

or (b) to do your error handling in the success handler:

success: function(data) {
    if (!data) {
        // do your error code here
    } else {
        // do your success code here
    }
}

I prefer the first option, with HTTP response codes, to allow your code to make the best logical sense to a future editor (which may be you!).

Sign up to request clarification or add additional context in comments.

Comments

0
success: function(data) {
        if(data!=null){
        ...
        }
}

try this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.