Refreshing a AJAX call - ajax

I have an AJAX call in cordova application.I have checked the availability of internet connection before actual call. But some times in mobile internet connectivity is lost for few seconds after the call is made and thus device does not read any reply from web-service. It goes to error part of Ajax call. I wants to make this Ajax call again so that DOM should get created
call AJAX function is
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if(isOnline == false)
{
alert('Internet is not running. Please reconnect and try');
return 0;
}
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
// alert(JSON.stringify(response));
errorFunction(response);
}
});
}

If you want to retry after an error, you can just re-call your function recursively, or do something like this to prevent too many retries:
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if (isOnline == false) {
alert('Internet is not running. Please reconnect and try');
return 0;
}
function tryAjax(retryCount) {
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
if (retryCount > 10) {
errorFunction(response);
} else {
tryAjax(retryCount + 1);
}
}
});
}
tryAjax(0);
}

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

AJAX dont call WebMethod but returns HTML

I had read a lot of questions here on Stackoverflow about AJAX calls to WebMethods, and I tried a lot of things and nothing works.
My AJAX method doesnt call the WebMethod on server side but returns success and the entire HTML of the page.
This is the AJAX:
$("[id*=butLogin]").click(function () {
var obj = {};
obj.pEmail = "EMAIL"; //$.trim($("[id*=txtName]").val());
obj.pPassword = "PASSWORD"; //$.trim($("[id*=txtAge]").val());
$.ajax({
type: "POST",
url: "login.aspx/logOn",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
failure: function (msg) {
alert(msg.d);
},
error: function (msg, merr, derr) {
alert(msg.d);
}
});
return false;
});
And this is the WebMethod:
[System.Web.Services.WebMethod]
public static string logOn(string pEmail, string pPassword)
{
return "logged";
}
I believe is a simples mistake.
Thanks for your help.

I have 2 functions in my Javascript.One has multiple ajax calls to get the data and other displays the data.The functions are not executed in sequence [duplicate]

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
How to wait until jQuery ajax request finishes in a loop?
(5 answers)
Closed 5 years ago.
Sample Code
$( document ).ready(function() {
getData();
LoadData();
});
function getData() {
alert('getData');
Data='';
$.ajax({
type: "GET",
url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {},
processdata: true,
async: false,
success: function (json) {
Data= json;
alert('Data:' + Data);
},
error: function (e) {
alert('error ' + e.status + ' ' + e.responseText);
}
});
}
function LoadData() {
alert('LoadData');
}
The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData
The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}
What am I doing wrong.Please help me!!
why don't you call LoadData() after success?
like below
$( document ).ready(function() {
getData();
});
function getData() {
alert('getData');
Data='';
$.ajax({
type: "GET",
url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {},
processdata: true,
async: false,
success: function (json) {
data= json;
alert('Data:' + data);
LoadData();
},
error: function (e) {
alert('error ' + e.status + ' ' + e.responseText);
}
});
}
function LoadData() {
alert('LoadData');
}
UPDATE :
as you said , you are having multiple ajax calls,
one work around could be ,
try setting flag for each ajax call and make them true on respective success event , and lastly you need to call loadData() from all success completion and in loadData(){ ...} body check all the success are completed or not,
$( document ).ready(function() {
getData();
$flag1= flase;
$flag2= flase;
$flag3= flase;
$flag4= flase;
});
function LoadData() {
if($flag1 && $flag2 && $flag3 && $flag4)
{
alert('LoadData');
}
}
and in each ajax call's success
success: function (json) {
data= json;
alert('Data:' + data);
$flag1=true;
LoadData();
},
and don't forget to make all flag false in $(document).ready(){}
Inside success function call the LoadData() function
success: function (json) {
Data= json;
alert('Data:' + stackMonthData);
LoadData();
},
AJAX is asynchronous process ans ajax request start in different thread, so JavaScript not wait for AJAX response, so there is two possible way to handle it
Make AJAX request in synchronous process, by pass async:false in jquery AJAX parameter
call getData() function in AJAX callback liks success/error or done/faild callback something like
$.ajax({
// your code
}).done(function(data) {
getData()
}).fail(function(data){
});

e.preventDefault() prevents the kendo 'read' event but does not work for 'create' on update keypress in kendo popup editor

transport: {
parameterMap: function (data, operation) {
if (operation !== "read") {
return JSON.stringify(data);
} else {
return (data);
}
},
read: {
url: function () {
return moduleServiceRoot;
},
type: "GET",
dataType: "json",
async: true
},
create: {
url: function (rec) {
return moduleServiceRoot;
},
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
async: true
},
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
async: true
},
},
requestStart: function (e) {
console.log('request started');
if (e.type == 'create' & validInput == false) {
console.log('request started');
e.preventDefault();
}
}
in the above code validInput is always false. if i comment out the if statement kendo grid read operation is prevented (grid does not show any data) but if i uncomment it, it won't work for kendo create, when i hit update in kendo popup editor.
create: function (options) {
if (validInput) {
$.ajax({
url: moduleServiceRoot,
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
async: true,
data: JSON.stringify(options.data),
success: function (result) { // notify the data source that the request succeeded,
options.success(result);
},
error: function (result) { // notify the data source that the request failed
options.error(result);
}
});
}
}
and it works fine

Object doesn't support this property or method jquery ie8

I have two variables in my script view page, one called products and the other sites.
I have declared them like that.
Add.cshtml View:
$(function () {
products;
sites;
GetProductsAndSites(productsURL, sitesURL, '#Model.Key', false);
});
I call an ajax function, in another .js file.
People.js
function GetProductsAndSites(productsURL, sitesURL, secondLevelSiteKey, flag) {
$.ajax({
type: "POST",
url: productsURL,
async: false,
success: function (returndata) {
if (returndata.ok) {
**products = returndata.dataNames;**
//var tempProducts = returndata.dataNames;
$('#select-product').autocomplete({
delay: 0,
minLength: 1,
source: returndata.dataNames,
select: function (event, ui)
{
$.ajax({
type: "POST",
url: sitesURL,
data: { "productID": selectedProductID, "siteID": secondLevelSiteKey },
async: false,
success: function (returndata) {
if (returndata.ok) {
//products = tempProducts ;
**sites = returndata.dataNames;**
$('#select-site').autocomplete({
delay: 0,
minLength: 1,
source: returndata.dataNames,
select: function (event, ui) {
$("#select-site").val(ui.item.label);
});
}
});
}
}
});
}
it throws "Object doesn't support this property or method" exception at (products = returndata.dataNames;) line...at first I thought it can not see the products vairalble, but then I realized that it can see the "sites" variable, so I commented the products line and expected that it would throw the same exception at the sites line, but it works just fine.
I have tried creating a local variable and store the returndata.dataNames in it instead of products vairalbe and then set products value before the sites line, but still it throws an exception. I tried to put the products line after the sites lines it threw the same exception at the products line also.
Help!
After searching and searching, I finally found my solution. Tested with IE8.
Override
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
jQuery.ajaxSettings.xhr = function() {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) { }
jQuery.support.cors = true;
}
}
Make the ajax request
$.ajax({
type: 'GET',
url: "your-url",
async: true,
cache: false,
crossDomain: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json'
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('ERROR: ' + errorThrown);
})
.always(function() {
// Do stuff
});
For me this answer helped, where I detect the IE browser and if its lower than 7 or so then set ActiveXObject else XMLHttpRequest.
jQuery.ajaxSettings.xhr: function() {
// detect if IE and older versions of IE
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) <= 7)
return new ActiveXObject("Microsoft.XMLHTTP");
else
return new XMLHttpRequest();
}
Reference:
Detect IE 7 or lower.
Difference between ActiveXObject and XMLHttpRequest.

Resources