How to make an AJAX request by clicking on the link don’t send a button

How can I do AJAX REQUEST by clicking a link instead of a submit button? I want, as soon as the link is clicked on the POST data from the input fields

+3
source share
4 answers
$('selector').click(function(e){
  e.preventDefault();
  $.ajax({
       url: "<where to post>",
       type: "POST",//type of posting the data
       data: <what to post>,
       success: function (data) {
         //what to do in success
       },
       error: function(xhr, ajaxOptions, thrownError){
          //what to do in error
       },
       timeout : 15000//timeout of the ajax call
  });

});
+9
source

Here's how AJAX works:

$('#link_id').click(function(event){
   event.preventDefault(); // prevent default behavior of link click
   // now make an AJAX request to server_side_file.php by passing some data
   $.post('server_side_file.php', {parameter : some_value}, function(response){
      //now you've got `response` from server, play with it like
      alert(response);
   });
});
+2
source

With jQuery

$('#link-selector').on('click', function(event) {
    event.preventDefault();
    $.post('url', {$('form selector').serialize()}, function(json) {
        // proccess results
    }, 'json');
});
+1
source

You can use jQuery functions for users and form serialization functions

$('#A-id-selector').click(function() {
    $.ajax({
        type:'POST', 
        url: 'target.url', 
        data:$('#Form-id-selector').serialize(), 
        success: function(response) {
          // Any code to execute on a successful return
        }
    });
});
+1
source

All Articles