tags:

views:

55

answers:

4

I'm sending a $.post request to php with jQuery. The jQuery code looks like this:

$('form').submit(function() {

    username = $('input[name="username"]').val();
    alert(username);
    $.post('/ajax/new_user.php', {username:username}, function(data) {
        alert(data);
    });


});

In PHP, I'm just trying to do this for now:

<?php

echo $_POST['username'];

?>

The first alert in jQuery worked and prints the correct value, however the alert(data) always alerts and empty string ("").

The file path is correct. I'm doing many other AJAX requests on my site that work perfectly so I'm not sure what makes this one so different. Any help is greatly appreciated!

+1  A: 

should not

 $.post('/ajax/new_user.php', {username:username}, function(data) { 
        alert(data); 
    }); 

be

 $.post('/ajax/new_user.php', {"username":username}, function(data) { 
        alert(data); 
    }); 
Mark Schultheiss
Didn't change anything, but thanks for the suggestion!
WillyG
Just for the record, that's a somewhat common misconception. The first example is a perfectly valid object literal, which can be used anywhere in your client side code. It's not, however, valid JSON (which is what you fixed in the second example). Having valid JSON is primarily important when you're rendering it to a response that will be consumed/parsed as a JSON service (or similar)...
jmar777
+1  A: 

Try replacing

{username:username}

with

{'username':username}

If that doesn't work, replace the contents on your PHP file with:

<?php

print_r($_POST);

?>

So you can see if you're even getting the data.

Kranu
Nope...but thanks for the suggestion!
WillyG
What's the output of the print_r?
Kranu
The print_r() just does the same thing, and when I navigate to the PHP file directly, it shows Array()
WillyG
A: 

Pixeline's comment solved my problem, all I had to do was return false at the end of the submit.

WillyG
+3  A: 

So. The answer was adding a

return false;

at the end of the submit() event.

pixeline
Nice catch! I can't believe I didn't see something so obvious q:
Kranu