Skip to content

Instantly share code, notes, and snippets.

@wkw
Created November 23, 2014 18:36
Show Gist options
  • Select an option

  • Save wkw/789a3712cda787f62dbd to your computer and use it in GitHub Desktop.

Select an option

Save wkw/789a3712cda787f62dbd to your computer and use it in GitHub Desktop.
While building a WordPress BackboneJS Admin app, I found that some errant plugins are improperly injecting content into the ajax response stream when they should not (e.g., styles, or snippets of javascript). Also, if WordPress error reporting it turned on, you may be getting PHP notices/warnings. All of this causes the json response to fail to …
Backbone.$.ajaxSetup({
// look for invalid json responses
dataFilter: function(data, type){
var d = null;
//-------------------------------------------
function tryParse(resp){
try {
JSON.parse(resp);
}catch(err){
console.log("%c-->JSON Parse Error: %s","color:red;", err);
console.log("----Raw response snippet-----\n",snippet(resp).replace(/\s+[\r\n]/g, ""), "\n-------------------");
return false;
}
return resp;
}
function snippet(str){
var len = str.length > 100 ? 100 : str.length;
return str.substr(0,len);
}
//----------- handle response -----------
// ignore non-json responses
if(type !== 'json'){
return data;
}
// ignore if url does not contain '/wp-json/'
if( "undefined" === typeof this.url || this.url.indexOf("/wp-json/") === -1 ){
return data;
}
if( false === tryParse(data) ){
console.log("-->Attempting to fix data...");
d = data.substr(data.indexOf( "[{" ));
return tryParse(d);
}
return data;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment