Alexis Alexis - 25 days ago 5
Javascript Question

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

Answer

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 ";":