Ajax call never gets called in phonegap for android - javascript

I searched similar questions but never found a proper answer. I am making app for multiple platforms using phonegap and JQM. I made index.html, which is "login page", with similar call. Index's call works, but the one below never gets called on my android device, even though it works both on chrome and safari.
I checked sever logs and there are no problems with "login", but as I said, there is no request from my android device when function below should be called.
//document.addEventListener("deviceready", onDeviceReady, true);
$( document ).bind( "mobileinit", function(){
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.loadingMessageTextVisible = true;
$.mobile.showPageLoadingMsg();
console.log('Page Started');
})
//var onDeviceReady = function(){
$( document ).ready(function (){
console.log('Start');
//$.support.cors = true;
//$.mobile.allowCrossDomainPages = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://ip/services/rest/contact/list',
callback: 'jsonpCallback',
jsonpCallback: 'jsonpCallback',
jsonp: '_jsonp',
contentType: 'application/json',
dataType: 'jsonp json',
timeout : 10000,
success: function(data){
var html ='';
console.log('Success');
$.each(data.response, function(key, value) {
html += '<li><a class=contact href="#" id="' + data.response[key].id + '" ><h1>' + data.response[key].label + '</h1><p>'+ data.response[key].customerName + '</p><p>' + data.response[key].phone + ', ' + data.response[key].email + '</p></a></li>';
$('#ul_id').append($(html));
html='';
console.log('conatct');
});
$('#ul_id').trigger('create');
$('#ul_id').listview('refresh');
},
error: function (xhr, ajaxOptions, thrownError){
alert("Status: " + xhr.status + ", Ajax option: " + ajaxOptions + ", Thrown error: " + thrownError);
//location.reload();
console.log('Blad');
},
});
});

What is the access origin value in your Android project config.xml file ?
your value should be as below :
<access origin=".*"/>

There was a problem with placing script and specific way that jqm work.

Related

Handling file download from ajax get request in JavaScript

I am using a python CGI server to handle a cgi-bin request that I am making from an ajax call.
I'm trying to download the information I'm receiving on the Python side from my browser, using a button that triggers the ajax call.
I have tried some different things I saw on StackOverflow, but nothing has helped.
function issueDownloadCmd(port) {
var statusURL = window.location.protocol + "//" + window.location.host + "/cgi-bin/sod_log.py" + "?" + "down" + port.toString();
$.ajaxSetup({ 'cache': true });
$.ajax({
type: 'GET',
url: statusURL,
error: function (xhr, desc, exception) {
$('#traceStatus').html("Fail: response=" + xhr.status + "\nbecause: " + desc + "\nexception: " + exception);
},
success: function (data) {
console.log("data was downloaded");
}
});
return false;
}

JSON parsing and listing data in PhoneGap not working

I'm working on making an API call in PhoneGap. I wrote a function and calling it from a button click event, and I'm getting a response too, but I want to know how to display it. I have tried, but it's not working.
function getContactList() {
console.log("Entering getContactList()");
$.ajax({
url: "https://api.androidhive.info/contacts/",
dataType: "json",
cache: false,
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success: function(json) {
console.log("====CONTACTLIST ---->", json);
$(json).find("contacts").each(function() {
var html = '<li>' + $(this).find("name").text() +
' ' + $(this).find("name").text() + '</li>';
$('#contacts').append(html);
});
}
});
}
You're receiving JSON string which is then automatically converted by jQuery to a JavaScript object, so you can interact with it directly and shouldn't convert it to a jQuery object like $(json). Change the code inside your success to this:
for (var i = 0; i < json.contacts.length; i++) {
var c = json.contacts[i];
var html = '<li>' + c.name + ' ' + c.email + '</li>';
$('#contacts').append(html);
}
Note: it seems that there is an error in your code, you're using the find("name") twice. I changed it to name & email, but you can use any property of the contacts that you're getting.

jQuery order of events - unable to figure out proper solution

I'm trying to create an if/else statement within my jQuery code that changes the ajax URL and success function that gets fired off:
if($($this.context).find('img').hasClass('scheduler-img')) {
url = window.location.origin + "/recipes/" + planned_recipe_id +'/update_recipe'
} else {
url = window.location.origin + "/recipes/" + recipe_id +'/make_recipe'
success = successfulRecipeAdd(closest_date, image_url, recipe_id);
}
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
data: {
planned_for: planned_for,
meal_type: meal_type
},
success: (function() {
success
}),
error: (function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
})
});
I'm using this for a jQuery draggable and sortable table, so when I'm dragging and dropping the first item, it doesn't work because it tries creating the 'success' variable with an empty dataset. However, it does work for every subsequent drag/drop after.
function successfulRecipeAdd(closest_date, image_url, recipe_id) {
$.get( window.location.origin + "/recipes/get_recipes", function(data) {
console.log(data);
var planned_recipe_id = $(data).last()[0][0].id;
$(closest_date).append("<img src='"+image_url+"'class='scheduler-img col-md-12' id='"+ recipe_id +"' data-planned-id='"+planned_recipe_id+"'>");
});
}
I'm having a lot of trouble figuring out a way to write this that would allow me to create variables within the if/else statement, then fire off the ajax call using variables, rather than having two ajax calls within the if/else statement.

Jquery ajax call throws empty JS exception?

This function works on one page but not another. I've added all sorts of logging to try to find the error, but cannot. The output of this code on the broken page is:
[13:59:56.427] "here"
[13:59:56.428] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[13:59:56.428] "fileName=undefined"
[13:59:56.428] "lineNumber=undefined"
[13:59:56.428] "columnNumber=undefined"
[13:59:56.428] "here6"
That tells me it's getting into the exception handler, completely skipping my ajax() call, but it's not telling me the exception.
function test(server, port, username, password, spanId) {
spanId = "#" + spanId;
$(spanId).html("<img src='/images/ajax-small.gif'/>");
console.log("here");
try {
$.ajax({
dataType: "json",
type: "GET",
url: "/admin/test.html?server=" + server + "&port=" + port + "&username=" + username + "&password=" + password,
success: function(json){
console.log("here2");
if (json.httpStatus == "200") {
// Change the image to show success
$(spanId).html("<img src='/images/accept.png' title='success'/>");
}
else {
console.log("here7");
// Change the image to show failure
$(spanId).html("<span style='color:#b22222;'>" + json.httpStatus +"</span> <img style='vertical-align: middle;' src='/images/cancel.png' title='placeholder'/>");
}
console.log("here8");
$(spanId).tooltip({ content: json.msg});
},
// Display the URL
beforeSend: function(b,c,d) {console.log("beforesend: " + c.url);},
error: function(b,c,d) {console.log("here5");}
});
}
catch(e) {
console.log(e);
for (var i in e)
console.log(i + "=" + i[e]);
}
console.log("here6");
}
What could I do further to debug this?
UPDATE: Output of code on a working page
Here's the output of the exact same code but on the page where it is working:
[15:01:20.158] "here"
[15:01:20.159] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[15:01:20.159] "here6"
[15:01:21.661] GET https://localhost/images/accept.png [HTTP/1.1 200 OK 2ms]
[15:01:21.599] "here2"
[15:01:21.600] "here8"
So it obviously gets through the ajax call with flying colors. No errors, nothing. How can I find the problem on the page where it doesn't work?

javascript window.print() access is denied

I'm loading an image from a different domain in a img html element via $.ajax cross domain call and opening up a popup with the contents of the image as you can see in the code below
var printWindow= "";
methodName = "CreateVisitor";
$.support.cors = true;
$.ajax({
type: "get",
url: visitorServiceUrl + methodName + "/" + tenantId + "/" + userId
+ "/" + visitorid + "/" + visitorname + "/" + visitormobilenumber
+ "/" + visitorcompanyid + "/" + visitorcompanyname + "/" + visiteeid,
dataType: "jsonp",
async: false,
cache: false,
crossDomain: true,
success: function (data) {
var imageUrl = "";
imageUrl = data ? siteImageUrl + data : 'image/NO_IMAGE.jpg';
$("#visitorcard").attr('src', imageUrl);
printWindow = window.open($("#visitorcard").attr('src'), "_blank", 'width=200,height=200');
// printWindow.onload = function () {
// printWindow.print();
// };
setTimeout(function () { printvisitorcard(); }, 1000);
},
error: function (xhr, type, exception) {
//alert("Error: " + xhr + " : " + exception + " : " + type);
}
});
I then use a setTimeout() to try to automatically print the image to my network printer (I'm not sure if I'm in the same domain or not) like this
function printvisitorcard() {
printWindow.print();
printWindow.close();
}
However each time I'm getting a Microsoft JScript runtime error: Access is denied. on the printWindow.print(); line. I'm aware of cross domain issue with javascript but I still want to print the image. How do I overcome this error? Any help will be appreciated.
P.S
Firefox and Chrome do not throw this error however they also do not print the image.
change to something from your own domain.
Here is a DEMO - works in Fx - to work in Chrome, you need to add a click handler. Popups are blocked unless the user clicked to get it
success: function (data) {
var imageUrl = data ? siteImageUrl + data : 'image/NO_IMAGE.jpg';
$("#visitorcard").attr('src', imageUrl);
var printWindow = window.open("", "_blank", 'width=200,height=200');
printWindow.document.write('<body onload="window.focus();window.print()">'+
$("#visitorcard").parent().html()+'</body>');
printWindow.document.close();
},

Categories

Resources