ajax jquery message show after the function completed - javascript

I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?

You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.

Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},

Related

undefined variable under jquery payload

I'm trying to post some data to an API but I'm struggling with javascript.
function pushData() {
let rawdata;
$.ajaxSetup({
async: false
});
$.getJSON('https://api.db-ip.com/v2/free/self', function(result) {
result = rawdata;
})
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
}
})
}
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
I'm getting Uncaught ReferenceError: message is not defined although I think that message is a global variable, so it should be called successfully on the payload? What I'm I doing wrong here?
Thanks to anyone for his reply in advance, I'm just trying to write a quick script for my API here.
message is a local variable in the pushData() function, not a global variable. But even if it were global, you'd have to call the function before the second $.ajax() call.
Move the second AJAX call inside the function so you can access the variable. And embrace asynchrony, don't fight it with async: false. Nest the successive AJAX calls inside the callback function of the previous one.
function pushData() {
$.getJSON('https://api.db-ip.com/v2/free/self', function(rawData) {
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
});
},
error: function() {
console.log("error");
}
})
}

How to use async/await for getting data through sharepoint online?

I am able to get some data in SharePoint online using rest and js, and it is solving my purpose also but then i am using async: false to make it synchronous, which i think is not the recommended way. so when i looked for alternative solution, i found out about async/await. Is it possible to use async/await in the code below? Please suggest.
function GetUserProperties(user) {
//getting user properties for a user
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v=%27i%3A0%23.f|membership|" + user + "%27";
$.ajax({
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
url: url,
success: function(data) {
successUsersInfo(data);
},
error: function(data1) {
alert("ERROR");
}
});
}
function successUsersInfo(data) {
// logic to call data
secondFunction(); //then i am calling another function
}
function secondFunction() {
$.ajax({
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
url: url,
async: false,
success: function(data) {
//logic to get data
},
error: function(data1) {
alert("ERROR");
}
});
//now my third function depends on the values of second data
//and i am using async:false, to make it synchronous
thirdFunction();
}
function thirdFunction() {
//logic to use second function data since my third function is dependent on second function
}
Use $.Deferred() in such senarios, which will help to chain the functions and you will be able to use then operator
function GetUserProperties(user) {
var deferred = $.Deferred();
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v=%27i%3A0%23.f|membership|" + user + "%27";
$.ajax({
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
url: url,
success: function (data) {
deferred.resolve(data);
},
error: function (data1) {
alert("ERROR");
}
});
return deferred.promise();
}
function secondFunction() {
var deferred = $.Deferred();
$.ajax({
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
url: url,
async: false,
success: function (data) {
deferred.resolve(data);
},
error: function (data1) {
alert("ERROR");
}
});
return deferred.promise();
}
function thirdFunction() {
var deferred = $.Deferred();
$.ajax({
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
url: url,
async: false,
success: function (data) {
deferred.resolve(data);
},
error: function (data1) {
alert("ERROR");
}
});
return deferred.promise();
}
Now you can call these function as follows
GetUserProperties("uerid")
.then(function (secondFuncData)
{
secondFunction(secondFuncData)
.then(function (thirdFuncData)
{
thirdFuncData(thirdFuncData)
.then(function (finalData)
{
console.log(finalData);
})
})
})
Function will start with var deferred = $.Deferred(); and end with return deferred.promise();. And return the data in success using deferred.resolve(data);
$.ajax already returns a promise. It's jQuery promise that isn't necessarily Promise/A+ compliant (this was fixed in jQuery 3), but it is thenable, so it can be handled by await naturally. $.ajax requires no callbacks to return a promise:
async function GetUserProperties(user) {
...
let result = await $.ajax({
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
url: url
});
...
}

Ajax Response is not defeined

I am quite green when it comes to AJAX and am trying to get an email address from an ASP.Net code behind function
When using the below code I am getting the error as per the title of this issue.
This is the code I am using
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
});
which is an adaptation of the code from this site.
ASP.Net Snippets
When changing the line
success: OnSuccess to success: alert(response) or success: alert(data)
I get the error up, but if I use success: alert("ok") I get the message saying ok so I suspect that I am getting into the function as below.
<System.Web.Services.WebMethod()> _
Public Shared Function FindEmailAddress(ByVal id As String) As String
Dim response As String = GetEmail(id)
Return response
End Function
I would be extremely grateful if someone to help me and let me know where I am going wrong on this one.
thanks
I think you have can check the state of failure by using this code below as I think there is wrong syntax used by you.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: JSON.stringify({id: ' + $(".txtRequester").val() + ' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, header){
console.log(data);
},
error: function (response) {
alert(response.d);
}
});
}
});
then definitely you will get error response, if your success won't hit.
You have not called the function thats why its never get called.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
ShowCurrentTime();
});
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Onsuccess(response);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
This will help :)
use ajax directly ,
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
var cond = $(".txtRequester").val();
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: {id:cond},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
Change $('.txtRequester') to $('#txtRequester')
and
Change $("txtRequester").val to $('#txtRequester').val()

Call ajax.fail() from ajax.success()

So all I want to do is conditionally call the .fail method from within the .success method, how?
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { ajaxCall.fail(); return; }
alert("success");
})
.fail(function () {
alert("fail");
});
$.ajax return a promise so you can't do it directly. Your best shot is that :
var fail = function () {
alert("fail");
};
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { fail(); return; }
alert("success");
})
.fail(fail);
You can simply call as this.fail(); as shown below :-
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail")
{
this.fail();
return;
}
alert("success");
})
.fail(function () {
alert("fail");
});
For more information :-
http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/
just use the "this" keyword to actually call any other method of the ajax call, I have made a sample for error method.
$.ajax({
url: 'url',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
type: 'GET',
success: function (dataReturn) {
this.error('error called explicitly');
},
error: function (errorMessage) {
if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
//actual error code
else
alert(errorMessage);
}
});
hope this helps :)

Have JavaScript method return the result of jQuery AJAX call [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
function Run(someJsonObject) {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
}
var result = Run({dummy:'dummy'});
If I'm not mistaken, the above function will not return true or false, but rather it will be undefined. I want to return the result of the AJAX call, I'd prefer to make it synchronous (I realize I'm using AJAX). How would I accomplish this?
You are backwards, let your ajax run first.
$(function () {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
DoStuffWithResult(data.d);
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
});
function DoStuffWithResult(result){
//time to rock, i have my result
}
If you add the async option to your jquery call, it stops being asynchronous.
That being said, this is usually a bad idea and can probably be handled a better way. Usually, this is done by doing your ajax call first and working with your data in your success function.
If you are really adamant about doing it this way, though, this is what you want:
function Run(someJsonObject) {
var result;
$.ajax({
async: false,
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
result = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
result = false;
}
});
return result;
}
var result = Run({dummy:'dummy'});
If you want to make an ajax request in jquery synchronous and have it be the return value of Run:
function Run(someJsonObject) {
var returnValue;
$.ajax({
type: "post",
async: false,
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
returnValue = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
returnValue = false;
}
});
return returnValue;
}
I added async: false to the ajax options and used a local variable (accessible to the success and error handlers) as the return value.
You can't just return $.ajax(/* snip */) because that returns a promise object.
You can simplify
$.post('/MyWebService', JSON.stringify(someJsonObject), function(r) {
if(r.success) {
// do something (1)
} else {
// do else something (2)
}
},'json').error(function() {
alert('comunication error');
});
If you get any response like this
{ "success": true, data: "my_data" }
execute something (1)
else (2)
If not a valid json or timeout trigger .error()

Categories

Resources