Kalimero
Kalimero

Reputation: 1

Sending data via AJAX not working - why?

I am creating a jQuery function to send some data via AJAX and then open a div with the result:

<div class="comments_div" id="comments_div" data-id='<?php echo $post_id; ?>' "> 
  More Comments--->
  <div class="comments_more_<?php echo $post_id; ?>" id="comments_more"> 
$(function() {
  $(".comments_div").click(function() {
    var post_id = $(this).attr('data-id');       
    $.ajax({
      url: "jscripts/comment_query.php",
      type: "POST",
      data: post_id,
      success: function(datos) {
        $('.comments_more_' + post_id).html(datos);
        $('.comments_more_' + post_id).show('slow');
        //alert(post_id);
      }
    });
  });
})

alert(post_id) shows the correct post_id. But for some reason it does't send data.

comment_query.php:

<?php
    echo 'post_id: ';
    echo $_POST['post_id'];
?>

The div comment_more opens and show the text "post_id: " (but not the variable).

Upvotes: 0

Views: 42

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

The issue is because you're not providing a key to the post_id value when you send it in the request.

You can either do that using form-urlencoded format:

data: 'post_id=' + post_id,

Or, more preferably, by providing an object which jQuery will serialise and encode for you:

data: { post_id: post_id },

Upvotes: 1

Related Questions