Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send AJAX request by clicking a link without redirecting user

Tags:

jquery

php

mysql

I have a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.

I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!

like image 593
Andrew De Forest Avatar asked Mar 08 '12 18:03

Andrew De Forest


2 Answers

You have to do something like

$('.classofyourlink').click(function(e){
  e.preventDefault();//in this way you have no redirect
  $.post(...);//Make the ajax call
});

in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post

EDIT - to pass the value to jQuery in your case you should do something like

$('.order_this').click(function(e){
  e.preventDefault();//in this way you have no redirect
  var valueToPass = $(this).text();
  var url = "url/to/post/";
  $.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});
like image 93
Nicola Peluchetti Avatar answered Nov 08 '22 21:11

Nicola Peluchetti


HTML

<a id="aDelete" href="mypage.php">Delete</a>

Script

$(function(){    
   $("#aDelete").click(function(){           
      $.post("ajaxserverpage.php?data1=your_data_to_pass&data2=second_value",function(data){
         //do something with the response which is available in the "data" variable
     });
   });
  return false;    
});
like image 34
Shyju Avatar answered Nov 08 '22 21:11

Shyju