1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

@getaway: Ah, good; I've removed the string part of the answer.
thanks it works, can i ask you, if i wanted to make this ajax request secure, what shall i avoid or do :) thanks +1 from me
@getaway: No worries. The question of how to make the request secure is different enough from this question that I'd ask it separately. (Also, I think it's probably already been answered on SO, so search around a bit first. FWIW, I find SO's own search feature to be pretty unreliable, so instead I use Google with "site:stackoverflow.com".)
cheers! thanks i will take that into mind, i will accept your answer when it lets me :))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.