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.

Ernest Marcinko

WordPress developer, javascript enthusiast, photoshop clicker and the founder of wp-dreams.com

Stay connected

Related Posts
Filter by
Post Page
Blog Commercial Plugins Wordpress Tutorials Wordpress jQuery Free Plugins Hosting
Sort by

Ajax Search Pro Nulled

2015-01-15 09:50:16
admin

18

Using Ajax in your WordPress plugins

2014-04-14 13:23:29
admin

18

Ajax Search Pro for WordPress

2012-11-06 19:27:10
admin

18

Saving space automatically – Beginners guide to Digital Ocean

After a while, you will notice an exponential growth of used space, without even copying anything to it. How
2016-05-06 09:24:05
admin

8

Comments 1

Leave a Reply

Your email address will not be published. Required fields are marked *