Ajax request to server, error function is not calling - android

i am sending ajax request to server to get the database. But if i enter incorrect data (which is to be sent over server) nothing is happening, error function is not working, all i am doing is to verify credentials from the server
here is my code
$.ajax
({
url: "URL",
type: "GET",
datatype: "jsonp",
data: {type: 'login', id: C_id},
ContentType: "application/json",
success: function(res)
{
var simpleJson = JSON.parse(res);
myDB.transaction(function (txe1)
{
for (var i = 0; i < simpleJson.User.length; i++)
{
var Cli_id= simpleJson.User[i].id;
myDB.transaction(function (txe)
{
txe.executeSql('CREATE TABLE Client_data(Mobile integer , C_id integer, U_id integer , name text , ip integer )');
});
myDB.transaction(function (txe1)
{
var data_ins = 'INSERT INTO Client_data (Mobile,C_id,U_id) VALUES (?,?,?)';
txe1.executeSql(data_ins, [p,C_id,U_id]
,function(tx, result)
{
navigator.notification.alert('Inserted' , onSignup, 'Info', 'ok');
},
function(error)
{
navigator.notification.alert('Already Registered');
});
});
}
});
},
});
});
my PHP code
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysql_connect("***", "***", "****");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekspeser_pro"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$id=$_GET['id'];
$sql = "SELECT * from client_master WHERE id='$id'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if($num_rows!=0)
{
while($myrow = mysql_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('User' => $recipes));
echo $output;
}
else
{
print "invalid key";
}
}
else
{
print "invalid login";
}
}
else
{
echo "invalid";
}
mysql_close();
?>

You should implement the error callback to perform some operation when the request fails. This is how you can implement request failure callback.
$.ajax({
url: "/save/author",
type: "POST",
dataType: "json",
data: { name: "John", age: "35" },
success: function (data, status, jqXHR) {
alert("request succeed");
},
error: function (jqXHR, status, err) {
alert("request failed");
}
})
as per this example, we are just showing an alert with text request failed. You can implement it accordingly as per your requirement.

If i get you correct,you want to validate the data passed to your url, if i am getting you correct you want to handle,please refer below:
Ajax error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/
So if you return any response from your PHP server/API, the error function won't be triggered as The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...
However, you can return a key from your PHP code as below to handle success and error in your ajax code:
$data['error'] = $success ? 0:1;// If success than set error to 0 else 1;
and in AJAX success you can handle it as :
success: function (data, status, jqXHR) {
if(data.error)
//do something
else
//do something else
}
Let me know if any queries
------EDIT------------------
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysql_connect("***", "***", "****");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekspeser_pro"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$id=$_GET['id'];
$sql = "SELECT * from client_master WHERE id='$id'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$is_error=0;
if($num_rows!=0)
{
while($myrow = mysql_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('User' => $recipes,'is_error'=>$is_error));
echo $output;
}
else
{
$is_error=1;
$error_message = "Invalid Key";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
}
else
{
$is_error=1;
$error_message = "Invalid Login";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
}
else
{
$is_error=1;
$error_message = "Invalid";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
mysql_close();
?>
In AJAX Code access it like this :
Check for following in success
if(simpleJson.is_error!=1)
//do your processing
else
alert(simpleJson.error_message);
Let me know if anything unclear

Related

I can't see my ParsePush Notification on my android emulator

I'm currently working on a chat application and I want to implement Parse Server Push notifications. I follow the documentation and put all the code that is required. My problem is that I can't see the notification, even though the console tells me that it was sent.
This is my MainActivity.java where is the Parse Installation.
#Override
protected void onCreate(Bundle savedInstanceState) {
notificationsPush();
createGraphicElements();
super.onCreate(savedInstanceState);
}
private void notificationsPush(){
ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null){
System.out.println("---------------------");
System.out.println("SUCCESS ON INSTALLATION");
System.out.println("----------------------");
ParsePush.subscribeInBackground("Chat", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
System.out.println("----------------------");
System.out.println("SUCCESS ON CHANNEL");
System.out.println("----------------------");
} else {
System.out.println("----------------------");
System.out.println("ERROR ON CHANNEL: " + e.getMessage());
System.out.println("CODE: " + e.getCode());
System.out.println("----------------------");
}
}
});
}else{
System.out.println("---------------------");
System.out.println("ERROR ON INSTALLATION");
System.out.println("ERROR: " + e.getMessage());
System.out.println("CODE: " + e.getCode());
System.out.println("----------------------");
}
}
});
}
These are my implementations on graddle module. (There is also the one that is required to connect to Firebase).
implementation platform('com.google.firebase:firebase-bom:28.4.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-messaging'
//Parse Server
implementation "com.github.parse-community.Parse-SDK-Android:parse:1.26.0"
//PUSH Parse Server
implementation "com.github.parse-community.Parse-SDK-Android:fcm:1.26.0"
These are the functions that I use on my ParseCloud (they are on main.js).
Parse.Cloud.define("SendPush", function(request) {
var query = new Parse.Query(Parse.Installation);
query.exists("deviceToken");
// here you can add other conditions e.g. to send a push to sepcific users or channel etc.
var payload = {
alert: request.params.Message
// you can add other stuff here...
};
Parse.Push.send({
data: payload,
where: query
}, {
useMasterKey: true
})
.then(function() {
response.success("Push Sent!");
}, function(error) {
response.error("Error while trying to send push " + error.message);
});
});
Parse.Cloud.define("SendPush2", function(request) {
var msg = request.params.Message;
var query = new Parse.Query(Parse.User);
var user = request.params.user;
query.equalTo("objectId", user);
Parse.Push.send({
where: query,
data:{
alert: {
"title" : msg,
"body" : msg
},
sound: 'default'
}
}, {
useMasterKey: true,
success: function(){
response.success("Push Sent!");
},
error: function(error){
response.error("Error while trying to send push " + error.message);
}
});
});
Parse.Cloud.define("SendPush3", function(request, response) {
var userId = request.params.user;
var message = "sening a test message"; //request.params.message;
var queryUser = new Parse.Query(Parse.User);
queryUser.equalTo('objectId', userId);
var query = new Parse.Query(Parse.Installation);
query.matchesQuery('user', queryUser);
Parse.Push.send({
where: query,
data: {
alert: message,
badge: 0,
sound: 'default'
}
}, {
success: function() {
console.log('##### PUSH OK');
response.success();
},
error: function(error) {
console.log('##### PUSH ERROR');
response.error('ERROR');
},
useMasterKey: true
});
});
Finally, the piece of code of my app where I test those ParseCloud functions to send the notification.
private void sendMessage(){
if(messageEditText.getText().toString().length() > 0) {
String messageToSend = messageEditText.getText().toString();
messageEditText.setText("");
MessageBO messageBO = new MessageBO();
messageBO.setText(messageToSend);
messageBO.setUserIdSender(idUser);
messageBO.setUserIdReceiver(idContact);
insertMessage(messageBO.getUserIdSender().toString(),
messageBO.getUserIdReceiver().toString(),
messageBO.getText().toString());
enviarNotificacionPush(messageBO);
}
actualizarMensajes();
}
private void sendNotificationPush(MessageBO m){
HashMap<String,String> map = new HashMap<String, String>();
map.put("Message", m.getText().toString());
ParseCloud.callFunctionInBackground("SendPush",map, new FunctionCallback<Object>() {
#Override
public void done(Object object, ParseException e) {
if (e == null){
System.out.println("----------------------------");
System.out.println("NOTIFICATION SUCCES: " + object);
System.out.println("----------------------------");
}else{
System.out.println("----------------------------");
System.out.println("ERROR ON NOTIFICATION PUSH: " + e.getMessage());
System.out.println("CODE: " + e.getCode());
System.out.println("----------------------------");
}
}
});
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("Message", m.getText().toString());
map2.put("user", idUser);
ParseCloud.callFunctionInBackground("SendPush2",map2, new FunctionCallback<Object>() {
#Override
public void done(Object object, ParseException e) {
if (e == null){
System.out.println("----------------------------");
System.out.println("NOTIFICATION 2.0 SUCCESS: " + object);
System.out.println("----------------------------");
}else{
System.out.println("----------------------------");
System.out.println("ERROR ON NOTIFICATION PUSH 2.0: " + e.getMessage());
System.out.println("CODE: " + e.getCode());
System.out.println("----------------------------");
}
}
});
ParseCloud.callFunctionInBackground("SendPush3",map2, new FunctionCallback<Object>() {
#Override
public void done(Object object, ParseException e) {
if (e == null){
System.out.println("----------------------------");
System.out.println("NOTIFICACION 3.0 SUCCESS: " + object);
System.out.println("----------------------------");
}else{
System.out.println("----------------------------");
System.out.println("ERROR ON NOTIFICACION PUSH 3.0: " + e.getMessage());
System.out.println("CODE: " + e.getCode());
System.out.println("----------------------------");
}
}
});
}
As you can see, I use 3 functions that send notifications, all of them said that it was a success, but in my android emulator never arrive a notification. I check my parse Dashboard and even though that it says that the notifications were sent, it also says 0 deliveries. I need your help please because I don't know exactly what I'm doing wrong.
If you need, the info of my Android emulator is the following:
My android emulator info
[EDIT 1]
(I don't know how to refer the comment that ask me to do it but anyways) Because I see that maybe you'll need the installation class.
installation class
All installations are from the emulator due to I uninstall and install again the application. There is algo my smartphone, that is a Huawei (that also I can't see notifications but I know thats due to Huawei problems with google services).
[EDIT 2]Hello again, here is my Parse Server configuration(aka the index.js of my parse). I'm using the parse_server_example repository by the way.
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
const express = require('express');
const ParseServer = require('parse-server').ParseServer;
const path = require('path');
var ParseDashboard = require('parse-dashboard');
const args = process.argv || [];
const test = args.some(arg => arg.includes('jasmine'));
const databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
const config = {
databaseURI: databaseUri || 'mongodb://admin:123#localhost:27017/ParseServer?authSource=admin',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'MY_APP_ID',
masterKey: process.env.MASTER_KEY || 'MY_MASTER_KEY', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'http://192.168.10.100:1337/parse/', // Don't forget to change to https if needed
liveQuery: {
classNames: ['Posts', 'Comments'], // List of classes to support for query subscriptions
},
push: {
android: {
apiKey: 'AAAASP09btg:APA91bGxn3e0vJX0ri2DeFEWUjAODTCaP3mfCQ0la3oiIgNqNYUlj2THFlEwRjqnXGuI-8H_l5-0xZtyscn3yY4mRrAL5tNHYXrM8NBltgCwCx1gH8LFVvgAWubmV2Zsa5NkmD53vCeO'
}
}
};
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var configdashboard = {
"allowInsecureHTTP": true,
"apps": [
{
"serverURL": "http://192.168.10.100:1337/parse/",
"appId": "MY_APP_ID",
"masterKey": "MY_MASTER_KEY",
"appName": "ParseServer01"
}
],"users": [
{
"user": "root",
"pass": "123456"
}
]
};
var dashboard = new ParseDashboard(configdashboard,{allowInsecureHTTP:configdashboard.allowInsecureHTTP});
const app = express();
app.use('/dashboard', dashboard);
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
const mountPath = process.env.PARSE_MOUNT || '/parse';
if (!test) {
const api = new ParseServer(config);
app.use(mountPath, api);
}
// Parse Server plays nicely with the rest of your web routes
app.get('/', function (req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function (req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
const port = process.env.PORT || 1337;
if (!test) {
const httpServer = require('http').createServer(app);
httpServer.listen(port, function () {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
}
module.exports = {
app,
config,
};
[EDIT 3] Hello again, I was trying to send notifications with curl and this is what happens:
curl -X POST \
-H "X-Parse-Application-Id: wPacsFQMmP" \
-H "X-Parse-Master-Key: DwonoEbeNf" \
-H "Content-Type: application/json" \
-d '{
"where": {
"deviceType": {
"$in": [
"android"
]
}
},
"data": {
"title": "The Shining",
"alert": "All work and no play makes Jack a dull boy."
}
}'\ http://192.168.10.100:1337/parse/push
{"result":true}[
Also as additional info, when I try making a push using FCM only (that means, follow this Firebase FCM documentation) and the result is basically the same, it says it was sent succesfully but I don't see it on the android emulator, not even in my old smartphone (Nokia 6).
[EDIT 4] I turn on verbose, and this is what I found in my parse logs about SendPush cloud function.
REQUEST for [POST] /parse/push: {\\n \\\"channels\\\": [\\n \\\"SignChat\\\"\\n ],\\n \\\"data\\\": {\\n \\\"alert\\\": \\\"The Giants won against the Mets 2-3.\\\"\\n }\\n}\",\n \"method\": \"POST\",\n \"timestamp\": \"2021-10-28T20:25:27.623Z\",\n \"url\": \"/parse/push\"\n },\n {\n \"level\": \"verbose\",\n \"message\": \"RESPONSE from [POST] /parse/functions/SendPush: {\\n \\\"response\\\": {}\\n}\",\n \"result\": {\n \"response\": {}\n },\n \"timestamp\": \"2021-10-28T20:25:27.619Z\"\n }
To send push notifications for Android devices, the required fields are deviceToken and GCMSenderID.
However, according to the screenshot you sent, the GCMSenderId of your installations is empty, and it's required for sending push notifications.
In your MainActivity, you're not explicitly set it, which is needed to save it properly.
Here's a sample code showing how you can do that:
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("GCMSenderId", INSERT_YOUR_SENDER_ID);
installation.saveInBackground();
Once both fields are filled, the push notification might work properly.

getResponseHeader is empty

here is an Android mobile application , from which I'm making call to SAP SERVER .I came across a very strange problem.
I'm making a ajax call to server and getting data as expected.
but the problem is getResponseHeader is coming empty. But I can see the response header in browser console and it is as per my expectation.
How to get the response header?
Browser Console image
var a = {};
a = {
// object that contains HTTP headers as name value pairs
"Authorization" : "Basic " + btoa(username + ":" + password),
"X-CSRF-Token" : "Fetch",
},
$.ajax({
type: "GET",
cache: false,
url: requestUri1,
headers: a,
success: function(a, b, c) {
globalTocken = c.getResponseHeader("X-CSRF-Token");
alert(globalTocken);
},
statusCode: {
401: function() {
alert("User name and password is wrong");
},
403: function() {
alert("error 403");
}
},
error: function(a, b) {
alert(b);
}
});
I have tried these ways also.
OData.request ({
requestUri: requestUri1,
method: "GET",
headers: {
"Authorization" : "Basic " + btoa(user_name + ":" + pass_word),
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
"X-CSRF-Token":"Fetch"
}
},
function (data, response)
{
var header_xcsrf_token = response.headers['x-csrf-token'];
//console.log(header_xcsrf_token);
alert(header_xcsrf_token);
},function(err) {
//Error Callback:
alert("Error occurred " + err.message + err.response.statusText);
});
Another way
var request = {
headers : {
// object that contains HTTP headers as name value pairs
"Authorization" : "Basic " + btoa(user_name + ":" + pass_word),
"X-CSRF-Token" : "Fetch",
},
requestUri : requestUri1, // OData endpoint URI
method : "GET",
datatype : "json",
};
OData
.read(
request,
function(data,response) {
x_csrf_token = response.headers["X-CSRF-Token"];
}, function(err) {
//Error Callback:
alert("Error occurred " + err.message + err.response.statusText);
});
}
I have done lot of R&D and reached to a conclusion that all of the three coding are correct problem is from server side, it is not generating Token everytime so I have saved token in local memory and using it until the new one will not get generate from server(I'm making call to server everytime). it is working for me.
function save_all(){
var globalTocken,X_CSRF_Token,a = {};
a.Authorization = "Basic " + btoa("username" + ":" + "password"),
a["X-CSRF-Token"] = "fetch",
$.ajax({
type: "get",
cache: !1,
url: requestUri1,
headers: a,
dataType: "xml",
success: function(a, b, c) {
if(!c.getResponseHeader("X-CSRF-Token")){
globalTocken = localStorage.savedTocken;
X_CSRF_Token = globalTocken;
else{
globalTocken = c.getResponseHeader("X-CSRF-Token");
localStorage.removeItem("savedTocken");
localStorage.setItem("savedTocken",globalTocken);
X_CSRF_Token = globalTocken;
}
},
statusCode: {
401: function() {
alert("User name and password is wrong");
},
403: function() {
alert("error 403");
}
},
error: function(a, b) {
alert(b);
}
});

Get separate JSON from the response

My team & I are working on a chatting app: an Android client, & a web client.
Recently, we stumbled up a blocking issue. Here is how:
So the web & the Android client (I will refer to them as 'the clients' from now on) communicate with a Node.js server.
We're actually working on the login/signup section. This is an example of what we have so far:
Android client
MainActivity.java
Button loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new LoginListener());
private class LoginListener implements View.OnClickListener {
#Override
public void onClick(View v) {
CustomAsyncTask manageSession = new CustomAsyncTask();
Map<String, String> params = new HashMap<>();
params.put("postURL", "/signin");
params.put("username", mUsername.getText().toString());
params.put("password", mPassword.getText().toString());
manageSession.execute(params);
}
}
Briefly, what this code does, is that it sends a parametrized POST request to the /signin route.
Web client
<form ...>...</form>
<script type="text/javascript">
$('button').click(function(){
$.post('/signin',{username : $('#username').val(),password :$('#password').val()});
})
</script>
Server side
// signin post
app.post('/signin', function (req, res) {
connection.query('SELECT * FROM User WHERE ((username = "' + req.body.username + '" OR email = "' + req.body.username + '") AND password = "' + req.body.password + '")', function (err, rows) {
if (err) throw err;
// If the user entered a valid username or email, then check for the password
if (rows.length > 0 && rows[0].password == rows[0].password) {
res.render('index', { status: "SUCCESS", username: req.body.username })
} else {
// Valid username or email, but invalid password
res.render('index', { status: "FAILURE", username: req.body.username })
}
});
})
The problem
As you can see from the code snippets above, the clients send POST requests to the /signin route, but:
The Android client expects pure JSON as a response
The web client expects a whole page as a response (index.ejs)
res.render() solves the problem for client 2, res.end({json}) solves it for client 1.
Is there a way we could separate the response, so that each client gets what it wants ?
What is the optimal way to work this out ?
You can add an extra variable to get if it is coming from web or android and then do as needed.
e.g.-
app.post('/signin', function (req, res) {
connection.query('SELECT * FROM User WHERE ((username = "' + req.body.username + '" OR email = "' + req.body.username + '") AND password = "' + req.body.password + '")', function (err, rows) {
if (err) throw err;
// If the user entered a valid username or email, then check for the password
if (rows.length > 0 && rows[0].password == rows[0].password) {
if(req.body.device_type == "web"){
res.render('index', { status: "SUCCESS", username: req.body.username })
}
else{
res.end({ status: "SUCCESS", username: req.body.username })
}
} else {
// Valid username or email, but invalid password
if(req.body.device_type == "web"){
res.render('index', { status: "FAILURE", username: req.body.username })
}
else{
res.end({ status: "FAILURE", username: req.body.username })
}
}
});
})
and in android:-
params.put("postURL", "/signin");
params.put("username", mUsername.getText().toString());
params.put("password", mPassword.getText().toString());
params.put("device_type", "android");
manageSession.execute(params);
in web:-
$.post('/signin',{username : $('#username').val(),password :$('#password').val(),device_type:'web'});
Let me know if there's any more problem.

Json error with xamarin

My environment is Android and i use Xamarin for do my project.
I have a problem with my connection to server, for that i use Json my error is :
`Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2. at Newtonsoft.Json.Linq.JObject.Load`
so my code app side is :
public async Task Login (string user_email, string user_password)
{
var content = new Dictionary<string, string> { {
"user_email",
user_email
},
{
"user_password",
user_password
}
};
String str = await ProcessPOST ("/api/login", content);
JObject data = JObject.Parse (str);
if (data ["success"] != null)
return (string)data ["success"];
throw new Exception ((string)data ["error"]);
}
and server side is :
So login
public function login() {
if ($this->method == "POST") {
if ($this->_data("user_email") && $this->_data("user_password")) {
$u_dao = new UserDAO();
$users = $u_dao->executeSelect("WHERE user_email = :user_email", array("user_email" => $this->_data("user_email")));
if (!isset($users[0]))
return $this->_response(array("error" => "User not found"), 403);
$user = $users[0];
if ($user && crypt($this->_data("user_password"), $user->user_password) == $user->user_password) {
$token = bin2hex(openssl_random_pseudo_bytes(16));
$user->user_token = $token;
$u_dao->update($user);
return $this->_response(array("success" => $token));
}
return $this->_response(array("error" => "Bad login"), 403);
}
return $this->_response(array("error" => "Missing data"), 500);
}
return $this->_response(array("error" => "Wrong method"), 405);
}
and code of _response
protected function _response($data, $status = 200) {
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
return json_encode($data);
}
and now of _requestStatus
private function _requestStatus($code) {
$status = array(
200 => 'OK',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
);
return ($status[$code]) ? $status[$code] : $status[500];
}
and when i try to connect my web service is online , but i forget to said when i have error like "Missing Data" i haven't error of JObject but when i have success i have error.
so i show to all two str one of error:
"{\"error\":\"Missing data\"}"
and one of succes:
"''{\"success\":\"db035db78a9f1e64d71c83bcbb45ffa5\"}"
i want to said thanks to all people which help me . And i'm sorry for my bad english but i'm french .
i hope to be clear but if u have question u can ask them.
I don't see any necessary use for Json.net here. I would simplify and just check if the response contains "success" or "error".

Phonegap/Pushwoosh Android retrieving Device id / Token

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. :)

Categories

Resources