function moveIt(result, finish) {
$result = $(result);
$result.find('#main-content-wrapper').appendTo('#aem-content');
$result.appendTo('#scriptDiv');
if (finish !== undefined) {
finish();
}
}
function isAuthSpace(path) {
if (path.toLowerCase().indexOf("shop/") > 0) return true;
return false;
}
function finishInjecting() {
ProcessInjection("div.dyna-prd-lnk", parseDivTag, pumpDivTag, "Shop.aspx/GetLinks");
}
function AEMLoadError(isAuth) {
var fileToLoad = "unAuth.html";
if (isAuth) {
fileToLoad = "auth.html";
}
$("#aem-content").load(fileToLoad, finishInjecting);
}
function breakAEMLoadPath(path) {
return BreakTheAEMLoadPath === true ? "2" : path;
}
function PullAEM(path, finish) {
var isAuth = isAuthSpace(path);
var ppath = breakAEMLoadPath(path);
$.ajax({
url: ppath,
success: function (result) {
moveIt(result, finish);
},
error: function () {
AEMLoadError(isAuth);
},
dataType: "html"
});
}
When I call the above function PullAEM(path, finish), no matter what value I put in path parameter, the ajax call calls the success function, if the path has garbage in it, say it's empty, the call succeeds (even though it should fail). When it should fail, the result contains the contents of the current page which is not what path is pointing to. Anyone have any idea what I'm doing wrong?
Thanks for everyone answering so fast. I'm not sure what the problem was but after I cleaned it all up to post it up here it worked great! Though, it ay have been something you both were saying.
This is working perfectly....
Related
I have a jQuery file which also uses unserscore.js. It controls the selections of dates and different venues. For one of the pages it also controls which visuals are displayed depending on the type of venue. I can successfully, using ajax, get the type of page, but I have been unable to pass that value to a public variable in the script. It is based on which WiFi spot the data is coming from. If the data is from a local spot the page should display a d3 bubble chart. If it's from a remote spot it should display a map of the venue. Currently I have the functionality working with hard coding based on the id of the venue which is far from ideal.In order to make the decision based on which spot the venue is using I created an ajax call that gets the "spot". With console.log I can see that I am getting the correct result from the ajax call, but I'm missing something in terms of passing that information to a variable so I can use it.
This is the complete jQuery files:
define([
"ui/selects",
], function (SelectsUiClass) {
var global = this;
var MainControlsClass = function () {
// Private vars
var _this = this,
_xhr = null,
_selects = new SelectsUiClass(),
_dateRangeSelect,
_venueSelect,
_floorSelect,
_zoneSelect;
// Public vars
this.Selects = null;
this.spotName = null;
// Private Methods
var _construct = function () {
_dateRangeSelect = _selects.InitSelect('#mainControls-dateRange', _onSelectChange);
_venueSelect = _selects.InitSelect('#mainControls-venue', _onSelectChange);
_floorSelect = _selects.InitSelect('#mainControls-floor', _onSelectChange);
_zoneSelect = _selects.InitSelect('#mainControls-zone', _onSelectChange);
var value = _this.GetVenue();
_getChartDisplayDiv(value);
};
var _getChartDisplayDiv = function (venueId) {
var path = window.location.pathname,
pathArray = path.split("/"),
page = pathArray[pathArray.length - 1];
console.log('controlsjs 36, navigation page: ' , page);
console.log('controlsjs 37, venue value: ' , venueId);
_this.Load(venueId);
console.log('Controls 40, sPot Name = ', _this.spotName);
if (page === 'heatmap') {
if (venueId === 8 || venueId === 354) {
//make the bubble div visible
$("#heatmap-bubble").show();
//make the map div invisible
$("#heatmap-map").hide();
} else {
//make the map div visible
$("#heatmap-map").show();
//make the bubble div invisible
$("#heatmap-bubble").hide();
}
}
}
this.Load = function (venueId) {
console.log("Controls 66, Venue Id sent = ", venueId);
if (_xhr) {
_xhr.abort();
_xhr = null;
}
_this.SetLoading(true);
_xhr = $.ajax({
url: $("meta[name='root']").attr("content") + '/app/heatmap/spot',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
venue_id: venueId
},
dataType: 'JSON',
async: true,
cache: false,
error: function (jqXHR, textStatus, errorThrown) {
_this.SetLoading(false);
},
success: function (response) {
_this.SetLoading(false);
console.log("Controls 90, Response of ajax call = ", response);
_this.Update(response);
}
});
};
// Public functions
this.SetLoading = function (option) {
if (_.isUndefined(option)) { option = false; }
if (this.spotName) { this.spotName.SetLoading(option); }
};
this.Update = function (data) {
if (_.isUndefined(data) || _.isNull(data)) {
console.log('Controls 106: Spot Name: ', data)
this.spotName = data;
}
};
var _getVenueData = function (venueId) {
for (var i = 0; i < venuesData.length; i++) {
if (venuesData[i].id === venueId) {
if (!_.isUndefined(venuesData[i].spot_data)) {
return venuesData[i].spot_data;
}
}
}
};
var _onVenueChange = function () {
var value = _this.GetVenue();
if (_.isNull(value)) {
return;
}
_getChartDisplayDiv(value);
//_setSelectValue(_venueSelect, value);
var venueData = _getVenueData(value);
console.log('Venue data received: ', venueData);
if (!_.isUndefined(venueData) && !_.isUndefined(venueData.floors)) {
_selects.UpdateSelect(_floorSelect, venueData.floors);
_onFloorChange();
}
};
var _onFloorChange = function () {
var value = _this.GetFloor(),
zones = [];
if (_.isNull(value)) {
return;
}
//_setSelectValue(_floorSelect, value);
if (_.isNumber(value)) {
var venueData = _getVenueData(_this.GetVenue()),
floors = venueData.floors;
for (var i = 0; i < floors.length; i++) {
if (floors[i].id === value) {
zones = floors[i].zones;
}
}
}
_selects.UpdateSelect(_zoneSelect, zones);
};
var _onZoneChange = function () {
var value = _this.GetZone();
if (_.isNull(value)) {
return;
}
//_setSelectValue(_zoneSelect, value);
};
var _onSelectChange = function (e) {
var t = $(e.target),
id = t.attr('id');
if (_venueSelect && _venueSelect.attr('id') === id) {
_onVenueChange();
} else if (_floorSelect && _floorSelect.attr('id') === id) {
_onFloorChange();
} else if (_zoneSelect && _zoneSelect.attr('id') === id) {
_onZoneChange();
}
EventDispatcher.Dispatch('Main.Controls.Change', _this, {
caller: id
});
};
// Public Methods
this.GetDateRange = function () {
return _selects.GetSelectValue(_dateRangeSelect);
};
this.GetDateRangeKey = function () {
if (_dateRangeSelect) {
var selected = _dateRangeSelect.find('option:selected');
if (selected.length) {
return selected.attr("data-key") || "";
}
}
return "";
};
this.GetVenue = function () {
return _selects.GetSelectValue(_venueSelect);
};
this.SetVenue = function (value) {
_selects.SetSelectValue(_venueSelect, value);
}
this.GetFloor = function () {
return _selects.GetSelectValue(_floorSelect);
};
this.SetFloor = function (value) {
_selects.SetSelectValue(_floorSelect, value);
}
this.GetZone = function () {
return _selects.GetSelectValue(_zoneSelect);
};
this.SetZone = function (value) {
_selects.SetSelectValue(_zoneSelect, value);
}
this.GetData = function () {
return {
dateRange: {
date: this.GetDateRange(),
key: this.GetDateRangeKey()
},
venue: this.GetVenue(),
floor: this.GetFloor(),
zone: this.GetZone()
};
};
// Init
_construct();
};
return MainControlsClass;
});
The function that determines which visual to display is close to the top: _getChartDisplayDiv:
var _getChartDisplayDiv = function (venueId) {
var path = window.location.pathname,
pathArray = path.split("/"),
page = pathArray[pathArray.length - 1];
_this.Load(venueId);
console.log('Controls 40, sPot Name = ', _this.spotName);
if (page === 'heatmap') {
if (venueId === 8 || venueId === 354) {
//make the bubble div visible
$("#heatmap-bubble").show();
//make the map div invisible
$("#heatmap-map").hide();
} else {
//make the map div visible
$("#heatmap-map").show();
//make the bubble div invisible
$("#heatmap-bubble").hide();
}
}
}
When I am able to pass the "spot" information to it or a variable that it uses, it should look like this:
var _getChartDisplayDiv = function (venueId) {
var path = window.location.pathname,
pathArray = path.split("/"),
page = pathArray[pathArray.length - 1];
_this.Load(venueId);
console.log('Controls 40, sPot Name = ', _this.spotName);
if (page === 'heatmap') {
if (_this.spotName === 'local' ) {
//make the bubble div visible
$("#heatmap-bubble").show();
//make the map div invisible
$("#heatmap-map").hide();
} else {
//make the map div visible
$("#heatmap-map").show();
//make the bubble div invisible
$("#heatmap-bubble").hide();
}
}
}
My ajax call is here:
this.Load = function (venueId) {
console.log("Controls 66, Venue Id sent = ", venueId);
if (_xhr) {
_xhr.abort();
_xhr = null;
}
_this.SetLoading(true);
_xhr = $.ajax({
url: $("meta[name='root']").attr("content") + '/app/heatmap/spot',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
venue_id: venueId
},
dataType: 'JSON',
async: true,
cache: false,
error: function (jqXHR, textStatus, errorThrown) {
_this.SetLoading(false);
},
success: function (response) {
_this.SetLoading(false);
console.log("Controls 90, Response of ajax call = ", response);
_this.Update(response);
}
});
};
This successfully gets the right spot, but I have been unable to pass it to a variable I can use. I think I am getting mixed up between private and public variables. I tried to use the 'this.Update' function to pass the setting to the public 'this.spotName' variable, but that comes up null. I have also tried to simply return the result of the ajax call, but I get a "not a function" error. How can I make the result of the ajax call available to my '_getChartDisplayDiv' function?
Your problem is that you are trying to read the value of _this.spotName before it is assigned. Let us walk through the steps that happen.
When you call _getChartDisplayDiv(value), the _getChartDisplayDiv function first calls _this.Load(venueId). Load, in turn, submits an ajax request with a success callback, reproduced in abbreviated form below:
this.Load = function (venueId) {
// ...
_this.SetLoading(true);
_xhr = $.ajax({
...
success: function (response) {
_this.SetLoading(false);
console.log("Controls 90, Response of ajax call = ", response);
_this.Update(response);
}
});
};
When the response arrives, the success callback will be invoked, which in turn will call _this.Update, which will set the variable you are after. The syntax you used for this purpose is correct. However!
"When the response arrives" happens to be an unpredictable event in the future. It might be after 10 milliseconds, it might take 2 seconds, or the request might time out altogether. Even 10 milliseconds is already an eternity, compared to the time it takes your browser to execute all other code in your script. You can be quite sure that by the time $.ajax returns, the success callback has not run yet.
When you pass a callback (success) to a function ($.ajax) and the callback is not run before the function returns, this is called an asynchronous callback, "async" for short. When a callback might be invoked async, it is important for the function to guarantee that it always runs async, because this type of situation needs to be handled in an entirely different way from when the callback is invoked synchronously (i.e., before the function returns). You can read more about the technicalities in this blogpost. So this is exactly what $.ajax guarantees: it will never invoke the success (or error) callback before it returns, even in the hypothetical situation that the response would arrive fast enough.
Right after $.ajax returns, your Load function returns, at which point your _getChartDisplayDiv function continues to execute. Almost immediately after that, you intend to read _this.spotName. $.ajax has already returned, so you might hope that at this point, the success callback has already been invoked.
Unfortunately for you, async callbacks are more stubborn than that. Not only does an async callback not run until the function to which you pass it returns; it does not run until any currently executing function returns. Besides $.ajax, Load needs to return, _getChartDisplayDiv needs to return, any function that was calling _getChartDisplayDiv needs to return, and so forth. The entire call stack needs to unwind. Only then (and when the response actually arrives, which is likely to be many milliseconds later) will the success callback be invoked. This game rule is called the event loop in JavaScript.
The solution is simpler than you might expect: you just need to invert the order of control. Rather than trying to force the data out of a request when you want to update the chart, you can update the chart when the response arrives, and rather than trying to update the chart directly, you can just trigger the request. Specifically in your case, you just need to make three changes:
In the places where you currently call _getChartDisplayDiv, call _this.Load instead.
Remove the line that calls _this.Load inside the _getChartDisplayDiv function.
At the end of the success handler, add a line that calls _getChartDisplayDiv.
Incidentally, using a proper application framework will make it much easier to manage this kind of thing. In your case, I recommend trying Backbone; it builds on top of Underscore and jQuery and it is unopinionated, so you can gradually adopt it without having to radically change the way you work.
I am not familiar with underscore.js. For jQuery you have two options, which you can use as an inspiration for your case. Untested code:
1. Callback function
You provide a callback function:
$('.mydiv').myPlugin({ // Pass options Object to plugin
venuId: '123',
getType: function(type) {
console.log(type); // Example accessing internal data
}
});
Your plugin code:
(function( $ ) {
$.fn.myPlugin = function(opt) {
this.filter('div').each(function() {
const settings = $.extend({
namespace: 'myPlugin',
type: 'local'
getType: function() {},
// otherSettings: 'as needed',
}, opt);
// plugin code here...
if(typeof settings.getType === 'function') {
settings.getType(settings.type);
}
});
return this;
};
}( jQuery ));
2. Plugin method
You define plugin method(s) that can be called:
$('#mydiv').myPlugin({ // Pass options Object to plugin
venuId: '123'
});
console.log($('#mydiv').myPlaugin('getType'));
Your plugin code:
(function( $ ) {
$.fn.myPlugin = function(opt) {
this.filter('div').each(function() {
const settings = $.extend({
namespace: 'myPlugin',
type: 'local',
// otherSettings: 'as needed',
}, opt);
this.getType = function() {
return settings.type;
}
let firstArg = arguments[0];
if(typeof firstArg === 'string') {
let func = this[firstArg];
if(typeof func === 'function') {
var args = [];
for(var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
return func.apply(this, args);
}
} else {
// plugin init code here...
}
});
return this;
};
}( jQuery ));
I'm new to javascript, but I can't get my head around this problem. I have a function that upvotes a game:
function upVoteGame(name) {
$.get("/get_gameValues", function(data) {
var alreadyExist = false;
var noVotes = false;
var games;
games = data;
for (var i = 0; i < games.length; i++) {
if (name === games[i].gameName) {
alreadyExist = true;
voteOperations();
if (userLoggedIn == false) {
alert("second");
swal("Cannot post votes", "Please log in or register to vote", "error");
}
if (noVotesLeft == false && userLoggedIn == true) {
$.ajax({
url: '/editVotes/' + games[i]._id,
type: 'PUT',
data: {
likes: games[i].likes + 1,
totalVotes: data[i].totalVotes + 1
},
success: function(result) {
alert(games[i].likes + 1);
}
});
}
refreshGameValues();
break;
}
}
//This is for us Developers!
if (!alreadyExist) {
$.post("/add_game_to_dB", {
gameName: name
}, function(result) {
alert("Introduced " + name);
});
}
});
}
Now I have the function that updates the user's votes left, voteOperations():
function voteOperations() {
$.get("/users/get_current_user", function(data) {
//var votes = 5;
for (var i = 0; i < data.length; i++) {
votesRemaining = data[i].votesRemaining;
userLoggedIn = true;
alert("votes left : " + votesRemaining);
if ((votesRemaining - 1) < 0) {
swal("No votes remaining", "Please wait 24 hours to get more votes", "error");
noVotesLeft = true;
}
if (noVotesLeft == false) {
$.ajax({
url: '/users/updateUserDetails/' + data[i].user_name,
type: 'PUT',
data: {
votesRemaining: votesRemaining - 1
},
success: function(result) {}
});
}
}
});
}
My problem is a simple problem. In the upVoteGame(name) function, I want the voteOperations() to execute before the if loop below it. However, when I run the code, the if loop below executes first and alerts the user that they are not logged in. When a user logs in, userLoggedIn is set to true, but the if loop executes firsts and tells them that they are not logged in, and then executes the voteOperations() function. I don't know why this is happening. How can I fix this so that voteOperations executes before the if loop?
This is because the voteoperations function has a get request which is asynchronous. You will need a callback function where you should include if condition
You can try:
function upVoteGame(name) {
vote(afterGet);
}
afterGet() {
if condition here
}
function vote(callback) {
$.get .... {
//after getting data
callback();
}
}
You problem occurs due to the asynchronous call of your $.get in the voteOperations function.
Since it is an asynchronous call your code continuous while your $.get is waiting to retrieve data and thus your if statement seems to trigger before your voteOperations function.
In simple words your function actually is triggered before the if statement but before it completes it's result the code continues and triggers your if statement.
You could put your if statement (logic) in the success callback of your vote operation function or use $.ajax with async:false which is not considered a good practice generally but I use it sometimes.
Something like that for example (for the second case)
$.ajax({
async: false,
.....
success: function (response) {
//
}
});
Asynchronous calls can be handled with jquery function Deffered
function upVoteGame(name) {
vote().then(doUpVoteGame(), handleError());
}
function doUpVoteGame() {
...
}
function handleError(e) {
console.error("fail", e);
}
function vote() {
var d = new $.Deferred();
$.get .... {
d.resolve();
}).fail(function(e) {
d.reject(e);
});
return d;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery ajax return value
How to return the response from an AJAX call from a function?
I have javascript. It loads data from database. I want to return true or false with respect to loading data. But I could not return it. My code has given bellow:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.get(url, {
isrc: isrc
}, function (data) {
if (data == "true") {
result = true;
}
else {
result = false;
}
});
return result;
}
It always gives false result. Anyone has faced this kind of problem? 'Thanks advance'
If it's so important to use the function synchronously you can refactor it to:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.ajax({
async: false,
success: function (data) {
if (data == "true") {
result = true;
}
else {
result = false;
}
},
data: { isrc: isrc }
});
return result;
}
As #ManseUK async is deprecated in jQuery 1.8 so if you want synchronous approach you should use older version.
The problem is that when you return result, It doesnt have value. because the ajax didn't finish its task. you make some callback function and when the result of ajax is returned from server, do what you want to.
Some thing like this:
function CheckISRC(Callback) {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.get(url, {
isrc: isrc
}, function (data) {
if (data == "true") {
Callback(true);
}
else {
Callback(false);
}
});
}
function YourCallback(result) {
//...
}
The JQuery ajax functions are asynchronous. This means that when you initialise result to false, the result is set to true or false after the "return result;" line has run.
You can make the call synchronous but this is considered worse practice. You are often better off refactoring your code to allow for the asynchronous nature of the JQuery Ajax.
For example, where you previously had:
function myFunction() {
//Code before
var result = CheckISRC();
//Code after using result
}
you could have the following:
function myFunction() {
//Code before
CheckISRC();
}
function myFunction_callback(result) {
//Code after using result
}
where you call myFunction_callback in the success option of your ajax code like so:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
$.get(url, {
isrc: isrc
}, function (data) {
myFunction_callback(data == "true");
});
}
I have the following code grabbing a JSON object from github and I am tring to add certain parts to an array.
function getTree(hash) {
var pathToTree, returnedJSON;
pathToTree = 'https://api.github.com/repos/myaccount/myrepo/git/trees/' + hash;
$.ajax({
accepts: 'application/vnd.github-blob.raw',
dataType: 'jsonp',
url: pathToTree,
success: function (json) {
returnedJSON = json;
},
error: function (error) {
console.debug(error);
}
});
return returnedJSON;
}
function parseTree(hash) {
var objectedJSON, objectList = [], i, entry;
objectedJSON = getTree(hash, function () {
console.debug(objectedJSON); // this is not appearing in console
for (i = 0; i < objectedJSON.data.tree.length; i += 1) {
entry = objectedJSON.data.tree[i];
console.debug(entry);
if (entry.type === 'blob') {
if (entry.type.slice(-4) === '.svg') { // we only want the svg images not the ignore file and README etc
objectList.append(i.content);
}
} else if (entry.type === 'tree') {
objectList.append(parseTree(getTree(entry.sha)));
}
}
});
return objectList;
}
$(document).ready(function () {
var objects = parseTree('master', function () {
console.debug(objects);
});
});
I have the code retrieving the JSON object fine but I run into trouble when trying to get it parsed (aka pulling out the bits I want). The callbacks I am using do not seem to be going and was wondering if someone could look it over and help me out.
Specifically, can I add a callback to any function I choose? Do I have to do anything to that function?
I have fixed the code to illustrate how you would go about it.
function getTree(hash, cb) {
// notice that I copy the callback and hash references to have access to them in this
// function's closure and any subsequent closures, like the success and error
// callbacks.
var pathToTree, returnedJSON, cb = cb, hash = hash;
pathToTree = 'https://api.github.com/repos/myaccount/myrepo/git/trees/' + hash;
$.ajax({
accepts: 'application/vnd.github-blob.raw',
dataType: 'jsonp',
url: pathToTree,
success: function (json) {
returnedJSON = json;
// if anything was passed, call it.
if (cb) cb(json);
},
error: function (error) {
console.debug(error);
// an error happened, check it out.
throw error;
}
});
return returnedJSON;
}
function parseTree(hash) {
var objectedJSON, objectList = [], i, entry;
objectedJSON = getTree(hash, function (objectedJSON) {
console.debug(objectedJSON); // this is not appearing in console
for (i = 0; i < objectedJSON.data.tree.length; i += 1) {
entry = objectedJSON.data.tree[i];
console.debug(entry);
if (entry.type === 'blob') {
if (entry.type.slice(-4) === '.svg') { // we only want the svg images not the ignore file and README etc
objectList.append(i.content);
}
} else if (entry.type === 'tree') {
objectList.append(parseTree(getTree(entry.sha)));
}
}
});
return objectList;
}
$(document).ready(function () {
var objects = parseTree('master', function () {
console.debug(objects);
});
});
As far as I can see it, you are not passing callback to your functions:
function getTree(hash) {
And you are using like:
objectedJSON = getTree(hash, function () {
Similarly this function does not have callback param:
function parseTree(hash) {
And you are using like:
var objects = parseTree('master', function () {
Modify your functions like this:
function getTree(hash, fn) { ... }
function parseTree(hash, fn) { ... }
And then call fn using fn() when needed.
Add a second parameter o getTree function. Something like
function getTree(hash, callback)
And use a "jsopCallback" parameter in your Ajax options
$.ajax({
...
jsopCallback: callback,
...
I have 3 ajax call in one function and checkAjaxCompletion which checks each ajax completion flag.
What the code below does is send multiple separate ajax calls and interval method checks completion flags to determine whether to proceed or keep interval. (I know clearInterval is not shown but the point is I want to use something other than interval)
Current code is:
function manyAjax() {
setInterval( function() { checkAjaxCompletion(); } , 200);
ajax1();
ajax2();
ajax3();
}
function ajax1() {
//send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}
function ajax2() {
//send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}
function ajax3() {
//send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}
function checkAjaxCompletion() {
if(ajax1_flag == 1 && ajax2_flag == 1 && ajax3_flag == 1) {
//everything went success, do some process
}
else if(ajax1_flag == 2 || ajax2_flag == 2 || ajax3_flag == 2) {
//some ajax failed, do some process
}
else {
//all ajax have not been completed so keep interval i.e. do nothing here
}
}
But I'm hesitating to depend on using interval function because calling it so often seem such waste of memory. There must be better way to do. I'm thinking if observer pattern can be applied here but would like to hear opinions.
It is observer-notifier, if you want to call it that - but each of your ajax calls will more than likely have a callback in javascript when they complete. Why not call checkAjaxCompletion() at the end of each of them, and do nothing if you're still waiting on others?
Dustin Diaz does a great job with this example.
function Observer() {
this.fns = [];
}
Observer.prototype = {
subscribe : function(fn) {
this.fns.push(fn);
},
unsubscribe : function(fn) {
this.fns = this.fns.filter(
function(el) {
if ( el !== fn ) {
return el;
}
}
);
},
fire : function(o, thisObj) {
var scope = thisObj || window;
this.fns.forEach(
function(el) {
el.call(scope, o);
}
);
}
};
The publisher:
var o = new Observer;
o.fire('here is my data');
The subscriber:
var fn = function() {
// my callback stuff
};
o.subscribe(fn);
To unsubscribe:
var fn = function() {
// my callback stuff
};
o.subscribe(fn);
// ajax callback
this.ajaxCallback = function(){
$.ajax({
type: "POST",
url: ajax.url,
data: {key: value},
async : !isAll,// false使用同步方式执行AJAX,true使用异步方式执行ajax
dataType: "json",
success: function(data){
if(data.status == 'successful'){
selfVal.parent().find('.msg').addClass('ok').html(msg.ok);
}else if(data.status == 'failed'){
checkRet = false;
selfVal.parent().find('.msg').removeClass('ok').html(msg.error);
}else{
checkRet = false;
}
return this;
}
});
}
return this;
Maybe you want to check your inputvalue callback ajax in your form;
You can view my website Demo, hope help you.
http://6yang.net/myjavascriptlib/regForm
Okay my idea was to make your own object that can handle sending an array of requests, keep a history of each request and do what i'm gonna call 'postProccessing' on each response, here is a probably very dodgy bit of code to hopefully demonstrate what I am thinking.
var Ajax = function() {
var request, callback, lst;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = handleResponse;
this.history = [{}];
this.send = function(args) {
for (var i = 0; i < args.length; i++) {
if (args.url) {
request.open(args.type || 'GET', args.url);
}
request.send(args.data || null);
callback = args.callback;
lst++;
}
}
function handleResponse() {
var response = {
url: '',
success: true,
data: 'blah'
};
history.push(response);
if (postProccess()) {
callback();
}
}
function postProcess() {
if (this.history[lst].success) {
return true;
} else {
return false;
}
}
}