Home > Blockchain >  How to pass data through a hyperlink to a php page using Ajax
How to pass data through a hyperlink to a php page using Ajax

Time:12-20

I am trying to pass data from a hyperlink to a page via a get request using Ajax

Initially I am able to do this without Ajax directly as below

 <a id="link" href="page.php?id=12&pid=12" >pass data</a>

and I catch below in php

<?php $_GET['id'] ?>
<?php $_GET['pid']?>

now I want to do this using Ajax so the page does not need to load

I am trying with the below

 <a  id="link" href="page.php?id=12&pid=12" >pass data</a>

$(document).ready(function() {
          
                $(".choice").click(function(e) {
                    e.preventDefault();
                    $.ajax( {
                        <!--insert.php calls the PHP file-->
                        url: "votes.php",
                        method: "get",
                       dataType: 'html',
                        success: function(strMessage) {
                            $("#vote").html(strMessage);
                          
                        }
                    });
                });
            });

but I am unable to get this to work. I need help on the correct implementation of send data using Ajax to my php file

CodePudding user response:

First of all, a <script> tag is required for JavaScript part. Ajax URL can read from <a> tag href attribute by $(this).attr('href'). Also based on your code, a div with vote id is needed so <div id="vote"></div> added.

<a  id="link" href="page.php?id=12&pid=12" >pass data</a>
<div id="vote"></div>
<script>
$(document).ready(function() {
    $(".choice").click(function(e) {
        e.preventDefault();
        $.ajax( {
            url: $(this).attr('href'),
            method: "get",
           dataType: 'html',
            success: function(strMessage) {
                $("#vote").html(strMessage);
              
            }
        });
    });
});
</script>
  • Related