Phonegap: Received JSON data fails to display - android

I'm trying to code a dynamic phonegap app that retrieves and format information from a live database.
I use jsonp to get data from a php service I coded.
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://example.com/service.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
//data loaded
$.each(data, function(c,comp){
window.alert(comp.filter); // I added this just to check I was getting data correctly.
var company = '<div class="project-post ' +comp.filter+ ' ">'
+'<img src=" ' +comp.img+ ' ">'
+'<div class="hover-box">'
+'<div class="project-title">'
+'<div><i class="fa fa-arrow-right"></i></div>'
+'</div></div></div>';
output.append(company);
});
},
error: function(){
//error loading data
output.text('Error loading data.');
}
});
});
My console doesn't display any errors, I've been trying to solve this for a long time. I have this in my config:
<access origin="*" />
Also I confirmed I was receiving data with window.alert(comp.filter); It's just not displaying at all, maybe something's wrong with my formatting but can't figure out what it is.

I think the issue because of dom formating, the img tag is not closed correctly it should be like:
var company = '<div class="project-post ' +comp.filter+ ' ">' +'<img src=" ' +comp.img+ ' "/>' +'<div class="hover-box">' +'<div class="project-title">' +'<div><i class="fa fa-arrow-right"></i></div>' +'</div></div></div>';
Also take care of your access policy to allow all urls, update your config.xml file with the following code:
<access origin="*" />

Related

window.localStorage.setItem not working on mobile phone

I am working on HTML5 mobile app using jQuery mobile.
This is my code:
$(document).on("click","#send_mobile_number",function(){
var mobile = $('#mobile_number').val();
var user_id = sessionStorage.getItem("user_id");
$('.ui-loader').show();
$.ajax({
url: BASE_URL+'users/send_sms_code.php',
type: 'POST',
datatype: 'json',
data: "user_id="+user_id+"&mobile="+mobile+"&type=1",
async:false,
success: function (response) {
var data = jQuery.parseJSON(response);
$('.ui-loader').hide();
if(data.status == 'Fail') {
$('.very_mob_no_message').html('Sorry some error occurred,try again.');
}else{
$('#close_mob_popup').trigger('click');
setTimeout(function()
{
$('.click_mobile_verify').trigger('click');
}, 500);
$('#send_mobile_verify_span').hide();
$('#after_mobile_send_span').show();
$('#moble_number_div').hide();
$('#user_code_div').show();
$('#user_code').val(data.sms_code);
//alert(window.localStorage.getItem('mobile'));
//sessionStorage.setItem("mobile",mobile);
window.localStorage.setItem("mobile",mobile); // IT IS NOT WORKING
$('.very_mobile_message').html('Enter code which is <br/> sent to your mobile number.');
}
},
error: function (jqXHR, textStatus, errorThrown) {
//alert(jqXHR.status);
}
});
});
I want to store mobile number in session using window.localStorage.setItem("mobile",mobile);. It is working when I run on my browser but when I runt on mobile phone as APP it stop working. Why this happening. I am checking android phone.
Just use localStorage.mobile = "mobile". It's as simple as that. localStorage is a global object and can be accessed and manipulated as any other object. The only difference with regular objects is that it can store only strings.
You can then retrieve your value using alert( localStorage.mobile ); // will alert "mobile"
So finally found the solution, I need to set webSettings.setDomStorageEnabled(true); on android code and after this localstorage is working perfectlly.

Android browser times out Ajax request

I am submitting a form via ajax (using JQuery) and the time taken for the response to be received can be anything from a few seconds to a few minutes. This is expected and cannot be changed. This is working fine in all browsers except the stock Android browser which is timing out my request after 120 seconds, no matter what I set the timeout to in the ajax constructor. Is there a way around this?
The code for the Ajax request is quite simple:
var jqxhr = $.ajax({
type: 'post',
timeout: 500000,
url: 'process.php',
data: $('form').serialize(),
success: function (data) {
alert("success" + data);
},
error: function(xhr, error){
alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
When submitted on Android with a script that takes over 120 seconds, the error handler is hit with the following message:
Error: error, XHR status: 0
Please have a look at this article indicating that the error may arise from the presence of a HTTP Expires header.
Use a tool like Fiddler to monitor the HTTP network traffic and present the results for further analysis.
You have a syntax error.
var jqxhr = $.ajax({
type: 'post',
timeout: 500000,
url: 'process.php',
data: $('form').serialize(),
success: function (data) {
alert("success" + data"); <------- HERE
},
error: function(xhr, error){
alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
Try your code with this on-line JavaScript runner but remove the extra double qoute.
var jqxhr = $.ajax({
type: 'post',
timeout: 500000,
url: 'process.php',
data: $('form').serialize(),
success: function (data) {
alert("success" + data);
},
error: function(xhr, error){
alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
After some research it appears that others have had similar issues with AJAX timeouts at ~60ms and ~120ms. Those seem like very deliberate values (like internal browser settings), and I am going to go ahead and assume from the lack of responses/solutions that we can't get around those timeouts.
Have you considered posting your AJAX request to a separate server/service which does not do any processing and can return a quick 200 OK response. Then let this second server handle the communication with the slow server. I know this sucks, but it might be your only solution (and might result in a snappier app and happier users).
Can you give any more insight into your app? Is this a PhoneGap app or is the app hosted at some domain that you can access from the browser? Are you able to provide a URL?
Have you seen the below thread.
AJAX (XmlHttpRequest) timeout length by browser
Regards,
SP
Try inserting your code on a separate blank html page with nothing but your ajax request, jquery attached and some basic alerts like success, status code or errors etc. Put the correct file path in url handler, in data handler, put some static values like name:"Macros",site:"stackoverflow". When all gets ready, you should get alert message on desktop browser, if its success, try running that html page on stock android browser. If that works as well.. The problem might be jquery conflict with some other script or your $("form#testform").serialize() function.
How about if you retry after the timeout?
$("form#testform").submit(function(){
var allFormValues = $("form#testform").serialize();
$.ajax({
cache:false,
timeout:8000, // I chose 8 secs for kicks
tryCount : 0,
retryLimit : 5,
type:"POST",
url:"someurl.php",
data:allFormValues,
error:function(xhr, status, error) {
if (status == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
alert("Timeout! Retrying now!");
//try again
$.ajax(this);
return;
}
return;
} else {
// not a timeout? not a problem
alert("Error: " + status + ", XHR status: " + xhr.status);
}
},
success:function(response){
alert(response);
}
});
});

Android Browser Issue with jQuery Ajax and when appcache is used

we are having a problem with the built in browser on Android 4.0, 4.1 and 4.2 (we haven't got anything lower to test on).
The problem is that the ajax call will work perfectly on first load, you can press the run Ajax button as many times as you like and it will be fine. You can disconnect from the internet and it will work properly.
But if you exit (FULLY, make sure its not just running in the background) the browser then relaunch it, it will fail on load and on button press. It doesn't matter if you are on-line or off-line.
The error that is been returned from the ajax call is "Error" with status = 0 and readyState = 0.
When its successful you get a message back says "respose from Ajax Call" with a status = 200 and a readyState = 4.
The code works find on every other browser we have tested on Android Chrome, Firefox and Opera. on IOS 5 and 6 it works and every desktop browser we can find.
Is there something that I missing or have we found a bug in the built in browser. Any help on this would be appreciate especially if it just something stupid I have done.
We have created a test script that demonstrates this problem well I have attached it to the bottom of this message.
Thanks
Tim
test.php
<?php
function displayPage() {
?>
<!DOCTYPE html>
<html manifest="test.manifest" debug="true">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" >
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function runAjaxGet() {
var XMLHttpRequest = $.ajax({
url: "test.php",
dataType: "json",
data: "test=test",
traditional: "true",
success: function( responseData ) {
alert('good\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status );
console.log(XMLHttpRequest);
},
error: function (xhr, ajaxOptions, thrownError, responseData) {
alert('bad\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status);
console.log(XMLHttpRequest);
}
});
}
$(document).ready(function() {
runAjaxGet();
});
</script>
</head>
<body>
<button Name="Run Ajax" onclick="runAjaxGet();">Run Ajax</button>
</body>
</html>
<?php
}
function processRequests() {
header("Content-Type: application/json; charset=UTF-8" );
echo (json_encode("respose from Ajax Call"));
}
date_default_timezone_set ( "UTC" );
if (isset($_REQUEST['test'])) {
$which = $_REQUEST['test'];
} else {
$which = '';
}
switch ($which) {
case "test":
processRequests();
break;
default :
displayPage();
break;
}
?>
test.manifest
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
Just add NETWORK section with asterisk and it will work
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
NETWORK:
*
I hit this same problem and determined that when retrieved from the cache, 0 indicates success. This is likely because there is no actual http request involved since the request is resolved entirely locally.
Appcache manifest file:
CACHE MANIFEST
CACHE:
/config
Javascript:
var request = new XMLHttpRequest();
request.open('GET', '/config', false); // async=false is ok because this file will always come from AppCache
request.send(null);
// Older versions of android return 0 when ajax request retrieved from appcache
if (request.status == 200 || request.status == 0) {
return JSON.parse(request.responseText);
} else {
console.log("ERROR: config not retrievable");
throw "Attempt to retrieve config return http status " + request.status;
}

LocalFileSystem is not defined PhoneGap (Build) in Android

I have the following code:
function wait(){
$(document).ready(function() {
//alert("Dentro de ready");
document.addEventListener("deviceready", init(), true);
});
}
Where "wait" is a Javascript function called from the onload event. I use the onload event, as well as $(document).ready and "deviceready" event to make sure every single thing is loaded when i start coding.
The "init()" method does a few things and then calls the following method:
function download_img(imgToDownload){
var url = remote_url+imgToDownload; // image url
alert("img url: "+url);
try{
window.requestFileSystem(**LocalFileSystem**.PERSISTENT, 0,
function (fs) {
var imagePath = fs.root.fullPath +"/"+ imgToDownload; // full file path
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imagePath,
function (entry) {
alert("OK: " + entry.fullPath); // entry is fileEntry object
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
alert("http_status"+error.http_status);
}
);
}
);
}catch(err){
alert(err.message);
}
}
Where I get the error message: "LocalFileSystem is not defined".
My config.xml is:
<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
id = "com.lamakun.mancomunidad"
version = "3.0.0">
<name>PhoneGap Build Application</name>
<description>
A simple PhoneGap Build application.
</description>
<author href="https://example.com" email="you#example.com">
Your Name
</author>
<preference name="phonegap-version" value="2.2.0" />
<access origin="http://www.mytests.es" subdomains="true"/>
</widget>
In case I might add any permission, even though I think right now I have them all.
Can anyone give me a clue on that?
It isn't:
document.addEventListener("deviceready", init(), true);
it should be:
document.addEventListener("deviceready", init, true);
having the () after init calls that function immediately before the deviceready event is fired.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
write these lines in android manifiest file

Webservice client to connect SugarCRM web service from PhoneGap

I have SugarCRM Web services in the below link.
http://www.sugarcrm.besplatform.com/soap.php?wsdl
Using web services, I wanted to login and list Leads Management Details through SugarCRM Web Services. I am not able to access SugarCRM web services because of "cross - domain security" issue and "same origin" issue.
I have tried using JSONP , but could not succeed.
I am new to jquery and jsonp. Some one could help me to solve this problem.
Thanks in advance.
using ajax code:
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
alert("inside ajax");
var username = "admin";
var password = "admin";
$.ajax({
url: "www.sugarcrm.besplatform.com/soap.php/login",
data: "{'user_name':'" + username + "','password':'" + password + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data == null) {
alert( "nothing.");
}
else {
alert(data);
}
},
error: function(e){
alert("failure : "+e);
}
});
using jsonp:
<script type="application/javascript" src="jquery-1.7.2.min.js"></script>
<script type="application/javascript">
var url = "http://www.sugarcrm.besplatform.com/soap.php/login?user_name=admin&password=admin";
jQuery.getJSON(url+"&callback=?", function(data) {
alert("Success" + data.id);
});
</script>
I think you need to send the password MD5 encrypted to Sugar. Also there's a REST WS available at "../service/v2/rest.php" that you could use instead of the SOAP interface.
Since version 6.5.11 this is fixed. If you use "jsoncallback" and then the name it works. Take a look at the file service/core/REST/SugarRestJSON.php to see what changed and patch older versions of sugar

Categories

Resources