Alegro
Alegro

Reputation: 7956

How to check data content inside $.post function?

$.post(
    $("#formReg").attr("action"), $("#formReg").serialize(),
    function(data, textStatus, jqXHR) {
            $("#info").html(data);
        alert (data); // to check - ok - `folder` is displaying
        if ($("#info").html() == "folder"){
        $("#imgOk").fadeIn();  //doesn't work
        }
});

Seems like #info has another content and not folder, although is checked by alert, and folder is visible on screen as the content.

Upvotes: 1

Views: 100

Answers (1)

adeneo
adeneo

Reputation: 318182

Sometimes when doing ajax requests, you'll have code on the server that inserts whitespace in the returned results. It's not always easy to see where the whitespace is added, but it could be a space before or after the code, like having a single space before <?php in PHP etc.

The best thing would be to simply remove the space on the serverside, but javascript also has a trim method that will trim following and trailing whitespace from a string:

if ($("#info").html().trim() == "folder"){...}

That function is not supported in older browsers, so if that's an issue you can use a regex, or since you're already using jQuery you can use a similar cross browser function, and it actually uses the same native trim() method in newer browsers, and regex in older browsers, so you don't have to worry about it:

$.post($("#formReg").attr("action"), $("#formReg").serialize(), function(data) {
    $("#info").html(data);
    if ($.trim(data) == 'folder') $("#imgOk").fadeIn();
});

Upvotes: 1

Related Questions