Ajax request fails in Cordova application Visual studio - ajax

I am Using visual studio 2015 to build android application using cordova. It works fine in the emulator. but when i am releasing it ajax request is failing where as same thing works on emulator.no error is seen in log but only the ajax error.
var url = 'http://oployeelabs.net/demo/demo_doctorola/doctorola-server/index.php/doctor_panel_api/validation_modified/format/json';
load();
$.ajax({
url: url,
data: { cell_no: phone, pass: pass },
method: 'POST',
dataType: 'json',
success: function (data) {
alert();
if (data == "false")
{
alert("Wrong password");
}
else
{
localStorage.doctorid = data[0].id;
localStorage.userinfo = JSON.stringify(data);
$.ajax({
url: "http://oployeelabs.net/demo/demo_doctorola/doctorola-server/index.php/api/information/meta-info/location/id/"+data[0].id+"/username/9791a47fef07649b1c3e70749e898153/password/2d593e25d0560b19fd84704f0bd24049/format/json",
method: 'GET',
dataType: 'json',
success: function (dt) {
localStorage.Chamberinfo = JSON.stringify(dt);
mainView.router.loadPage({ url: 'menu.html', ignoreCache: true, reload: true })
$('.toolbar').removeClass('hide');
}
});
}
//if (data === "ok") {
// $(".confirm_appointment").remove();
// var anc = "<a id='confirm_appointment' class='confirm_appointment' style='opacity: 0;' href='confirm.html' data-context='{\"slot_id\": \"" + slot_id + "\",\"slot_date\": \"" + slot_date + "\", \"email\": \"contact#john.doe\"}'>profile</a>";
// $(document).find('.page_content').append(anc);
// $(".confirm_appointment")[0].click();
//}
//else {
// myApp.hidePreloader();
// myApp.alert("", "Sorry, this slot has been booked. Please try with another slot.");
//}
},
error: function (xhr, status, exception) {
alert(xhr.responseText+" "+status+" "+ exception);
console.log("Error: " + xhr.responseText + " - " + exception);
},
complete: function () {
myApp.hidePreloader();
unload();
}
});

Strangely it worked after i uninstalled whitelist plugin and installed it again. i dont know why but i think its a bug of cordova.

Related

Getting 500 error on some docs but not others. Why?

My add-in for MS Word works for some docs but not others. For test-doc-A, it works fine. I get the results I want. test-doc-B throws a 500 error on the $.ajax call that sends the text to the server. Both docs are one page. Granted, 500 errors are supposed to be "server" side. But what could be so different between these docs that's causing this?
The server logs don't indicate anything (to my eye) that tells me what the issue is.
test-doc-A (All Good)
2019-02-28 23:41:33 MyApiEndPoint POST /api/Document/Upload X-ARR-LOG-ID=8b253a46-bca8-4981-9ded-3fdf671fe63c 443 - myIpAddressMozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+Touch;+rv:11.0)+like+Gecko - https://localhost:44399/Home.html?_host_Info=Word$Win32$16.01$en-US myServerUrl 200 0 0 664 3793 46
test-doc-B (500 Error)
2019-02-28 23:42:13 MyApiEndPoint POST /api/Document/Upload X-ARR-LOG-ID=b0095aa0-9fc5-4a26-83b0-40d44ff160ba 443 - myIpAddress Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+Touch;+rv:11.0)+like+Gecko - https://localhost:44399/Home.html?_host_Info=Word$Win32$16.01$en-US myServerUrl 500 0 0 326 11306 46
Is there some way to compare the text that's being sent? Am I using the right method 'range.load("text")'?
The only difference between the docs appears to be formatting. But, I'm just sending the text, regardless of formatting, aren't I?
Do I need to "clean" the text before sending? Just so confused, right now.
function sendTextToServer() {
Word.run(function (context) {
var doc = context.document;
var range = doc.body;
range.load("text");
return context.sync()
.then(function () {
var myData = '{\"FileName\": \"WordAddIn-Test\",\"Text\": \"' + range.text + '\" }';
// begin promise
var promise = $.ajax({
url: urlToUse + "/Upload",
method: 'POST',
contentType: 'application/json; charset=utf-8',
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Negotiate");
},
crossDomain: true,
dataType: 'json',
processData: false,
cache: false,
data: myData,
success: function (data) {
log("sendTextToServer Success: " + JSON.stringify(data));
},
error: function (xhr, textStatus, errorMessage) {
log("sendTextToServer promise Error: " + errorMessage + " : " + JSON.stringify(xhr) + " : " + textStatus);
}
});
// end promise
// do something with promise
promise.done(function (data) {
myDocID = data.documentID;
log("sendTextToServer myDocID: " + myDocID);
log("url = " + urlToUse + "/Status?documentID=" + myDocID);
setTimeout(function () { goDoSomethingElse(); }, 2000);
});
})
.then(context.sync);
}).catch(function (error) {
log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
log("Debug info: " + JSON.stringify(error.debugInfo));
log("Something went wrong. Trying again");
}
});
}
"Looks like I picked the wrong week to quit sniffing glue."
~Steve McCroskey

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

Ext.Msg.show in ajax not append the page

I have a function for saving data. Before saving data there is dialog confirmation Yes or No. While I click option Yes the page behind this is back to the gridview (it's list). What i want is while click Yes the page behind is not change.
This is my function :
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
var str = "<br/><br/><span style='color:red;font-weight:bold'>Success add new PF !</span>";
MsgBox2("Budget Validation", result.Error + str);
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I add new dialog confirmation like this, but it does not work (didn't append the page after click Yes button):
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
$.post(root + "PF/GetSetupName", function (datas) {
if (datas == "FILTER_BRAND") {
Ext.Msg.show({
title: 'Over Budget',
msg: 'Budget is over. Modify or Not ?',
fn: function (btn) {
if (btn == "yes") {
SaveData("none");
}
else {
CancelData();
}
},
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION
});
}
});
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I try also separate this Ext.Msg.show in another function. but it doesn't work. Is there any idea please ?
I've found that when I try to do a mask and an ajax request at the same time, Ext gets overwhelmed and will not properly display the mask.
To fix this, I delay doing my ajax request until Ext & the browser have had enough time to properly display the mask. It generally does not need much time. In the example below, it waits 50 ms before posting.
Ext.get(document.body).mask("Updating data .. Please Wait ...", 'x-mask-loading');
Ext.defer(function() {
Ext.Ajax.request({ ... });
}, 50);
This gives the browser enough time to render the masking before it has to do anything else.

wrong ajax callback invoked using cordova

In my jqm app I make a POST using jQuery $.ajax sending and receiving json data. Everything is fine in the browser and on iPhone; on Android I noticed that when this server response is like this:
{ "code" : 500,
"errorMsg" : "bla bla bla",
"errors" : null,
"status" : "INTERNAL_SERVER_ERROR",
"success" : false
}
the ajax invokes the "error" callback and not the "success". This happens only on android and only if I include corova-2.0.0. js on the project. Any help?
I'm using cordova-2.0.0 with jqm 1.3.1 and jQuery 1.9.1
Here's my code:
var ajax = $.ajax({
type: "post",
url: url,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
timeout: 30000
});
var success = function (d) {
if(d.success==true && obj.success)
obj.success(d.data);
else
{
var msg = parseErrors(d);
console.log(msg);
//open page passing results
obj.msgBus.fire("RequestResult", {
callback: function(){ obj.msgBus.fire("Welcome");},
success: false,
text: msg
});
}
};
var error = function (xhr, status, e) {
console.log('error ajax url:[' + url + '] status:[' + status + '] error:[' + e + ']');
if (obj.error) {
if ((typeof e == 'string'))
obj.error({
statusText: e,
code: xhr.statusCode,
text: xhr.responseText
});
else {
e = $.extend(e, {
statusText: status
});
obj.error(e);
}
}
};
var complete = function () {
if (obj.complete) {
obj.complete();
}
};
var parseErrors = function(d){
console.log( d);
if(d.errors==null){
return d.errorMsg;
}
else
{
var res="";
for (var i=0;i< d.errors.length;i++){
res+= "{0}: {1} <br/>".format( d.errors[i].field, d.errors[i].errorMsg);
}
return res;
}
};
ajax.success(success).error(error).complete(complete);
where data is an object like this:
{
"date" : 1371679200000,
"idBeach" : "1",
"idStuff" : 3,
"idUser" : "8",
"numStuff" : 1
}
Try this, it works for me
$.ajax({
async: false,
type: "POST",
url: "Your_URL",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, object) {
alert(obj.Data);
});
},
error: function () {
alert("There was an error loading the feed");
}
});

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

Resources