getaway
getaway

Reputation: 8990

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.

Upvotes: 1

Views: 1417

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

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...

Upvotes: 3

Related Questions