Why can not I get the value when calling jquery / ajax on a link click?

advertisements

In my website I have a link where user id is store like this :

<p>by <a href="#" onclick="ofUser(<?php echo $uid; ?>, event);"><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</a></p>

Here you can see variable $uid. This is the user id. So I want to make ajax call when I click on this link. It's should get the value of $uid to result page ofUser.php. But in result page (ofUser.php) it's showing :

Undefined index: id

Can you tell me how can I solve it ?

Here is the JS offUser function

function ofUser(id, event){
  id = $(id);
  event.preventDefault();
  var formData =  id;
  $.ajax({
    url :  <?php echo "'ofUser.php'"; ?>,
    type : 'POST',
    xhr : function () {
      var myXhr = $.ajaxSettings.xhr();
      return myXhr;
    },
    beforeSend : function () {
      $("#ofUser_message").val("Searching...");
    },
    success : function (data) {
      $("#danger").hide();
      $("#bydault_pagination").hide();
      $("#bydeafult_search").hide();
      $("#ofUser_message").html(data);
    },

    data: formData,
    cache: false,
    contentType: false,
    processData: false
  });
}

offUser.php

echo $uid = (int) $_POST['id'];


id = $(id); will cast id to jQuery object which is not making any sense here. It will make id as array(id=$(1) => [1])

Also note, your data being sent over server should be an object.

Try this:

function ofUser(id, event) {
  event.preventDefault();
  $.ajax({
    url: 'ofUser.php',
    type: 'POST',
    xhr: function() {
      var myXhr = $.ajaxSettings.xhr();
      return myXhr;
    },
    beforeSend: function() {
      $("#ofUser_message").val("Searching...");
    },
    success: function(data) {
      $("#danger").hide();
      $("#bydault_pagination").hide();
      $("#bydeafult_search").hide();
      $("#ofUser_message").html(data);
    },

    data: {
      id: id
    },
    cache: false
  });
}

Edit: Remove processData : true as it will send data as DOMDocument