Sapui5 navTo not working in ajax statement - ajax

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
});

Related

call function in ajax success callback

Is it possible to call a function in success callback of ajax request?
For example I have something like that :
constructor(private http: HttpClient,private serviceComposition: CompositionService) { }
[...]
save() {
var isValid = this.isValidCompo();
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
this.serviceComposition.changeValue(isValid);
})
}
}
I want to call a function of my service (named : changeValue() ) if my ajax request is a success.
But I have this error message : core.js:12632 ERROR TypeError: Cannot read property 'changeValue' of undefined
Do you know if it's possible to resolve that ?
I am suspecting this binding is going wrong in call backs,
prefer using arrow function because of "this" operator binding.
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done((data) => {
this.serviceComposition.changeValue(isValid);
})
}
if not u can store this reference in a variable and call it
var self = this;
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
self.serviceComposition.changeValue(isValid);
})
}
Use an arrow function to access this of your parent scope. In your example, this is referring to your jQuery XHR object.
So:
// [parent scope]
$.ajax({
...
}).done((data) => {
// [child scope]
// `this` now refers to [parent scope], so the following is valid
this.serviceComposition.changeValue(isValid);
});
Another common practice prior to arrow functions (ES6) would've been assigning a const self = this; variable in the [parent scope] area to be accessed in the child method. Either method works the same.
Also check out the MDN docs on this. It's a confusing topic for many.

What is callback function in AJAX? How to implement a callback function in PreSaveAction function of SP2013 list NewForm?

I want to store the value of a variable and use it outside the ajax call. But being an asynchronous call it is giving me initial value of that variable. I am implementing my custom code for some validations in PreSaveAction function since I have to do validations on Save button click of SharePoint NewForm,Following is my code,
<script type="text/javascript">
var titleItem;
var flg=0;
var dataFromServer;
function PreSaveAction()
{
titleItem = $("input[title='Title']").val();
$.ajax({
url:"http://sp13dev:4149/Appraisals/_api/web/lists/GetByTitle('SkillMaster')/items?$select=Id,Title&$filter=Title eq '"+titleItem+"'" ,
type: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
if(data.d.results.length>=1)
{
flg=1;
$("#labelTitle").html("Skill already exists. Please enter another name.");
}
else
{
flg=0;
$("#labelTitle").html("");
}
},
error: function (error) {
alert(JSON.stringify(error));
}
});
if(flg==1)
{
// $("#labelTitle").html("Skill already exists. Please enter another name.");
return false;
}
return true;
}
</script>
It seems like you have misplaced your return call. You should have your return placed inside your
if(data.d.results.length>=1)
statement inside the success callback function.

Populate Textbox with Session Variable When Opening New Window

I am attempting to populate a textbox in a new window with a Session variable from a parent window using an ajax call. When using Fiddler, I receive a 200 message, however, when ran from code, I'm getting a 500 Error.
I am aware that the ajax call is only returning an alert with the entire JSON result at this point because I haven't gotten to the step to actually pull the session variable yet.
Please offer any additional solutions to pull the Session variable from the parent window.
My JS from the parent is as follows:
function openRelatedItems(ReportID)
{
window.open('../WebUserProvider/ReportLibraryView.aspx?r='+ ReportID,'mywin','left=50,top=50,location=no,resizable=yes, status=yes, scrollbars=no, titlebar=no, channelmode=no, directories=no');
return false;
}
My JS from the window popup is as follows:
function callAjaxMethod() {
$.ajax({
type: "GET",
url: "ReportLibraryView.aspx/GetSetSessionValue",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
}
$(function () {
var value = callAjaxMethod();
var b;
});
My codebehind for the AJAX call is as follows:
[System.Web.Services.WebMethod (EnableSession = true)]
public static string GetSetSessionValue()
{
return HttpContext.Current.Session["AppealNo"].ToString();
}

using On success function in Jquery Ajax call

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..

synchronize two ajax jquery function

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();

Resources