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

前端 未结 3 2084
野趣味
野趣味 2020-12-21 06:29

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 co

相关标签:
3条回答
  • 2020-12-21 07:00

    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.

    0 讨论(0)
  • 2020-12-21 07:13

    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.

    0 讨论(0)
  • 2020-12-21 07:19

    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
        });
    });
    
    0 讨论(0)
提交回复
热议问题