Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send or assign Jquery Variable value to php variable?

Tags:

jquery

php

I got the answer from this post [How to send or assign Jquery Variable value to php variable? but somehow my PHP can not get the value passed from Jquery
this is html code

<a href="random.php" id="comp1">comp1</a>
<a href="random.php" id="comp2">comp2</a>
<a href="random.php" id='comp3'>comp3</a>

Jquery code

$('a').click(function(){
    $.ajax({
        type: 'POST',
        url:'random.php',
        data: {name:$(this).attr('id')
    }           
    }).done(function(msg){
        alert(msg)
    })
})

and PHP code

<?php
$id = $_POST['name']  ;
echo $id;

?>
like image 662
user3761386 Avatar asked May 18 '26 11:05

user3761386


1 Answers

I guess you might want to use e.preventDefault(); to prevent the default behavior of a hyperlink. Because your <a tag has a link to random.php which is to jump to another page.

 $('a').click(function(e){
     e.preventDefault();
     .....
 }

Your code could go like this:

$('a').click(function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url:'random.php',
        data: {name:$(this).attr('id')}           
    }).done(function(msg){
     alert(msg);
  });
});

The document of event.preventDefault() is here:
http://api.jquery.com/event.preventdefault/


It might not be the main problem but you don't have to write a href to the random.php like this:

  <a href="random.php" id="comp1">comp1</a>

I guess you could go like this:

  <a href="#" id="comp1">comp1</a>

Or like this:

  <a href="javascript:void(0)" id="comp1">comp1</a>

You might want to read this page:

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Hope this helps.

like image 185
naota Avatar answered May 21 '26 01:05

naota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!