jQuery ajax before beforeSend - javascript

I am trying to add some custom code to jQuery's beforeSend.
To do so I came up with this code :
(function( $ ){
$.ajax_overlay = function(settings, overlay_selector, target_selector, class_active, class_deactive) {
var $overlay = $(overlay_selector);
function overlay_before(user_beforesend){
if ( target_selector === undefined )
{
var $body = $('body');
$overlay.height($body.height()).width($body.width()).css("position","absolute");
}
else{
var $target= $(target_selector);
$overlay.height($target.height()).width($target.width()).css("position","absolute");
$target.css("position","relative").append($overlay);
}
if (typeof(class_active) == "string"){
$overlay.addClass(class_active)
}
if (typeof(class_deactive) == "string") {
$overlay.removeClass(class_deactive)
}
$overlay.css("display","block").animate(
{
opacity: 0.8
},
500);
if (typeof(user_beforesend) == "function"){
user_beforesend();
}
}
function overlay_complete(user_complete){
if (typeof(class_active) == "string"){
$overlay.removeClass(class_active);
}
if (typeof(class_deactive) == "string") {
$overlay.addClass(class_deactive);
}
$overlay.animate(
{
opacity: 0.0
},
500, function(){
$overlay.css("display","none");
});
if (typeof(user_complete) == "function"){
user_complete();
}
}
if (typeof(overlay_selector) == "string"){
settings["beforeSend"] = overlay_before(settings["beforeSend"]);
settings["complete"] = overlay_complete(settings["complete"]);
}
return jQuery.ajax(settings);
}
})( jQuery );
The main idea is to add an overlay on each ajax request using this plugin.
The issue I am facing is that I can't keep the original behaviour of the beforeSend parameter as it expects an xhr and settings paramters.
How can I get a proper xhr to feed to my beforeSend function ?
EDIT:
Found some interesting links/answers related to this onee
Adding code to a javascript function programmatically
Overriding a JavaScript function while referencing the original

Having your overlay_before return a function with expected parameters, and propagate these parameters to the user_beforesend call, should do the trick :
function overlay_before(user_beforesend){
return function(xhr, settings)
{
if ( target_selector === undefined )
{
var $body = $('body');
$overlay.height($body.height()).width($body.width()).css("position","absolute");
}
else{
var $target= $(target_selector);
$overlay.height($target.height()).width($target.width()).css("position","absolute");
$target.css("position","relative").append($overlay);
}
if (typeof(class_active) == "string"){
$overlay.addClass(class_active)
}
if (typeof(class_deactive) == "string") {
$overlay.removeClass(class_deactive)
}
$overlay.css("display","block").animate(
{
opacity: 0.8
},
500);
if (typeof(user_beforesend) == "function"){
user_beforesend(xhr,settings);
}
}
}

Have you tried var xhr = new XmlHttpRequest();? Or are you looking for something more/different?

Related

how to use noConflict for 2 js functions?

I have a different js framework and it stop below script.
So I read that I must using The noConflict() Method.
I try do it but just first function works. and second function do not works!
(if replace loction these two functions,Always only first function works.
what is my mistake?
I used this tutorial on w3school to do it.
http://www.w3schools.com/jquery/jquery_noconflict.asp
Also I try var jq = $.noConflict(); and other method.
I use this script inline in my html codes.
function checkCitySelect()
{
$.noConflict();
jQuery(document).ready(function($){
$("#province, #county, #district,#selectSubject").on('change', function() {
var txt;
var type = this.id;
txt = $("#"+type).val();
$.post("ajax/validation.php", {value: txt,id: type}, function(result){
if(type == 'province')
$("#county").empty().append(result);
else if(type == 'county')
$("#district").empty().append(result);
else if(type == 'district')
{
setAddressMap2("Paris, France");
}
else if(type == 'selectSubject')
{
$("#selectSubject").after(result);
}
});
});
});
}
function setAddressMap2(whereis)
{
$.noConflict();
jQuery(document).ready(function($){
$("#signup_map").gmap3({
getlatlng:{
address: whereis,
callback: function(results){
if ( !results ) return;
$(this).gmap3({
marker:{
latLng:results[0].geometry.location
}
});
}
}
});
});
}
checkCitySelect();
setAddressMap2("JAPAN");
</script>

JQuery 1.11.1 Deferred Then - multiple with parameters

I am having issued chaining a bunch of deferred 'then's in my javascript function.
In JQuery 1.7.2 I was able to create something like the following example, passing parameters from each one to determine if I continue.
myAjaxFunction(myParametersObject)
.done(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (noErrors) {
if (anyErrors == true) {
// final code here
}
});
It works perfectly on JQuery 1.7.2 but I am working on a project that requires JQuery 1.11.1 and this no longer works.
How can I pass parameters to the upcoming 'then' in JQuery 1.11.1?
Return jQuery promise value from myAjaxFunction appear to be defined as noErrors at done handler argument parameter
.done(function (noErrors) {
within .done handler as anyErrors ?
if (anyErrors == true) {
similarly at
.then(function (noErrors) {
if (anyErrors == true) {
// call ajax routine
?
Try setting same parameter as argument parameter and within handler , .e.g. anyErrors
var dfd = $.Deferred().resolve(true);
dfd.done(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// call ajax routine
return true;
} else {
//stop code execution
return false;
}
})
.then(function (anyErrors) {
if (anyErrors == true) {
// final code here
document.body.textContent = anyErrors;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
jsfiddle http://jsfiddle.net/zr5rzb7v/1/
You could use it if you use first then and then done:
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
See official jquery api documentation: http://api.jquery.com/deferred.then/#deferred-then-doneFilter-failFilter-progressFilter

A script is executed/not executed due to when jQuery is loaded - Why?

This is a problem I have. Try this code:
if (typeof jQuery == 'undefined') {
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0];
done = false;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
};
};
head.appendChild(script);
};
getScript('http://code.jquery.com/jquery-1.11.2.min.js', function () {
if (typeof jQuery !== 'undefined') {
jQuery(document).ready(function ($) {
MyFunction($);
});
}
});
} else {
jQuery(document).ready(function ($) {
MyFunction($);
});
}
function MyFunction($) {
$.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?", function (d) {
}).done(function(d) {
JsonToHtml(d);
});
}
function JsonToHtml(html) {
var items = [];
$.each(html, function (key, val) {
items.push(val);
});
$('body').prepend(items.join(''));
}
you will notice that my code check if jQuery is loaded. If not, it loads a version from external source; than retrieve a JSON, parse it and "execute it".
As you can see, the script loaded inside the body it is not loaded at all (this is my problem).
Now, try to choose a version/library of jQuery in the fiddle (1.8.3 is ok) and press play: you will see the script/button render as well: the script is executed!!!
Why loading jQuery first (here) render the script, and load jQuery later won't execute the script? Can you help me?
I think your best bet is to force onload event to be refired if it is already fired because as you are loading jQuery (if undefined), this event is already fired. This is a workaround:
function JsonToHtml(html) {
var items = [];
$.each(html, function (key, val) {
items.push(val);
});
$('body').prepend(items.join(''));
if (document.readyState === 'complete') { // check if document is complete
var evt = document.createEvent('Event');
evt.initEvent('load', false, false);
window.dispatchEvent(evt); // then redispatch onload event
}
}
-DEMO-
I think the problem is the scope. The functions MyFunction() and JsonToHtml() are out of the scope. (Remember you are working with async functions like getJSON) Maybe my explanation are wrong, but the code works. :P
With this code you have no problem.
function _test(){}
_test.prototype = {
hasjQuery: function(){
if(typeof window.jQuery !='undefined' && !_test.prototype.otherLibrary() ) {
return true;
}else{
return false;
}
},
otherLibrary: function(){
if (typeof document.$ == 'function') {
return true;
}else{
return false;
}
},
inyectjQuery: function(url, success){
var script = document.createElement('script');
script.src = url;
script.id = "delete";
done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null
}
};
document.getElementsByTagName('head')[0].appendChild(script)
},
myFunction: function(){
urljQuery = 'http://code.jquery.com/jquery-latest.min.js';
if(_test.prototype.hasjQuery()){
jQuery.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?",
function (d) {
_test.prototype.JsonToHtml(d);
}).done(function() {
console.log("Success getJSON action");
});
}else{
_test.prototype.inyectjQuery(urljQuery, function(){
if (typeof window.jQuery == 'undefined') {
console.log("unable to load jQuery");
}else{
jQuery.getJSON("http://archiesocial.progettiarchimede.it/widget_privacy/test.aspx?asd=1&callback=?",
function (d) {
_test.prototype.JsonToHtml(d);
}).done(function() {
console.log("Success getJSON action");
});
}
});
}
},
JsonToHtml: function(html){
var items = [];
jQuery.each(html, function (key, val) {
items.push(val);
});
jQuery('body').prepend(items.join(''));
}
}
test = new _test();
test.myFunction();

Error 0x8007000e (NS_ERROR_OUT_OF_MEMORY)

I'm working on an addon to a forum and I get this error:
Error: Component returned failure code: 0x8007000e (NS_ERROR_OUT_OF_MEMORY) [nsIXPCComponents_Utils.evalInSandbox]
I read that the error means that the script goes into infinite loop until it fills the sandbox.
apparently the js file that leads to this error is script-compiler.js
this is the script:
var ddplus_gmCompiler={
// getUrlContents adapted from Greasemonkey Compiler
// http://www.letitblog.com/code/python/greasemonkey.py.txt
// used under GPL permission
//
// most everything else below based heavily off of Greasemonkey
// http://greasemonkey.mozdev.org/
// used under GPL permission
getUrlContents: function(aUrl){
var ioService=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream=Components
.classes["#mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel=ioService.newChannel(aUrl, null, null);
var input=channel.open();
scriptableStream.init(input);
var str=scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
},
isGreasemonkeyable: function(url) {
var scheme=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService)
.extractScheme(url);
return (
(scheme == "http" || scheme == "https" || scheme == "file") &&
!/hiddenWindow\.html$/.test(url)
);
},
contentLoad: function(e) {
var unsafeWin=e.target.defaultView;
if (unsafeWin.wrappedJSObject) unsafeWin=unsafeWin.wrappedJSObject;
var unsafeLoc=new XPCNativeWrapper(unsafeWin, "location").location;
var href=new XPCNativeWrapper(unsafeLoc, "href").href;
if (
ddplus_gmCompiler.isGreasemonkeyable(href)
&& ( /http:\/\/ddunlimited\.net/.test(href) )
&& true
) {
var script=ddplus_gmCompiler.getUrlContents(
'chrome://ddplus/content/ddplus.js'
);
ddplus_gmCompiler.injectScript(script, href, unsafeWin);
}
},
injectScript: function(script, url, unsafeContentWin) {
var sandbox, script, logger, storage, xmlhttpRequester;
var safeWin=new XPCNativeWrapper(unsafeContentWin);
sandbox=new Components.utils.Sandbox(safeWin);
var storage=new ddplus_ScriptStorage();
xmlhttpRequester=new ddplus_xmlhttpRequester(
unsafeContentWin, window//appSvc.hiddenDOMWindow
);
sandbox.window=safeWin;
sandbox.document=sandbox.window.document;
sandbox.unsafeWindow=unsafeContentWin;
// patch missing properties on xpcnw
sandbox.XPathResult=Components.interfaces.nsIDOMXPathResult;
// add our own APIs
sandbox.GM_addStyle=function(css) { ddplus_gmCompiler.addStyle(sandbox.document, css) };
sandbox.GM_setValue=ddplus_gmCompiler.hitch(storage, "setValue");
sandbox.GM_getValue=ddplus_gmCompiler.hitch(storage, "getValue");
// kick : aggiunta la funzione
sandbox.GM_remove=ddplus_gmCompiler.hitch(storage, "remove");
sandbox.GM_openInTab=ddplus_gmCompiler.hitch(this, "openInTab", unsafeContentWin);
sandbox.GM_xmlhttpRequest=ddplus_gmCompiler.hitch(
xmlhttpRequester, "contentStartRequest"
);
//unsupported
sandbox.GM_registerMenuCommand=function(){};
sandbox.GM_log=function(){};
sandbox.GM_getResourceURL=function(){};
sandbox.GM_getResourceText=function(){};
sandbox.__proto__=sandbox.window;
try {
this.evalInSandbox(
"(function(){"+script+"})()",
url,
sandbox);
} catch (e) {
var e2=new Error(typeof e=="string" ? e : e.message);
e2.fileName=script.filename;
e2.lineNumber=0;
//GM_logError(e2);
alert(e2);
}
},
evalInSandbox: function(code, codebase, sandbox) {
if (Components.utils && Components.utils.Sandbox) {
// DP beta+
Components.utils.evalInSandbox(code, sandbox);
} else if (Components.utils && Components.utils.evalInSandbox) {
// DP alphas
Components.utils.evalInSandbox(code, codebase, sandbox);
} else if (Sandbox) {
// 1.0.x
evalInSandbox(code, sandbox, codebase);
} else {
throw new Error("Could not create sandbox.");
}
},
openInTab: function(unsafeContentWin, url) {
var tabBrowser = getBrowser(), browser, isMyWindow = false;
for (var i = 0; browser = tabBrowser.browsers[i]; i++)
if (browser.contentWindow == unsafeContentWin) {
isMyWindow = true;
break;
}
if (!isMyWindow) return;
var loadInBackground, sendReferrer, referrer = null;
loadInBackground = tabBrowser.mPrefs.getBoolPref("browser.tabs.loadInBackground");
sendReferrer = tabBrowser.mPrefs.getIntPref("network.http.sendRefererHeader");
if (sendReferrer) {
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
referrer = ios.newURI(content.document.location.href, null, null);
}
tabBrowser.loadOneTab(url, referrer, null, null, loadInBackground);
},
hitch: function(obj, meth) {
var unsafeTop = new XPCNativeWrapper(unsafeContentWin, "top").top;
for (var i = 0; i < this.browserWindows.length; i++) {
this.browserWindows[i].openInTab(unsafeTop, url);
}
},
apiLeakCheck: function(allowedCaller) {
var stack=Components.stack;
var leaked=false;
do {
if (2==stack.language) {
if ('chrome'!=stack.filename.substr(0, 6) &&
allowedCaller!=stack.filename
) {
leaked=true;
break;
}
}
stack=stack.caller;
} while (stack);
return leaked;
},
hitch: function(obj, meth) {
if (!obj[meth]) {
throw "method '" + meth + "' does not exist on object '" + obj + "'";
}
var hitchCaller=Components.stack.caller.filename;
var staticArgs = Array.prototype.splice.call(arguments, 2, arguments.length);
return function() {
if (ddplus_gmCompiler.apiLeakCheck(hitchCaller)) {
return;
}
// make a copy of staticArgs (don't modify it because it gets reused for
// every invocation).
var args = staticArgs.concat();
// add all the new arguments
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
// invoke the original function with the correct this obj and the combined
// list of static and dynamic arguments.
return obj[meth].apply(obj, args);
};
},
addStyle:function(doc, css) {
var head, style;
head = doc.getElementsByTagName('head')[0];
if (!head) { return; }
style = doc.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
},
onLoad: function() {
var appcontent=window.document.getElementById("appcontent");
if (appcontent && !appcontent.greased_ddplus_gmCompiler) {
appcontent.greased_ddplus_gmCompiler=true;
appcontent.addEventListener("DOMContentLoaded", ddplus_gmCompiler.contentLoad, false);
}
},
onUnLoad: function() {
//remove now unnecessary listeners
window.removeEventListener('load', ddplus_gmCompiler.onLoad, false);
window.removeEventListener('unload', ddplus_gmCompiler.onUnLoad, false);
window.document.getElementById("appcontent")
.removeEventListener("DOMContentLoaded", ddplus_gmCompiler.contentLoad, false);
},
}; //object ddplus_gmCompiler
function ddplus_ScriptStorage() {
this.prefMan=new ddplus_PrefManager();
}
ddplus_ScriptStorage.prototype.setValue = function(name, val) {
this.prefMan.setValue(name, val);
}
ddplus_ScriptStorage.prototype.getValue = function(name, defVal) {
return this.prefMan.getValue(name, defVal);
}
ddplus_ScriptStorage.prototype.remove = function(name) {
return this.prefMan.remove(name);
}
window.addEventListener('load', ddplus_gmCompiler.onLoad, false);
window.addEventListener('unload', ddplus_gmCompiler.onUnLoad, false);
The user script is massive and available in this gist.
To be able to see the error:
install the addon
go to the message board at http://ddunlimited.net/
open any thread and open click the reply link
The message will appear as soon as the reply page loads.
in practice is a tool created specifically for a forum ... with the functions targeted to simplify the daily actions of the moderator. Now the forum has changed domain and tried to make it compatible with the new forum. I'm editing the js file with a simple text editor. ettengo the error when I edit the script that I posted above. if you do not touch this script ... some functions disappear and are no longer present.
someone can help me? thank you very much: D
OK, reproducible after all. The error in this case has a bogus message, as this isn't actually an OOM condition, but evalInSandbox() receiving a notification from the JS engine that the script was aborted (due to it being unresponsive) and evalInSandbox() not being able to tell the difference.
The reason is an infinite loop in your code at line 425 (cont.):
var max = textArea.parentNode.parentNode.clientHeight;
while (max == textArea.parentNode.parentNode.clientHeight)
textArea.rows++;
This loop whill never abort as the condition will never get false.

Reloading dynatree with new data - destroy method or reloadChildren do not seem to work

I'm not able to reload dynatree after I received response for AJAX request.
I've a pulldown 'plan.viewType' in code below. I'm invoking a JS function upon a new value selected in this pulldown which will in turn call an AJAX function.
<form:select path="plan.viewType" id="viewType" style="width:11.6em" onChange="loadView()" multiple="false">
<form:options items="${plan.viewType}"/>
</form:select>
I've two trees - dim_tree and kpi_tree.
$(document).ready(function(){
$.fn.clearable = function (treeid) {
var $this = this;
$this.wrap('<div class="clear-holder" />');
var helper = $('<span class="clear-helper">x</span>');
$this.parent().append(helper);
helper.click(function(){
$this.val("");
$('#' + treeid).dynatree('getRoot').search("");
});
};
$("#dimsearch").clearable("dim_tree");
$("#kpisearch").clearable("kpi_tree");
$("#dim_tree").dynatree({
checkbox: true,
selectMode: 3,
children: (isEdit == "true")? eval('('+'${plan_dimension_edit_info}'+')') : eval('('+'${plan_dimension_info}'+')'),
dnd: {
onDragStart: function (node) {
return false;
},
onDragStop: function (node) {
return false;
},
onDragOver: function (targetNode, sourceNode, hitMode) {
return false;
},
onDrop: function (targetNode, sourceNode, hitMode, ui, draggable) {
return false;
}
},
onSelect: function(select, node) {
if(select && dimKPIMisMatch(node)) {
node.select(false);
//showToolTip(node.span, dimMsg);
return;
}
createTreeSortable(select, node, "DIM");
}
});
$("#kpi_tree").dynatree({
checkbox: true,
selectMode: 3,
children: (isEdit == "true")? eval('('+'${plan_measurement_edit_info}'+')') : eval('('+'${plan_measurement_info}'+')'),
dnd: {
onDragStart: function (node) {
return false;
},
onDragStop: function (node) {
return false;
},
onDragOver: function (targetNode, sourceNode, hitMode) {
return false;
},
onDrop: function (targetNode, sourceNode, hitMode, ui, draggable) {
return false;
}
},
onSelect: function(select, node) {
if(select && kpiDIMMisMatch(node)) {
node.select(false);
//showToolTip(node.span, kpiMsg);
return;
}
createTreeSortable(select, node, "KPI");
}
});
});
I would like to reload these two trees when I get response from AJAX call below.
var loadView = function() {
if($("#viewType").val() == "Default View") {
$.ajax({
url : "planmntsdefault.do",
type : "GET",
success : function (data) {
var node = $("#dim_tree").dynatree("getTree").getRoot();
if(node && node.isLazy())
{
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
else
{
node.activate();
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
node = $("#kpi_tree").dynatree("getTree").getRoot();
if(node && node.isLazy())
{
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
else
{
node.activate();
node.reloadChildren(function(node, isOk){
if(!isOk) alert("Node " + node + " could not be reloaded.");
else alert("Tree reloaded");
});
}
},
error : function ( xhr, textStatus, error ) {
}
});
}
}
I referred to other posts how to reload/refresh/reinit DynaTree? which didn't resolve the problem. I've tried another variation where I do destroy and reload. Neither of these approaches work. Am I missing something here? Thanks.
You could try this:
success : function (data) {
$("#dim_tree").dynatree("getTree").reload();
$("#kpi_tree").dynatree("getTree").reload();
},
you can solve your problem by three method if you want to add new data and response come by ajax then u can add following code in dynatree
jQuery
$.ajax({
url : "planmntsdefault.do",
type : "GET",
success : function (data) {
var node = $("#dim_tree").dynatree("getTree").getRoot();
/*here you can use i assume title
come (by this name of root is set in
dynatree and if set isFolder :true then
folder icon appear in dyna tree*/
var childNode = node.addChild({ title: data.title,
isFolder: true
});
}
})
and if u want to edit some root name then you can use
In Previous Code Where We Use Add Set Below Line
var node = $("#tree").dynatree("getActiveNode");
node.data.title = $newtitle;
And For Delete
var node = $("#tree").dynatree("getActiveNode");
activeNode.remove();
these all steps when we apply then it look that dyna tree referesh hope it make help

Categories

Resources