st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 11

jQuery won't read JSON response (using $.post)

In a nutshell, I have a form, which upon submissions, sends data to a serverside script to process a function, return data in JSON format for me to parse and spit back out onto the page.

  1. jQuery sends data to "createUser.php" via the $.post method

    $("#create_submit").click(function(){
        $.post("/createUser.php", {
            create_user_name: $('#create_user_name').val(),
            create_user_email: $('#create_user_email').val(),
            create_user_password: $('#create_user_password').val() },
            function(data){
                alert(data.response);
            }, "json");
    });
    
  2. "createUser.php" returns JSON data

    <?php
    header('Content-type: application/json');
    $return['response'] = 'hmm...';
    echo json_encode($return);
    exit;
    ?>
    

Maybe it's me, but I can't seem to get the alert that I need. What's going on!?

Upvotes: 1

Views: 1211

Answers (2)

William
William

Reputation: 15601

From what I can tell from your answers, JSON is only being outputted when you do the above POST request. If you do a normal GET request it works fine. To test this, change $.post to $.get (and clear the variables create_user_* if need be) and see if you get a response then.

If you do, then you need to check your createUser.php file and see why the POST request returns no JSON, but the GET request does. It looks like this is a PHP issue, not a JavaScript/JSON/jQuery issue.

Upvotes: 0

Pekka
Pekka

Reputation: 449823

I think the data argument to your callback function already is the data, and has no response member.

Try function(data){ alert(data); }

Documentation: jquery.post

Upvotes: 3

Related Questions