Tag Archives: javascript

JQuery – Detect AJAX Requests with PHP

Certainly, for the huge majority of our projects, we can’t only rely on JavaScript for things like validation, or AJAX requests. What happens when JavaScript is turned off? For this very reason, a common technique is to detect whether an AJAX request has been made with your server-side language of choice.

jQuery makes this ridiculously simple, by setting a header from within the $.ajax method.

 // Set header so the called script knows that it's an XMLHttpRequest
 // Only send the header if it's not a remote XHR
 if ( !remote ) {
 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
 }
 

With this header set, we can now use PHP (or any other language) to check for this header, and proceed accordingly. For this, we check the value of $_SERVER['HTTP_X_REQUESTED_WITH'].

JQuery – Passing an Attribute Object

As of jQuery 1.4, we can now pass an object as the second parameter of the jQuery function. This is helpful when we need to insert new elements into the DOM. For example:

Before

    $('')
      .attr({
        id : 'someId',
        className : 'someClass',
        href : 'somePath.html'
      });

After

    $('', {
        id : 'someId',
        className : 'someClass',
        href : 'somePath.html'
    });

Not only does this save a few characters, but it also makes for cleaner code. In addition to element attributes, we can even pass jQuery specific attributes and events, like click or text.

JQuery – A Single Hover Function

As of jQuery 1.4, we can now pass only a single function to the hover method. Before, both the in and out methods were required.

Before

$('#someElement').hover(function() {
// mouseover
}, function() {
// mouseout
});

Now

 $('#someElement').hover(function() {
 // the toggle() method can be used here, if applicable
 });
 

Note that this isn’t an old vs. new deal. Many times, you’ll still need to pass two functions to hover, and that’s perfectly acceptable. However, if you only need to toggle some element (or something like that), passing a single anonymous function will save a handful of characters or so!