Send an AJAX request by clicking the link without redirecting the user

I have a web application that contains a bunch of different elements that are generated from a MySQL table. When users scroll it, I want them to be able to click the link next to the item that will insert the query into the MySQL database. Usually Id does this by creating a PHP page (which I will do anyway) that grabs the element name and user ID from the URI using the $ _GET method and inserts it into the table. However, in this case, I do not want users to be redirected from wherever they are. I just want the link to send a request and maybe display a small message after it has completed successfully.

I realized that jQuery / AJAX would be better for this, but since I'm not too familiar with it, I'm not sure what to do. Any advice is appreciated!

+5
source share
3 answers

You should 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 the link without redirecting. Here are the docs for $. Post

EDIT - pass the jQuery value 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
});
+12
source

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;    
});
+3
source

See http://api.jquery.com/jQuery.ajax/

$('#my-link').click(function(){
    $.ajax({
      url: "mypage.php",
      context: document.body,
      success: function(){
        $(this).addClass("done");
      }
    });
    return false;
});
0
source

All Articles