0

I am trying to pass a jquery variable to a PHP variable and then retrieve that variable so I can use it in a php function. The jquery variable is a string and after I pass to PHP and retrieve and echo it, I get nothing.

Here is my simplified code from test.php file.

<?php
 $senderid = $_POST['senderid']; 
 echo $senderid; //I get nothing here.
?>

<script>
$('a.send').on('click', function( event ) {
event.preventDefault();
var href = $(this).attr('href');
var senderID = parseInt(href.split('sender_id=')[1]);

    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: {senderid: senderid},
        success: function(){
          jQuery('.test').text('<?php echo $senderid; ?>'); ///nothing here
        }
    });
});
</script>
LearntoExcel
  • 129
  • 2
  • 15
  • you are not gettion nothing there because your post variable sender id may be null.. – SAMUEL Jan 04 '17 at 06:13
  • 1
    what version of jQuery are you using? `live()` has been deprecated for years – charlietfl Jan 04 '17 at 06:13
  • You can do it as `$('.popup').attr('id', senderid);` – Mohit Bhardwaj Jan 04 '17 at 06:13
  • process the response, add a success callback and make your attribute changes inside – Kevin Jan 04 '17 at 06:13
  • php runs before your page is rendered in your html. Once your page is rendered, you need to update your DOM using JS/jQuery. – Mohit Bhardwaj Jan 04 '17 at 06:14
  • @charlietfl Hi, that I understand. I am still learning. Should be using "on"(click), correct? – LearntoExcel Jan 04 '17 at 06:19
  • @MohitBhardwaj Hi please see updated code. I know I can just use the jquery variable but I need it converted into a php variable anyway because I will use it in a php function. – LearntoExcel Jan 04 '17 at 06:20
  • yes...in versions >= 1.7. Syntax is slightly different though for `on()` vs `live()`...see docs – charlietfl Jan 04 '17 at 06:20
  • @Ghost When I add a success callback and try to change the variable inside, nothing happens still. What am I missing? – LearntoExcel Jan 04 '17 at 06:34
  • @MohitBhardwaj Hi, would you mind taking a look at my updated code? – LearntoExcel Jan 04 '17 at 06:41
  • Firstly, `data: {senderid: senderid},` should be `data: {senderid: senderID},` because you have declared this as `var senderID`. After that, I don't think you need to use php at all to echo the variable here. You have the senderID and you can update it using jQuery alone: `jQuery('.test').text( senderID );`. Please try this once. – Mohit Bhardwaj Jan 04 '17 at 06:56

0 Answers0