Ajax Call not being accessed in most pages - javascript

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!

Related

Ajax call not working for every controller

I am using mvc 4 ,I need to call controller actions using ajax.So I created a new scripts.js file at Scripts folder.In my project there are lot of controllers and I wrote ajax functions for each of them in the same js file.But except the default controller other controllers are not initiated by the ajax code. Scripts.js file contains:
$(document).ready(function () {
//END COUNTRY ................................................................
$("#savecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/SaveCountry',
data: {name: $('#country').val() },
dataType: 'json', encode: true,
async: false,
cache: false,
//contentType: 'application/json; charset=utf-8',
success: function (data, status, jqXHR) {
// alert("success");
console.log(jqXHR);
console.log(status);
console.log(data);
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(jqXHR);
//console.log(textStatus);
//console.log(errorThrown);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$("#updatecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/Update',
data: { id:$('#id').val(), name:$('#country').val() },
dataType: 'json', encode : true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$('#cancel').click(function () {
$('input:text').val('');
});
//$('.deleteRow').click(function () {
// alert('ewewrwr');
// $.ajax({
// type: "POST",
// data: { id: $('#id').val() },
// url: "/Country/DeleteCountry",
// dataType: 'json', encode: true,
// async: false,
// cache: false,
// success: function (data, status, jqXHR) {
// alert("success");
// //$.each(data, function (index, customer) {
// // alert(customer.Name + " " + customer.UserName);
// //});
// },
// error: function (jqXHR, textStatus, errorThrown) {
// console.log(jqXHR);
// if (typeof (console) != 'undefined') {
// alert("oooppss");
// }
// else { alert("something went wrong"); }
// }
// });
//});
$("#updateoffer").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Offer/Update',
// contentType: "application/json; charset=utf-8",
data: { id: $('#id').val(), name: $('#offer').val(), description: $('#description') },
dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
});
Here Country is the default controller and ajax call working well.But call to Offer controller Update ajax not working .Page not responding error will result.
You should take project name to baseUrl for call ajax function.
$(document).ready(function(){
var baseurl = "";//your project name
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry', // baserurl+"/controller name/action"
.....
}
The accepted answer has a serious flaw in commercial deployments, so offering alternatives.
Yes, you need the base address of the website, but you do not want to hard-wire it into the code.
Option 1
You can inject a global javascript variable into your master page as a string constant.
e.g. put this at the top of your master page
<script>
window.baseurl = "#Url.Content("~/")";
</script>
then just use window.baseurl prepended to your URLs
e.g
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: window.baseurl+'/Country/SaveCountry',
Option 2
You can inject a data- attribute into the DOM in your master page. e.g. on the body tag
then extract it using jQuery:
e.g.
var baseurl = $('body').data('baseurl');
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry',
Option 3 (I do not advise this one)
Inject the string literal into your Javascript
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("SaveCountry", "Country")",
This is bad for maintenance and debugging as the code must be in a Razor view in order to work.
We used to use option 2 a lot, but now tend to use option 1.

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

Jquery Ajax callback not working calling success and failed

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

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

function calling ajax returns false

I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}

Categories

Resources