views:

193

answers:

2

Hi All,

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!?

+3  A: 

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

Pekka
pekka, like i noted above, the alert doesn't even pop up when i have the "json" parameter in the $.post method...however when i take that optional parameter out, the alert seems to work (though it doesnt alert the data, just says 'undefined'
st4ck0v3rfl0w
Make sure you're checking your JavaScript error log. It might be giving you a JavaScript error when alerting data.response because it doesn't exist.
William
Did you look at the json post example in the docs (bottom)? If you specify data type you do not access the response. Since you know that's wrong, take it out of your example, try again, and update your question if you're still having an issue. If it's not that, it seems like the most likely culprit is invalid json.
floyd
A: 

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.

William