background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Making a synchronous AJAX call using jQuery

Eric.London's picture

I recently was tasked with tracking when a user submitted a form, but in this case, the form was submitted to an external site. Normally, if the form was being submitted locally I could have added a form_alter hook function and modify the submit handlers. The following code snippet will explain how you can add a javascript submit event on the form, and using a synchronous AJAX call, execute server side code before the user leaves the site.

First, I setup a page callback used by the AJAX call to execute my inserted code.

<?php
// define the menu callback item
function MYMODULE_menu() {
 
$items = array();
   
 
$items[] = array(
   
'path' => 'MYAJAXPATH',
   
'title' => NULL,
   
'callback' => '_MYAJAXPATH_callback',
   
'access' => true,
   
'type' => MENU_CALLBACK,
  );
   
  return
$items;
}

// define the menu callback function
function _MYAJAXPATH_callback() {
 
// here, you could add any code you'd like (modify session data, execute some SQL, etc).
   
  // I added the die statement to prevent the theme layer from being executed
 
die;
}
?>

Make sure the page callback works by browsing to it. If you don't output any HTML in your callback function, you should just get a blank page.

Next, you'll need to attach a submit handler to the form and make the synchronous AJAX call.

<?php
$(document).ready(function(){
  $(
'form#FORM-ID-THAT-SUBMITS-EXTERNAL').submit(function(){
    $.
ajax({
     
type: "GET",
     
url: "/MYAJAXPATH",
     
cache: false,
     
async: false,
    });
  });
});
?>

I added a few properties to the AJAX request object to enable this functionality: cache set to false ensures the page request will not be pulled from your browser cache & async set to false will ensure the form is not submitted until the AJAX request is done. jQuery's default AJAX calls are set to asynchronous, which does not guarantee the request will be made before the form is submitted.

Great article!

Thanks for the help! It really helped me!