Removing unwanted output from ajax responses

Ernest Marcinko jQuery, Tutorials 1 Comment

This article is might be helpful to WordPress or other CMS plugin developers, where your plugin/module/theme get’s to meet with lot’s of other 3rd party plugins/modules/themes. It’s a great thing, that these CMS systems give you the opportunity to build your website, however these 3rd party applications might not work together well, no one can guarantee that.

Often times I see these plugins conflicting with each other, mostly because of poor coding. When it comes to ajax, you must prepare yourself, because if a notice, warning or some random output swoops in before or after your request, it’s over. Most CMS systems fire up all the plugins before handling your ajax request, so nothing is stopping them to throw notices or print something, that you might not expect, thus poisoning your ajax response.

My very simple solution

On the server side put your response text between delimiters:


function ajax_response() {
    $l_delimiter = "!!START!!";
    $r_delimiter = "!!END!!";

    // Do your stuff here
    $response = json_encode(array('hi' => 'Hi dude!'));    

    print $l_delimiter . $response . $r_delimiter;
}

On the client side, fetch the data between the delimiters:


/**
 * jQuery example
 *
 * Note that the request is handled as text, and then converted to JSON
 * */

var post = $.post('http://ajax.url.here', data, function (response) {

    // You can of course merge these lines
    response = response.replace(/^\s*[\r\n]/gm, "");
    response = response.match(/!!START!!(.*[\s\S]*)!!END!!/)[1];
    // If you don't need JSON, just skip the line below
    response = JSON.parse(response);

    // Here the response is in the expected JSON format
    console.log(response.hi);  // prints "Hi dude!" to the console

}, "text");

This solution might look unusual, but it works really well. You can of course try to play with output buffering on the server side, but I personally prefer this solution instead.

Comments 1

Leave a Reply

Your email address will not be published.