Alexis
Alexis

Reputation: 209

Sending GET requests to same page with jquery

Lets say there is a php code

page.php

<a href="page.php?pid=1" id="1">Product 1</a>
<a href="page.php?pid=2" id="2">Product 2</a>

<?php 
$_GET['pid'];
if(!isset($_GET['pid'])){
    $stmt=$mysqli->prepare("SELECT * FROM products WHERE id=?");
    $stmt->bind_param("i",$_GET['pid']);
    $stmt->execute();
?>
<table>
    <tr><td>*show products code*</td></tr>
</table>
<?php } ?>

Now what I'm thinking that is there any solution that when I click on anchor tags, the page wouldn't refresh instead it stays there and send value to the $_GET['pid'];

A bit of jquery ajax part I thought of is this

$('a').click(function()
{
    $.ajax(
    {
        url: 'page.php',
        method: 'GET',
        data: $(this).attr('id').serialize(),
    });
});

It didn't work and I do not fully understand how would I send data to $_GET['pid']

Any help with a bit of explanation would gladly help me a lot...

Upvotes: 0

Views: 196

Answers (1)

Dmitrii Korchemkin
Dmitrii Korchemkin

Reputation: 197

You can do

$('a').click(function(event){
   $.ajax({
      url: 'page.php?pid=' + $(this).attr('id'),
      method: 'GET'
   });
  event.preventDefault();
});

or

$('a').click(function(event){
   $.ajax({
     url: $(this).attr('href'),
     method: 'GET'
   });
   event.preventDefault();
 });

PS I recommend codestyle like this, because js interpreter puts the ";":

Upvotes: 1

Related Questions