Jquery Ajax callback not working calling success and failed - javascript

I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.
The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?
Here is my code:
$('input[type=button]').click(function () {
bookingID = $(this).closest('tr').attr('id');
sendEmail(bookingID, this);
});
function sendEmail(id, thisContext) {
var data = JSON.stringify({ 'id': id });
/*******
This calls setButtonSuccess AND setButtonFailed which is wrong
I want to execute only setButtonSuccess OR setButtonFailed depending on whether successful or not
*******/
jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};
function setButtonSuccess(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-success");
};
function setButtonFailed(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-warning");
};
function jsonPOST (pWebServiceFunction, pData, pOnCallbackSuccess, pOnCallbackFailed, async) {
$.ajax({
type: "POST",
url: url + pWebServiceFunction,
data: pData,
contentType: "application/raw; charset=utf-8", dataType: "json",
async:async,
processdata: true,
success: function (msg) {
if (msg.success === true) {
pOnCallbackSuccess(msg);
}
else {
pOnCallbackFailed(url + pWebServiceFunction);
}
},
error: function (xhr, ajaxOptions, thrownError) //When Service call fails
{
pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
}
});
};
Thanks

You're calling the functions immediately instead of passing a function that will call them later. It should be:
jsonPOST("~Booking/ResendEmail", data, function() {
setButtonSuccess(thisContext, "Email Sent");
}, function() {
setButtonFailed(thisContext, "Email Failed");
}, false);

Related

Ajax Call not being accessed in most pages

This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!

Vue js 1.0 call a method within another method throws 'not a function'

I'm trying to reuse a method within another of my vue js methods like this :-
sendCode: function () {
this.showSection("SENDING");
$.ajax({
url: "someurl" + app.searchResponse.Id,
type: "POST",
contentType: "application/json",
success: function (result) {
if (result.Success) {
this.showSection("SMS SENT");
}
else {
this.showSection("SMS FAILED");
}
},
error: function (error) {
console.log(error);
this.showSection("SMS FAILED");
}
});
},
showSection: function (section) {
return app.ui.currentSection = section;
}
But i get caught Type Error stating this.showSection() is not a function.
inside ajax callbacks, vue instance this is not available because it's a different scope. So declare $this = this with a variable before ajax and use $this inside ajax callbacks.
sendCode: function () {
this.showSection("SENDING");
var $this = this;
$.ajax({
url: "someurl" + app.searchResponse.Id,
type: "POST",
contentType: "application/json",
success: function (result) {
if (result.Success) {
$this.showSection("SMS SENT");
}
else {
$this.showSection("SMS FAILED");
}
},
error: function (error) {
console.log(error);
$this.showSection("SMS FAILED");
}
});
},

ajax jquery message show after the function completed

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

ajax not called..even alerts are not working

i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});

Javascript - Handling a AJAX call response from a web service

I'm using Javascript and Jquery to call a web service. The service should return an object. If the object returned contains Result=0, I want to show an alert, and if it doesn't, I want to show a different alert.
My code is shown below. I've tried "if (data.Result)" and "if (data.Result=0)", and neither of them work and show the "stock added" popup message.
Any help would be appreciated.
Object returned:
data: Object
Booking: Object
BookingId: "28eec5f6-29a7-e411-941a-00155d101201"
BookingProductIds: null
BookingStatus: 2
CrossSellProducts: null
ErrorMessage: ""
Result: 0
Javascript code:
function generateOrder() {
ABC.TixService.AddStockProduct(null, null, productRequest, ticketingRequest, function (context, data) {
if (data.Result) {
alert("stock added");
}
else
alert("error");
});
AddStockProduct: function (context, bookingId, productRequests, request, action) {
$.ajax({
url: 'TixService.svc/AddStockProduct',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ bookingId: bookingId, productRequests: productRequests, request: request }),
context: { context: context, action: action },
success: function (data) {
this.action(this.context, data.AddStockProductResult);
},
error: function (xhr, ajaxOptions, thrownError) {
ErrorResponse(xhr, thrownError);
}
});
},
Shouldn't the test be:
if(data.Result === 0){
alert('stock added');
}

Categories

Resources