1
$(document).ready(function(){
    $('#list li').click(function(){
        var ID= $(this).attr('id');
        $.post("index.php", ID, 
            function(){
                $("#category").html(ID);
            }
        );
    });
});

This code shows my selected list ID in html <div id="category">.

Question

Is there any way to post that data directly to PHP code and echo it? I need data in php, because I want to use it in my query.

3 Answers 3

0
$.ajax({
  type: "POST",
  url: 'index.php',
  data: { id: ID }, // name of the post variable ($_POST['id'])
  success: function(data) {
     console.log('successfully posted data! response body: ' + data);
  }
});
0

Maybe you can use ajax:

$('#list li').click(function(){
var ID = $(this).attr('id');
$.ajax(
   url:"index.php", //Page with data
   data:{id: ID},
   type: "POST", //You can use any method POST, GET, DELETE, PUT...
   success:function(result){
      $("#category").html(result);
   });
});
0

You aren't sending a key/value pair ... only a value.

You also have not added the argument for the response in the completion callback

Change

$.post("index.php", ID, function(){
     $("#category").html(ID);
});

To

$.post("index.php", {id: ID}, function(response){ //object used for key/value pairs
      $("#category").html(response.data);
},'json')
.fail(function(error){
      alert("Ooops ..something went wrong");
});

Then for simple php test

echo json_encode(array('data'=>'The ID sent was '. $_POST['id']));
6
  • Am getting error Notice: Undefined index: id on this line at my code: echo json_encode(array('data'=>'The ID sent was '. $_POST['id']));
    – Darius92
    Commented Feb 28, 2016 at 16:50
  • Did you use object the same way I showed? In browser dev tools (F12) network can inspect exactly what was sent. Could also do a dump of $_POST and see what it looks like in response body of request in dev tools or log it to console in callback
    – charlietfl
    Commented Feb 28, 2016 at 17:00
  • Am getting error alert("Ooops ..something went wrong"); I added if (isset($_POST['id'])) line before echo json_encode(array('data'=>'THE id sent was'.$_POST['id'])); and It looks like variable is not posted at all
    – Darius92
    Commented Feb 28, 2016 at 17:53
  • what do you see in browser console when you dump $_POST?
    – charlietfl
    Commented Feb 28, 2016 at 17:55
  • The code works in mozzilla network preview mode, but in the main window after i select my list row, am getting .fail(function(error) message and THE id sent was'.$_POST['id']) is not shown
    – Darius92
    Commented Feb 28, 2016 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.