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>
Related
I want to add notifications to an online android chatting app I have made. I am new to cloud functions, so I tried using the code given here https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html
My index.js file
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "xyz"; // Your Firebase
Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("firebase.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
requests.on('child_added', function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
console.log('notificationrecived, sent and removed- ' +
request.username + ' '+ request.message,);
requestSnapshot.ref.remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '
+response.statusMessage);
}
else {n
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
I have successfully deployed this code to the server using node.js command line.
But this does not show up on the console and nor the logs that I added to debug
and the code doesn't seem to work. I have done everything given in the link i mentioned. I could use some help on how to fix my code
I don't know how big of a difference this makes, but in the Firebase admin set up page https://firebase.google.com/docs/admin/setup, it is mentioned that for Cloud Functions, the following line is sufficient for initialisation:-
var firebase = require('firebase-admin');
firebase.initializeApp(functions.config().firebase);
So, if you're going by the book, you may replace the initialisation line in your code with the one above and try running it again.
I didn't export my function listenForNotificationRequests() but called it only once at the end of the script.
Which is why it didn't show up on the Firebase Console.
I fixed this by simply exporting the function like this
exports.sendFollowerNotification = listenForNotificationRequests;
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);
});
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;
}
I am a newbie to phonegap. I m stuck. I m unable to get result while calling webservice in phone gap. I used both Ajax and getJSON Method. Getting result as undefined, RealData variable as undefined. I am feeling that I am missing something. Please help guys.
Here is my code....
function onDeviceReady() {
console.log("Device is Ready111111");
alert("alert Device ready");
/*var jqxhr = $
.getJSON(
'http://www.infoline.in/mobdata.aspx?
reqfor=area_list&city=ahmedabad',
function() {
console.log("Device is Ready111111....."+jqxhr);
alert('success');
}).error(function() {
alert('error');
});*/
$(document).ready(function () {
$.ajax({
url: "http://www.infoline.in/mobdata.aspx",
data: {
"reqfor": "area_list",
"city": "ahmedabad"
},
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg, textStatus, jqXHR) {
alert(textStatus);
var theRealData = msg.d;
alert(theRealData.length)
}
});
});
In order to view the Object you have to convert the msg into a string.
try this:
console.log(JSON.stringify(msg));
How to retrieve device id/ token at device registration? I am using Phonegap Pushwoosh example and it works fine. But I could not figure out how to retrieve the token at device registration initPushwoosh.
I am not a professional programmer. Any help will be appreciated.
I have an index.html that initialize
<body onload="init();">
In main.js
function init() {
document.addEventListener("deviceready", deviceInfo, true);
document.addEventListener("deviceready", initPushwoosh, true);
}
In PushNotification.js
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
// CHANGE projectid & appid
pushNotification.registerDevice({ projectid: "xxxxxxx", appid : "xxxxxxxx" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
});
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
The first section is the .registerDevice and the token is probably pushToken, but I just cannot figure out how to retrieve it from this function!
The best is to send it to a MySQL database lets call it smartphonedb.tokentable
I modified the initPushwoosh() to send me the token to MySQL using Ajax (see below) I am receiving nothing on MySQL. Am I sending the right Token param (pushToken)?
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
// CHANGE projectid & appid
pushNotification.registerDevice({ projectid: "xxxxxx", appid : "xxxxxxx" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
// start my ajax to insert token to mysql
var param ={Token: pushToken};
$.ajax({
url: 'http://luxurylebanon.com/offeratlive/apitoken.php', data: param, dataType: 'json', success: function(result)
{
if(result.success == false)
{
alert(failed)
}
else {
alert(success)
}
}
});
// end ajax
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
});
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
The PHP apitoken.php
<?php
$username="xxxxxxx";
$password="xxxxxxxxxxxx";
$database="offeratdb";
$server="offeratdb.db.xxxxxxxxx.com";
$connect = mysql_connect($server,$username,$password)or die('Could not connect: ' . mysql_error());
#mysql_select_db($database) or die('Could not select database ('.$database.') because of : '.mysql_error());
$vtoken= $_POST['Token'];
// Performing SQL query
$query = "INSERT INTO `tokentable` (`thetoken`) VALUES ('$vtoken')";
$result = mysql_query($query)or die('Query failed: ' . mysql_error());
echo $vtoken;
// We will free the resultset...
mysql_free_result($result);
// Now we close the connection...
mysql_close($connect);
?>
any help will be appreciated
After looking through your code I think it contains some mistakes.
So, lets try to fix them:
First of all. Do you have jquery js script included before PushNotification.js? If not, "$.ajax" will not be executed.
The other thing. The ajax default type is GET, and you use POST in your php code.
And you don't use json at all. So your code should be transformed into something like this
$.ajax({
type: "POST",
async: true,
url: url,
data: params,
success: function (result) {
// todo
},
error: function (result) {
// todo
}
});
And the last thing. The param var should be initialized like this:
var param = "Token="+pushToken;
Hope this would be helpful.
I was having the same problem, I updated the Pushwoosh.jar and it worked for me. :)