Phonegap navigation ajax in loading pages - android

I am trying to create a index with navigation that when clicked will load the pages through ajax instead of going to another html
this is my javascipt:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function getPage(){
$.ajax({
type: 'post',
url: 'places.html',
success: function(html)
{
$("#response").fadeIn("slow");
$("#response").html(html);
}
});
return false;
}
</script>
i have a href that calls this
get page
this worked for xampp local host but seems to generate error in phonegap
Uncaught ReferenceError: $ is not defined at file:///android_asset/www/index.html:129
which is the line where the $.ajax is located

You have to wait till the device is ready to make an ajax call.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
function getPage(){
$.ajax({
type: 'post',
url: 'places.html',
success: function(html)
{
$("#response").fadeIn("slow");
$("#response").html(html);
}
});
return false;
}
}

well ajax worked at last needed the complete file address and put it inside documentready
$.ajax({
type: 'post',
url: 'file:///android_asset/www/.html/places.html',
success: function(html)
{
$("#response").fadeIn("slow");
$("#response").html(html);
}
});
another method i found was
$("#getProfile").click(function() {
var ajax = new XMLHttpRequest();
ajax.open("GET","file:///android_asset/www/places.html",true);
ajax.send();
ajax.onreadystatechange=function(){
if(ajax.readyState==4 && (ajax.status==200||ajax.status==0)){
var theHTML = ajax.responseText;
document.getElementById('response').innerHTML = theHTML;
}
}
});
thanks for the help Malek

Related

phonegap android ajax over ssl failes

I develope an App with Phonegap and Jquery Mobile. For some reasons I also need to get data from https domains. On IOS everything works perfect, but on Android I always get the following errors and the requests fails
06-17 17:16:33.890 6079-6154/de.sistecs.einlass E/chromium_net: external/chromium/net/socket/ssl_client_socket_openssl.cc:905:
[0617/171633:ERROR:ssl_client_socket_openssl.cc(905)] handshake failed; returned -1, SSL error code 1, net_error -107
Here is a simple sample code
$(document).on("pageinit", function (event, ui) {
$("#test").click(function () {
$.ajax({
type: "POST",
url: "https://test.sistecs.de/sismedia/test.php",
success: function (response) {
$("#testmsg").text(response);
}
});
});
});
I´ve read hundreds of posts, but didn´t find a solution to my problem.
The certificate of the server https://test.sistecs.de/sismedia/test.php is valide.
Can someone help me?
It seems like a Cross Origin problem.
With jQuery Mobile you should set $.mobile.allowCrossDomainPages and $.support.cors to true
<script>
$( document ).on( "mobileinit", function() {
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
Also be sure that your PHP page sets the headers accordingly. For example:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
header('Access-Control-Allow-Headers: Content-Type');
echo "test";
?>
Edit: I didn't test the code, it is an example. Adapt as you need to.
var myJson = {
'Par1': 'par'
};
$.ajax({
url: baseUrlAjaxServices + "/....",
data: JSON.stringify(myJson),
method: "POST",
crossDomain: true,
dataType: 'json',
contentType: 'application/json',
})
.done(function (data) {
//...
}).fail(function (error) {
console.log(error);
});

AJAX call not getting information on Intel XDK

I'm building an APK for the blood bank of my local city and i need to get the stock of blood by groups, i have some JSON that i test with Postman that woks but i need to add them to my Intel XDK project. I have follow some examples with AJAX and HTTP but with no result.
ionic.Platform.ready(function(){
$("#ajax").click(function(){
$.ajax({
method: 'GET',
url: 'http://192.168.1.100/api/hospital/17659861-1',
dataType: 'json',
success: function (data) {
alert('Data RecibidaAPI: ' + data);
console.log(data.data[0].us_rut);
console.log(data.data[0].us_nombre);
console.log(data.data[0].us_telefono);
console.log(data.data[0].us_id_dispositivo);
console.log(data.data[0].us_grupo_sangre);
}
}).then(function (data) {
console.log('Data RecibidaAPI: ' + data);
});
});
}
and also try
<div id="campa_de_sangre" class="upage-content vertical-col left hidden" ng-app="myApp2" ng-controller="myCtrl2">
<p>hola</p>
<h1>{{myWelcome}}</h1>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p
<p>{{content}}</p>
<script>
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, function myError(response) {
$scope.content = "Something went wrong";
});
});
</script>
</div>
where i could't even get the scope.satuscode to work.
I'm using Ionic as framework with AngularJS, if someone need extra info to helpmeet just ask and thanks for any idea.
See this FAQ on the Intel XDK web site > https://software.intel.com/en-us/xdk/faqs/app-designer#ajax-jquery-one-fail
If the call is being made successful but you're not getting your $scope to update try wrapping the values you need to update in $timeout .. you can use $scope.apply() but i believe $timeout to be the safer method
<div id="campa_de_sangre" class="upage-content vertical-col left hidden" ng-app="myApp2" ng-controller="myCtrl2">
<p>hola</p>
<h1>{{myWelcome}}</h1>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p
<p>{{content}}</p>
<script>
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function ($scope, $http, $timeout) {
$http({
method: "GET",
url: "welcome.htm"
}).then(function mySucces(response) {
$timeout(function () {
$scope.myWelcome = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, 0)
}, function myError(response) {
$timeout(function () {
$scope.content = "Something went wrong";
}, 0)
});
});
</script>
</div>

How to get correctly a JSON value for a phonegap android app from wordpress with API-JSON plugin

Hello I am stuck with an android application I am trying to build using phonegap. The application I try to build retrieves a feed from a wordpress site which i have installed locally. I have already installed and tested JSON-API plugin and it worked correctly.
But when i created an android application using phonegap with eclipse I do not get the feed loaded via javascript.
I have created an html file under projectfolder/assets/www folder where the code is
<!DOCTYPE HTML>
<html>
<head>
<script src="jquery.js"></script>
<script src="cordova.js"></script>
<script>
jQuery.support.cors = true;
var target_div = "#contents";
var nextID = null;
var prevID = null;
var api_read_url = "http://127.0.0.1/wordpress_phonegap/?json=get_post&dev=1&id=";
var init_url = "http://127.0.0.1/wordpress_phonegap/?json=get_post&dev=1&p=1";
function getID(url) {
var str = new String(url);
var x = str.split("=");
var id = x[1];
return id;
}
function readSinglePost (url,target_div) {
var URL = url+"&callback=?";
console.log(URL);
jQuery.ajax({
url: URL,
dataType: "json",
jsonp: null,
jsonpCallback: null,
success: function(data) {
alert(data);
jQuery(target_div).html("");
try{
jQuery(target_div).append("<h1>"+data.post.title+"</h1>");
jQuery(target_div).append(data.post.content);
jQuery(target_div).append("<small>"+data.post.date+"</small>");
} catch (e){
console.log("error console");
}
try {
nextID = getID(data.next_url);
}
catch (e) {
;
}
try {
prevID = getID(data.previous_url);
}
catch (e) {
; // you should include some of your own error-handling code or
}
} ,
error: function(error){
console.log("error console");
}
});
}
//Renew next and previous buttons
function getNext(){
jQuery("#next").click(function(){
var id = nextID;
var nextURL = api_read_url + id;
readSinglePost(nextURL, target_div);
});
}
function getPrevious(){
jQuery("#previous").click(function(){
var id= prevID;
var prevURL = api_read_url + id;
readSinglePost(prevURL, target_div);
})
}
jQuery(document).ready(function() {
readSinglePost(init_url, target_div);
getNext();
getPrevious();
});
</script>
</head>
<body>
<div id="main">
<button type="button" id="previous">Previous</button>
<button type="button" id="next">Next</button>
<div id="title"></div>
<div id="contents"></div>
</div>
</body>
</html>
When I open this file using firefox and firebug I obtain the following error in the console.
SyntaxError: invalid label
"status": "ok",
I understand what has happened. As it is a crossbrowser interaction json gets sent in jsonp format and thus the json value gets sent wrapped in a function. How can i get the value correctly?
I have read several threads and articles but unfortunately I have found no solution. The example comes from the tutorial included in the book "WordPress Mobile Applications with PhoneGap"

load an xml from external url to phonegap application

I'm trying to get a value from external url using jquery at phonegap application.
but it's not work, this is my code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js">
</script>
<script>
$(document).ready(function(){
jQuery.support.cors = true;
$("button").click(function(){
$.ajax({
type: "GET",
url: "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Cube').each(function(){
var usd = $(this).find('Cube type=["currency"]').text();
$("#d").html(usd);
});
}
});
});
});
</script>
</head>
<body>
<div id="d"></div>
<button>Get External Content</button>
</body>
</html>
is there any way to load / post / get data from/to external url by using:
phonegap, jquery, jquerymobile, ....... ?
Instead of the xml file you can use your url. Since I tried it from browser I created the xml file.
$.ajax({
type: "GET",
url: "../res/exData.xml",
dataType: "xml",
success: function (xml){
$(xml).find('Cube').each(function(){
$.each(this.attributes, function(i, attrib){
var name = attrib.name;
var value = attrib.value;
if (name === "currency")
$("#d").html(value);
});
});
},
error: function(model, xhr, options) {
alert("error");
}
});

How do I use PhoneGap to call a webservice

I'm trying to develop an application on phonegap on Android.
What I'm trying to do is call a webservice from my application, this will be used for data access.
I found many sheets online on how to do this, and the simplest one I could find that seems straight forward goes like this
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://www.webservicex.net/stockquote.asmx/GetQuote",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
});
However, All I can see is the text I had already put into the div, the div contents do not change. I'm testing on a Galaxy SIII device directly, not on a simulator.
My guess is that nothing seems to happen because you are getting a fail, not a success. try adding an error handler and see what happens.
.fail(function() { alert("error"); })
You are likely having 'cross domain' issues (because you are trying to get ajax from a different domain) and may need to use JSONP instead of JSON for your dataType. For more info about JSONP, see this post or the docs
EDIT:
Here is a fiddle of this code in action.
$(document).ready(function() {
//here is one way using the 'error' handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error:function(jqXHR, textStatus) {
alert("error:" + textStatus);
},
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
//here is another way using the 'fail' request handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
}).fail(function(jqXHR, textStatus) {
alert( "fail: " + textStatus );
});
});​

Categories

Resources