I have a .js class named Widget.js
In widget.js class I am initiating a errors.ascx control class that has a JS script function "GetErrors()" defined in it.
Now, when I call GetErrors from my widgets.js class it works perfectly fine.
I have to populate a few controls in widgets.js using the output from GetErrors() function.
But the issue is that at times the GetErrors() takes a lot of time to execute and the control runs over to my widgets class. and the controls are populated without any data in them.
So the bottom line is that I need to know the exact usage of the OnSuccess function of Jquery.
this is my errors.ascx code
var WidgetInstance = function () {
this.GetErrors = function () {
$.ajax({
url: '/Management/GetLoggedOnUsersByMinutes/',
type: 'GET',
cache: false,
success: function (result) {
result = (typeof (result) == "object") ? result : $.parseJSON(result);
loggedOnUsers = result;
}
});
},.....
The code for the Widgets.js file is
function CreateWidgetInstance() {
widgetInstance = new WidgetInstance();
widgetInstance.GetErrors();
}
now I want that The control should move from
widgetInstance.GetErrors();
only when it has produced the results.
any Help???
You can use jQuery Deferreds. $.ajax() actually returns a promise. So you can do the following:
var WidgetInstance = function () {
this.GetErrors = function () {
return $.ajax({
url: '/Management/GetLoggedOnUsersByMinutes/',
type: 'GET',
cache: false
});
},.....
Then you can process the results like so...
widgetInstance.GetErrors().done(function(result){
//process the resulting data from the request here
});
Hi Simply use async:false in your AJAX call.. It will block the control till the response reaches the client end...
var WidgetInstance = function () {
this.GetErrors = function () {
$.ajax({
url: '/Management/GetLoggedOnUsersByMinutes/',
type: 'GET',
cache: false,
async: false,
success: function (result) {
result = (typeof (result) == "object") ? result : $.parseJSON(result);
loggedOnUsers = result;
}
});
},.....
I did a simple solution for this..
I just called my populating functions in the onSuccess event of the GetErrors() of my control and everything worked perfectly..
Related
I have a form in my page. When a user clicks a button if have no problem this code must navigate my Tile page. I am taking this problem:Uncaught TypeError: Cannot read property 'navTo' of undefined.
This my code:
onPressGonder: function (evt) {
var sURL = "xxxxxx";
$.ajax({
url: sURL,
dataType: "json",
success: function(data) {
if (data.ResultCode === 7) {
sap.m.MessageToast.show("Error:" +data.Alerts[0].Message+"") ;
} else {
sap.m.MessageToast.show("Login succesfull.");
sap.ui.core.UIComponent.getRouterFor(this).navTo("Tile");
}
}
});
}
You are having a scope problem. The function provided as a success callback is a anonymous function called later on by jQuery.ajax. Therefore it is NOT a method of your controller and thereby does not know this. By default (as in your anonymous function) this refers to the window object. So what your basically doing is:
sap.ui.core.UIComponent.getRouterFor(window).navTo("Tile");
And the window object obviously does not have a router or a navTo method ;)
The easiest workaround is to make this available via the closure scope as follows:
onPressGonder: function (evt) {
var sURL = "xxxxxx",
that = this;
$.ajax({
url: sURL,
dataType: "json",
success: function(data) {
if (data.ResultCode === 7) {
sap.m.MessageToast.show("Error:" +data.Alerts[0].Message+"") ;
} else {
sap.m.MessageToast.show("Login succesfull.");
sap.ui.core.UIComponent.getRouterFor(that).navTo("Tile");
}
}
});
}
Another probably more elegant solution is to use the context property of jQuery.ajax. It will ensure that any ajax callback will be executed with the provided context (meaning whatever you pass as a context will be referred to as this inside your callbacks):
$.ajax({
...
success: function(data) {
...
sap.ui.core.UIComponent.getRouterFor(this).navTo("Tile");
},
context: this
});
I use JQuery Ajax function :
$.ajax({
url: ...,
success: function (){
...
},
...
});
I need to execute some code just before every call of the success function (but after the response has been received).
I suppose that this success function is triggered like an event, so is there a way to make an other function call in place of success one's?
You can use the Global Ajax Event Handlers methods to do this.
Sounds like you might want to use AjaxComplete:
$(document).ajaxComplete(function(){
// do something here when ajax calls complete
});
Be warned -- this will occur for EVERY jQuery ajax call on the page...
You could also call that other function right at the biginning of done:
$.ajax({
url: ...,
done: function (){
someOtherFunction();
},
...
});
This should pretty much accomplish what you described in your question.
Is beforeSend what you are looking for:
$.ajax({
url: "...",
beforeSend: function (x) {
//do something before the the post/get
}
}).done(function (data) {
//done code
});
I succeed in calling an other function just before success one by replacing $.ajax() by a custom function like :
function mYajax(options) {
var temporaryVariable = options.success;
options.success = function () {
console.log('Custom')
if (typeof temporaryVariable === 'function')
temporaryVariable()
};
return $.ajax(options);
}
$('button').click(function () {
mYajax({
url: "/echo/json/",
data: {
foo: "bar"
},
success: function (data, textStatus, jqXHR) {
console.log('succeed action');
},
});
});
I have a situation where in I m doing a number of AJAX calls using jquery and in turn returning JSON data from those calls into some variables on my page.
The issue is that the Ajax call takes a little time to get processed and in the mean time my control shifts to next statement where I intend to use the output of AJAX call.
Since the call takes time to return the data I am left with empty object that fails my function.
is there any way where I can wait for the finish of AJAX call to happen and proceed only when the result is returned from the call???
so this is my code where in I am trying to return transactionsAtError to some other jquery file where the control shifts to next statement before this call gets executed
this.GetTransactionAtErrors = function (callback) {
var transactionsAtError;
$.ajax({
url: ('/Management/GetTransactionsAtError'),
type: 'POST',
cache: false,
success: function (result) {
if (result && callback) {
transactionsAtError = (typeof (result) == "object") ? result : $.parseJSON(result);
}
}
});
return transactionsAtError;
}
Assuming you are using jQuery's $.getJSON() function, you can provide a callback function which will be executed once the data is returned from the server.
example:
$.getJSON("http://example.com/get_json/url", function(data){
console.log("the json data is:",data);
});
EDIT:
After seeing the code you added i can see what's your problem.
Your return transactionsAtError; line runs independently of the ajax call, i.e it will run before the ajax is complete.
you should just call your callback inside your success: function.
example:
this.GetTransactionAtErrors = function (callback) {
$.ajax({
url: ('/Management/GetTransactionsAtError'),
type: 'POST',
cache: false,
success: function (result) {
if (result && callback) {
var transactionsAtError = (typeof (result) == "object") ? result : $.parseJSON(result);
callback(transactionsAtError);
}
}
});
}
When you have your result in scope you can check wait for ongoin ajax calls to finish by using es6 promise:
function ajaxwait()
{
return(new Promise(function(resolve, reject) {
var i = setInterval(function() {
if(jQuery.active == 0) {
resolve();
clearInterval(i);
}
}, 100);
}));
}
You can use this like.
ajaxwait().then(function(){ /* Code gets executed if there are no more ajax calls in progress */ });
Use an es6 shim like this https://github.com/jakearchibald/es6-promise to make it work in older browsers.
I have two function of jQuery. Both the functions are calling jQuery ajax.
both have property async: false.
In both the function I am redirecting on basis of some ajax response condition.
In the success of first function I am calling the another function and then redirecting to another page. But my first function is not redirecting because my second function is not waiting of the response of the first function.
Hope problem is clear from my question.
my first function is as below
function fnGetCustomer() {
function a(a) {
$("#loading").hide();
//on some condition
//other wise no redirection
self.location = a;
}
var b = $("input#ucLeftPanel_txtMobile").val();
"" != b && ($("#loading").show(), $.ajax({
type: "POST",
url: "Services/GetCustomer.ashx",
data: { "CustMobile": b },
success: a,
async: false,
error: function () {
$("#loading").hide();
}
}));
}
and my second function I am calling the first function
function fnSecond() {
$.ajax({
type: "POST",
url: "some url",
async: false,
data: { "CustMobile": b },
success: function(){
fnGetCustomer();
//if it has all ready redirected then do not redirect
// or redirect to some other place
},
error: function () {
$("#loading").hide();
}
}));
}
I am using my first function all ready. So I don't want to change my first function.
A set up like this should work;
$.ajax({
data: foo,
url: bar
}).done(function(response) {
if (response == "redirect") {
// redirect to some page
} else {
$.ajax({
data: foo,
url: bar
}).done(function(response2) {
if (response2 == "redirect") {
// redirect to some other page
} else {
// do something else
}
});
}
});
I've not tested doing something like this, but that's roughly how I'd start off
If you don't need the result of the first AJAX call to be able to send the second you could add a counter to keep track of the calls. Since you can send both calls at the same time it'll be a lot more responsive.
var requestsLeft = 2;
$.ajax({
url: "Firsturl.ashx",
success: successFunction
});
$.ajax({
url: "Secondurl.ashx",
success: successFunction
});
function successFunction()
{
requestsLeft--;
if (requestsLeft == 0)
doRedirectOrWhatever();
}
If you absolutely need to do them in order you could do something like this. My example expects a json response but that's no requirement for this approach to work.
var ajaxurls = ["Firsturl.ashx", "Secondurl.ashx"]
function doAjax()
{
$.ajax({
url: ajaxurls.shift(), // Get next url
dataType: 'json',
success: function(result)
{
if (result.redirectUrl) // or whatever requirement you set
/* redirect code goes here */
else if (ajaxurls.length>0) // If there are urls left, run next request
doAjax();
}
});
}
doAjax();
Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});