PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How to pass data through a hyperlink to a php page using Ajax

 September 06, 2022     ajax, php     No comments   

Issue

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 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>


Answered By - Amirreza Noori
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing