1

I have a jQuery and a PHP file. If in PHP the process was done correctly, it returns 2 (by echo json_encode(2)). I catch it in the jQuery file, and I show a string on a HTM div. I can do This part without any problem.

The thing that is being difficult to me is to return the erorr to ajax, when it occurs, to show on the HTML div. I thought on return a JSON array {"error": "xxx"} where "xxx" was the error generated by php.

So the problem is that I can't get the value of the "error" key to show it. I read a lot of similar topics on the website, but they are about reading values of more than one object.

jQuery file:

$('#log').submit(function(event) {
        event.preventDefault(); 
        var stuff = $(this).serializeArray(); 
        stuff.push({name:'tag', value:'login'});

    $.ajax({
        url: './php/logreg.php', //Como si fuera el action del form
        type: 'post', //Por defecto es get 
        dataType: 'json',
        data: stuff,
        beforeSend: function(){
            $('#span-login-icon').css('display','inline');
        }
    })
    .done(function(data){
        if(data == 2){
            $('#span-login-resp').html('Correcto');
        }
        else{

            $('#span-login-resp').html(data);
        }

    });
});

PHP file:

if($object->queError()  === ''){
    echo json_encode(2);
}
else{

    echo json_encode('{"error"'.':"'.$object->queError().'"'.'}'); //output: {"error":"xxx..."}
}
1
  • Did you tryied checking the key of you json data ? if (data.hasOwnProperty('error')) { /* ... */ } else { /* ... */ } Commented Jan 20, 2016 at 16:25

2 Answers 2

4

Your code returning the error is calling json_encode on a string, which probably isn't what you want, as you'll end up returning a JSON string literal, not the object the text in it defines.

That is, you're currently returning this JSON:

"{\"error\":\"something went wrong\"}"

where you probably want to return this JSON:

{"error":"something went wrong"}

You probably want:

else {
    echo json_encode(array(
        'error' => $object->queError()
    ));
}

(Building JSON strings manually is almost always not your best option.)

Then in your ajax callback

.done(function(data) {
    if (data == 2){
        $('#span-login-resp').html('Correcto');
    }
    else {
        $('#span-login-resp').html(data.error);
        //                             ^^^^^^---------------- Note
    }
});

Or possibly:

.done(function(data) {
    if (data && data.error){
        $('#span-login-resp').html(data.error);
    }
    else if (data == 2) {
        $('#span-login-resp').html('Correcto');
    }
    else {
        $('#span-login-resp').html('Ocurrió un error inesperado');
    }
});

Alternately, in keeping with the style of your success return (just the number 2), you could just return a string:

echo json_encode('error: ' . $object->queError());

and then

.done(function(data) {
    if (data == 2){
        $('#span-login-resp').html('Correcto');
    }
    else {
        $('#span-login-resp').html(data);
    }
});

FWIW, even though it's no longer required, I would probably return an object with either an error property (containing the error) or a result property (containing the 2).

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

2 Comments

Yes, I read"{\"error\":\"something went wrong\"}" in the response of the .php file using the developer tools of Chrome. But if I show the data directly in the HTML div I see {"error":"something went wrong"} without the slashes. This is disconcerting. In a moment I'll try your code. Thanks a lot.
@Pablo: Right, the backslashes are escape characters in JSON, letting us write " inside a string literal (just like JavaScript string literals when we use double quotes for them).
2

Try this:

PHP last line:

echo json_encode( array("error" => $object->queError()) );

JS last line:

$('#span-login-resp').html(data.error);

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.