Lord Goderick
Lord Goderick

Reputation: 985

Retrieving JSON data is not working as expected

Below I have a JSON array in my main PHP file. As you can see $firstname_error and $lastname_error are variables which I intend to pass to AJAX in order to have it displayed in two separate divs. At the moment nothing shows up and am unsure why. Any insight is greatly appreciated.

PHP & JSON

if (empty($_POST["City"])) {
    $city_error = "A city required";
}

if (empty($_POST["E-mail"])) {
    $email_error = "E-mail is required";
}

echo json_encode(array("city" => $city_error, "email" => $email_error));

AJAX

$(document).ready(function () {
    $(".form").submit(function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "destination.php",
            data: $(this).serialize(),
            dataType: 'json',
            cache: false,
            success: function (data) {
                if (data.trim() != '') {
                    $('.error4').html(data.city);
                    $('.error5').html(data.email);
                }
            },
            error: function () {

            }
        });
    });
});

.error4 and .error5 currently displays nothing.

Upvotes: 0

Views: 55

Answers (3)

Rwd
Rwd

Reputation: 35200

Since you have dataType: 'json', the data variable passed to your success function is going to be an object so you can't use trim().

To check if the value exists in the response you can use hasOwnProperty on data:

success: function (data) {

    $('.error4').text(data.hasOwnProperty('city') ? data.city : '');
    $('.error5').text(data.hasOwnProperty('email') ? data.email : '');
},

Hope this helps!

Upvotes: 2

Lord Goderick
Lord Goderick

Reputation: 985

Ok, I figured it out. Use if(data !== null) instead of if (data.trim() != '')

Upvotes: 1

Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

I believe your if condition is not true, So try changing your success function like this:

success: function (data) {
    if (data.city.trim() != '') {
        $('.error4').html(data.city);
    } 
    if (data.email.trim() != '') {
        $('.error5').html(data.email);
    }
}

Upvotes: 2

Related Questions