Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass data through a hyperlink to a php page using Ajax

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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 class="choice" 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

>Solution :

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 class="choice" 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading