3

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;

?>
Community
  • 1
  • 1
user3761386
  • 49
  • 2
  • 10

3 Answers3

2

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.

Community
  • 1
  • 1
naota
  • 4,695
  • 1
  • 18
  • 21
1

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
    });
});
Burak
  • 5,252
  • 3
  • 22
  • 30
  • can you tell me what my error is ? because I have been checking for errors but I haven't seen anything – user3761386 Jul 05 '14 at 12:58
  • sorry my bad, on my local computer i forgot to add the `}` , you just need to add return false to prevent from browsing and going to the `random.php` page. – Burak Jul 05 '14 at 13:00
1

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.

Danijel
  • 12,408
  • 5
  • 38
  • 54