I trying to build an app with phonegap, jquerymobile and JSON (from wordpress json api). I use the code down here and that works for me it displays te list of recent posts (index.html).
<script type="text/javascript">
var wpAPI = "http://myurl.nl/api/get_recent_posts/";
$(document).on('pagebeforeshow', '#index', function(){
$.getJSON(wpAPI, function(result) {
$.each( result.posts, function( i, item ) {
var html = '<li><img src="'+ item.thumbnail +'"><h2>' + item.title + '</h2><p>' + item.excerpt + '</p></li>';
$( ".container>ul" ).append(html);
});
$("#list").listview('refresh');
});
});
</script>
The problem is when I try to open one of the posts (post.html) the post.html doesn't show anything when I export the app for android.
So I think is something with refreshing, but maybe something else hope some can help me.
<script>
function readSinglePost (url,container){
var postId = window.location.search;
var URL = 'http://myurl.nl/api/get_post/'+ postId + '';
jQuery.ajax({
url: URL,
dataType: 'json',
success: function(data) {
console.log(data);
$('.container').html("<h3>" + data.post.title + "</h3>" + data.post.content + "");
}
});
}
$(document).ready(function(){
readSinglePost (URL,'.container');
});
</script>
Replace
<a href="post.html?post_id='+ item.id +'">
with
<a href="post.html?post_id='+ item.id +'" data-ajax="false" data-role="none">
function readSinglePost (url,container){
var postId = window.location.search;
var URL = 'http://myurl.nl/api/get_post/'+postId;
jQuery.ajax({
type: "GET",
url: URL,
dataType: "json",
success: function(data) {
console.log(data);
$('.container').html("<h3>" + data.post.title + "</h3>" + data.post.content);
}
});
return false;
}
Related
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>
I am developing an android app using apache cordova tools in visual studio 2015. I want to call a web service from my index page in cordova app, but I somehow can't achieve it.
Here is the HTML
<div ><input type="button" id="callwebmethod" name="submit" /> <br /> </div>
Here is the JS function
<script type="text/javascript">
$('#callwebmethod').click(function () {
var params = "{'msg':'From Client'}";
$.ajax({
type: "POST",
url: "http://mysite/index.aspx/GetEmployees",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert(result.d); }
});
})
</script>
Here is the web method
[WebMethod]
public static string GetEmployees()
{
return "Hello World";
}
Your var params have to be simular to the Parameters of the WebMethod. Just leave them empty and try it again. They have to be exactly the same.
If you whant to use web methods with parametes here is a working example:
$.ajax({
url: "http://systemservice/systemservice.asmx/App_Test",
data: "{ par1: '" + xxx + "', par2: '" + xxx + "'}",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d) {
//Do something
}
},
error: function (xhr) {
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
})
[WebMethod]
public string App_Test(string par1, string par2) {
return "Hello";
}
With the shown error function you can also find out what is going wrong.
To do it without the paremeters you just have to leave them empty.
data: "{}"
[WebMethod]
public string App_Test() {
return "Hello";
}
It woked for me this example:
var person = {};
person.ID = $('#txtID').val();
person.Name = "Amir";
var pdata = { "p": person };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/SampleService.asmx/GetPesonnelSalary",
data: JSON.stringify(pdata),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
if (data.hasOwnProperty('d')) {
msg = data.d;
} else {
msg = data;
}
alert(msg);
}
},
error: function (data, status, error) {
alert("error");
}
});
The complete code is here: http://www.scriptiny.com/2012/12/calling-asmx-web-service-via-jquery-ajax-2/
i have this simple app , that works fine in a browser , but when building it using phonegap it's just shows a simple html page, means that jquery not working ,
in my page i call the jquery mobile.min.css ,jquery.min.js than this script :
$(document).bind("pagebeforechange", function (event, data) {
$.mobile.pageData = (data && data.options && data.options.pageData)
? data.options.pageData
: null;
});
$(document).ready( function (event) {
compSearch('');
$("#searchbtn").click(function () {
var sText = $("#searchtxt").val();
$("#search").dialog("close");
compSearch(sText)
});
});
function compSearch(searchString) {
var theUrl = serverName + "MobileService.asmx/getOrgPage";
var orgId = qString("org");
$.ajax({
type: "POST",
url: theUrl,
data: '{"OrgId":' + orgId +
',"SearchString":"' + searchString +
'"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
var s = msg.d[0];
$("#header").html(s).trigger("create");
$("#footer").html(msg.d[3]).trigger("create");
$("#contentHeading").html(msg.d[1]);
$("#content").html(msg.d[2]).find("ul").listview();
$("#newscontent").html(msg.d[4]);
},
error: function (msg) {
alert('error ' + msg.d[0]);
}
});
}
$(document).on('pagebeforeshow', '#indivnews', function (event, data) {
if ($.mobile.pageData && $.mobile.pageData.np) {
var orgId = qString("org");
var itemId = $.mobile.pageData.np;
var theUrl = serverName + "MobileService.asmx/getNewsPage";
var clubName = "";
$.ajax({
type: "POST",
url: theUrl,
data: '{"orgId":' + orgId +
',"compId":' + 0 +
',"itemId":' + itemId +
',"clubName":"' + clubName +
'"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
var s = msg.d[0];
$("#indivcontent").html(msg.d[4]);
},
error: function (msg) {
alert('error ' + msg.d[0]);
}
});
}
});
than the jquery mobile.min.js
like i said it's works fine in a browser,please if you have and idea to solve it
thank you.
It may be that you are loading the html page before PQ and JQM are properly initialized. I use the following in my project to ensure the framework is loaded correctly:
var deviceReadyDeferred = $.Deferred();
var jqmReadyDeferred = $.Deferred();
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
deviceReadyDeferred.resolve();
}
$(document).one("pageinit", function () {
jqmReadyDeferred.resolve();
});
$.when(deviceReadyDeferred, jqmReadyDeferred).then(frameworksLoaded);
function frameworksLoaded() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
jQm.allowCrossDomainPages = true;
console.log('PG & JQM ready');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width =device-width, initial-scale=1.0, user-scalable=no" />
<title>Test</title>
<link href="Example.css" rel="stylesheet" />
<link href="../www/Content/jquery.mobile-1.4.0.css" rel="stylesheet" />
<link href="../www/Content/jquery.mobile-1.4.0.min.css" rel="stylesheet" />
<script src="../www/Scripts/jquery-2.1.0.min.js"></script>
</head>
<body>
</body>
</html>
Reference to Deferred and Jquery Promises:
http://api.jquery.com/deferred.promise/
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"
hope u guys will be able to help me. I'm relatively very new to phonegap. I've cracking my head on this for a week+ now on this subject. I have a dbase wcf rest service in C# and have built an android client to call this service. Everything seem to be working fine when I test this app in wp7 i.e call this service in json format. but when I migrated this app to eclipse android environment and configured relevant settings the app will not run successfully even after I changed the url: http//:localhost:1067/Service1 to http//:10.0.2.2:1067/Service1. I'm still using a demo app which I have modified to the following
index.html
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=320 user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>PhoneGap WP7</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="console.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8" src="init.js"></script>
</head>
<body>
<div>
<h1 id="welcomeMsg">Welcome</h1>
<p>log in</p>
<p>Get Ajax</p>
<p>Post Ajax</p>
<p>Get Single Item</p>
<p>Delete</p>
<p>Update</p>
<p>Identify</p>
<p>Log via Form</p>
<p>log out</p>
<p id="errorMessage" class="err"></p>
<p id="loginCall"></p>
<p id="ajaxCall"></p>
<p id="postAjaxCall"></p>
<p id="getSingleCall"></p>
<p id="deleteSingleCall"></p>
<p id="updateSingleCall"></p>
<p id="identifyCall"></p>
<p id="logViaFormCall"></p>
<p id="logoutCall"></p>
<input type="text" id="myTest" value="1" name="myTest" />
</div>
</body>
</html>
and the init.js
$(document).ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
jQuery.support.cors = true; //Cross-Origin Resource Sharing
});
// phonegap is initialised
function onDeviceReady() {
$("#welcomeMsg").append("...Ready");
}
function showAlert(msg) {
navigator.notification.alert(
msg, // message
alertDismissed, // callback
'Alert', // title
'Done' // buttonName
);
}
function showError(error, otherInfo) {
var element = document.getElementById('errorMessage');
element.innerHTML = "Errors: " + error.Message + "<br>" + (otherInfo ? otherInfo : "");
}
function getAjax() {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/Service1/',
type: 'GET',
//headers:
beforeSend: function (xhr) {
//xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{ "Idi":5, "Type": "mike" }'
})
.done(function (data) {
var element = document.getElementById('ajaxCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) {
showError(error);
})
.always(function () { showAlert("complete"); });
}
function postAjax(parameters) {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/Service1/',
type: 'POST',
//headers:
//beforeSend: function (xhr) {
//},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{ "Id":5, "StringValue": "jerry 22" }'
})
.done(function (data) {
var element = document.getElementById('postAjaxCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function login() {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/login/',
type: 'POST',
//headers:
//beforeSend: function (xhr) {
//},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{ "Username":"test", "Password": "test" }'
})
.done(function (data) {
var element = document.getElementById('loginCall');
element.innerHTML = "Login Succesfull ? " + data;
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function logout() {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/login/logout',
type: 'POST',
//headers:
//beforeSend: function (xhr) {
//},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
})
.done(function (data) {
var element = document.getElementById('logoutCall');
element.innerHTML = "Login Out Succesfull ? " + data;
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function getSingle() {
var longcentre = "3.355";
var latcentre = "6.602";
var locname = "hotel";
var searchrad = "10";
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/Service1/?lat1='+latcentre+'&long1='+longcentre+'&srad='+searchrad+'&lname='+locname+'',
// url: 'http://10.0.2.2/estatewcf/Service1/?lat1=6.602&long1=3.355&srad=2.5&lname=bank',
type: 'GET',
//headers:
beforeSend: function (xhr) {
//xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
})
.done(function (data) {
var element = document.getElementById('getSingleCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function deleteSingle(parameters) {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/Service1/88',
type: 'DELETE',
//headers:
beforeSend: function (xhr) {
//xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
})
.done(function (data) {
var element = document.getElementById('deleteSingleCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function updateSingle(parameters) {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/Service1/99',
type: 'PUT',
//headers:
beforeSend: function (xhr) {
//xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{ "Id":99, "StringValue": "JERRY 22 " }'
})
.done(function (data) {
var element = document.getElementById('updateSingleCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function identify(parameters) {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/login/identify',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8'
})
.done(function (data) {
var element = document.getElementById('identifyCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function postAjax1(parameters) {
var id = "2";
var mysearchradius = "ope";
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/Service1/',
type: 'POST',
//headers:
//beforeSend: function (xhr) {
//},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{ "IDn":"' + id + '","type1":"' + mysearchradius + '" }'
})
.done(function (data) {
var element = document.getElementById('postAjaxCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
function logViaForm() {
var jqxhr = $.ajax({
url: 'http://10.0.2.2/estatewcf/login.aspx',
type: 'GET',
dataType: 'html'
})
.done(function (data) {
var eventVal = $(data).find('#__EVENTVALIDATION').attr('value');
var viewState = $(data).find('#__VIEWSTATE').attr('value');
//build post data
var postData = { __VIEWSTATE: viewState, __EVENTVALIDATION: eventVal, UserName: "test1", Password: "test2", LoginButton: "Log In" };
var jqxhr1 = $.ajax({
url: 'http://10.0.2.2/estatewcf/login.aspx',
type: 'POST',
dataType: 'html',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: postData
})
.done(function (data, status, jqxhr1) {
//this works but we will get an error dues to the redirect to the home.aspx
//TODO: need to handle that
var element = document.getElementById('logViaFormCall');
element.innerHTML = "Login Succesfull ! " + jqxhr1.status;
})
.fail(function (xhr, status, error) {
showError(error, "TODO: Works but need to handle redirect!!");
//but it really works!
var element = document.getElementById('logViaFormCall');
element.innerHTML = "Login Succesfull ! Verify that Authenticated AJAX calls work!";
})
.always(function () { showAlert("complete login"); });
})
.fail(function (xhr, status, error) { showError(error); })
.always(function () { showAlert("complete"); });
}
cordova.xml
<cordova>
<!--
access elements control the Android whitelist.
Domains are assumed blocked unless set otherwise
-->
<access origin="http://127.0.0.1*"/> <!-- allow local pages -->
<!-- <access origin="https://maps.googleapis.com/maps/api/js?key=AIzaSyDD353fOPh-KBUQ-2ekPCg75uxXRn0D9Tk&sensor=false" /> allow any secure requests to example.com -->
<!-- <access origin="https://10.0.2.2*" subdomains="true" /> such as above, but including subdomains, such as www -->
<!-- <access origin="*."/> Allow all domains, suggested development use only -->
<log level="DEBUG"/>
<preference name="classicRender" value="true" />
</cordova
as I have said earlier I have tested the wcf service locally withing vs2010 server and iis7
It seems to be working well, but Im not able to get it to work in android. Any help will be appreciated. Thanks in advance.
I found out that there is notting wrong with this code other than to un-comment the commented whitelist part i.e converting :
<!-- <access origin="https://10.0.2.2*" subdomains="true" /> such as above, but including subdomains, such as www --> to
<access origin="https://10.0.2.2*" subdomains="true" />
and that solved it.