user3761386
user3761386

Reputation: 49

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

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;

?>

Upvotes: 3

Views: 3741

Answers (3)

Danijel
Danijel

Reputation: 12689

HTML:

<a href="javascript:;" id="comp1">comp1</a>
<a href="javascript:;" id="comp2">comp2</a>
<a href="javascript:;" id='comp3'>comp3</a>

JS:

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

Use href="javascript:;" attr, or e.preventDefault(); inside event handler, to prevent the link executing.

Upvotes: 1

naota
naota

Reputation: 4718

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.

Upvotes: 2

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

Try this, you need to prevent onclick action to go to the that page.

$(document).ready(function() {
    $("a").click(function() {
        $.ajax({
            type: "POST",
            url: "random.php",
            data: {"name" : $(this).attr('id')}
        }).done(function( msg ) {
           alert( "Data Saved: " + msg );
       });
    return false; // prevent from browsing that page
    });
});

Upvotes: 1

Related Questions