Andrew De Forest
Andrew De Forest

Reputation: 7338

Send AJAX request by clicking a link without redirecting user

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!

Upvotes: 6

Views: 19022

Answers (4)

Muh.Baqir Amini
Muh.Baqir Amini

Reputation: 1

$('.classOfYourLinkToBecliked').click(function(){
       $.ajax({
          type:'GET',
          'url':'yoururl',
           data: {yourdata},
           processData: false,
           contentType: false,
           cache: false,
           dataType: 'json',
           success: function(response){
             alert(response);
             }
      });
});

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

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
});

Upvotes: 13

Shyju
Shyju

Reputation: 218722

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;    
});

Upvotes: 3

dotoree
dotoree

Reputation: 2993

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;
});

Upvotes: 0

Related Questions