getaway getaway - 1 month ago 10
Ajax Question

passing data to an ajax request jquery?

When i am trying to send data through ajax, its not passing data

$('#savenew').click(function () {
var user = <?php echo $user?>;
$.ajax({
type: "POST",
url: "actions/sub.php",
data: user,
success: function () {
$('#savenew').html('<span>Unsubscribe</span>');
$(this).removeAttr('id');
$(this).attr('id', 'clean');
}
});
});


My PHP code on receiving end,

if ($_POST['user']) {
$user = $_POST['user'];
}


Am i doing something wrong ? Please help.

Answer

This:

data: user,

should be

data: {user: user},

Because you're looking for a POST variable called "user" and using its value. jQuery will accept an object literal and serialize it into POST data using the property names as keys and the property values as values. The nice thing about using an object (literal or otherwise) is that then jQuery handles doing the encoding of the values for you. You can use a string (data: "user=" + user), but then you have to worry about doing the encodeURIComponent part yourself for string parameters (no need for this numeric one).

You can also just do it all in one, with no user variable on the client side:

$('#savenew').click(function(){
    $.ajax({
        type: "POST",
        url: "actions/sub.php",
        data: {user: <?php echo $user?>},
        success: function(){
            $('#savenew').html('<span>Unsubscribe</span>');
            $(this).removeAttr('id');
            $(this).attr('id', 'clean');
        }
    });
});

...although having the user variable client-side is harmless, and of course if you want to use it in more than one place...

Comments