Google Cloud Messaging- Sending Push Message To Android Using PHP - php

I am working on an android project where I need to push messages using GCM.
I wanna send the notification using only PHP and not HTML. How do I achieve this? The way I tried was just putting the gcm_regid and message as parameters to $gcm->send_notification($registration_ids,$msg) but I keep getting an error saying:-
Field "data" must be a JSON array: ["You Have A Notification!"]
Where "You Have A Notification!" is my msg!! Please help!! Thanks!
Code for send_notification is
public function send_notification($registatoin_ids, $message) {
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
This is the index.php used for sending the message using the button's on-click. I need to however do this automatically in the background without any button press and want to implement it in PHP.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.container{
width: 950px;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
}
ul.devices li{
float: left;
list-style: none;
border: 1px solid #dedede;
padding: 10px;
margin: 0 15px 25px 0;
border-radius: 3px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 50px;
}
ul.devices li textarea{
float: left;
resize: none;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>

Maybe this will work:
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => array("message" => $message),
);

You will need to embed the registration_id too in array.
$fields = array(
'registration_ids' => array($registatoin_ids),
'data' => array("message" => $message),
);

$fields[] = array(
'registration_ids' =>$registatoin_ids,
'data' =>$message
);
use square braces with $fields this will make it a json array

Related

PHP Customizing div to place next to each other

I have a problem. I created this code that shows products from my database like products:
<?php
include("connect.php");
session_start();
$status="";
if (isset($_POST['id']) && $_POST['id']!="")
{
$Id = $_POST['id'];
$result = mysqli_query($conn,"SELECT * FROM Producten WHERE `Id`='$Id'");
$row = mysqli_fetch_assoc($result);
$naam = $row['Naam'];
$id = $row['Id'];
$prijs = $row['Prijs'];
$foto = $row['Foto'];
$winkelwagen_array = array(
$id=>array(
'id'=>$id,
'naam'=>$naam,
'prijs'=>$prijs,
'hoeveelheid'=>1,
'foto'=>$foto)
);
if(empty($_SESSION["winkelwagen"]))
{
$_SESSION["winkelwagen"] = $winkelwagen_array;
$status = "<div class='box'>Product toegevoegd aan winkelwagen!</div>";
}
else
{
$_SESSION["winkelwagen"] = array_merge($_SESSION["winkelwagen"],$winkelwagen_array);
$status = "<div class='box'>Product toegevoegd aan winkelwagen!</div>";
}
}
?>
<html>
<head>
<link rel='stylesheet' href='css/style.css' type='text/css' media='all' />
</head>
<body>
<div style="width:700px; margin:50 auto;">
<?php
if(!empty($_SESSION["winkelwagen"]))
{
$winkelwagen_hoeveelheid = count(array_keys($_SESSION["winkelwagen"]));
?>
<div class="winkelwagen_div">
<img src="media/winkelwagen_logo.png" /> Winkelwagen<span><?php echo $winkelwagen_hoeveelheid; ?></span>
</div>
<?php
}
$result = mysqli_query($conn,"SELECT * FROM Producten");
while($row = mysqli_fetch_assoc($result))
{
echo "<div class='product_vak'>
<form method='post' actie=''>
<input type='hidden' name='id' value=".$row['Id']." />
<div class='foto'><img src='".$row['Foto']."' /></div>
<div class='naam'>".$row['Naam']."</div>
<div class='prijs'>€".$row['Prijs']."</div>
<button type='submit' class='koop'>Koop nu</button>
</form>
</div>";
}
mysqli_close($conn);
?>
<div style="clear:both;"></div>
<div class="melding_box" style="margin:10px 0px;">
<?php echo $status; ?>
</div>
</div>
</body>
</html>
with this css:
.product_vak {
float:left;
padding: 10px;
text-align: center;
}
.product_vak:hover {
box-shadow: 0 0 0 2px #e5e5e5;
cursor:pointer;
}
.product_vak .naam {
font-weight:bold;
}
.product_vak .koop {
text-transform: uppercase;
background: #F68B1E;
border: 1px solid #F68B1E;
cursor: pointer;
color: #fff;
padding: 8px 40px;
margin-top: 10px;
}
.product_vak .koop:hover {
background: #f17e0a;
border-color: #f17e0a;
}
.melding_box .box{
margin: 10px 0px;
border: 1px solid #2b772e;
text-align: center;
font-weight: bold;
color: #2b772e;
}
.table td {
border-bottom: #F0F0F0 1px solid;
padding: 10px;
}
.winkelwagen_div {
float:right;
font-weight:bold;
position:relative;
}
.winkelwagen_div a {
color:#000;
}
.winkelwagen_div span {
font-size: 12px;
line-height: 14px;
background: #F68B1E;
padding: 2px;
border: 2px solid #fff;
border-radius: 50%;
position: absolute;
top: -1px;
left: 13px;
color: #fff;
width: 14px;
height: 13px;
text-align: center;
}
.winkelwagen .verwijderen {
background: none;
border: none;
color: #0067ab;
cursor: pointer;
padding: 0px;
}
.winkelwagen .verwijderen:hover {
text-decoration:underline;
}
But when I load the page I see 2 products above each other in a very very large size. Now how can I get them to load next to each other and in a smaller size, because now they are filling the whole screen per product!
I already tried giving product_vak a width, but the image doesn't size with that!
How can I fix this?
try like this
.product_vak {
float:left;
padding: 10px;
text-align: center;
width:40%;

Uninitialized string offset: 36 Error ONLY when reloading page

I'm getting an error in my php page only when I reload it and sometimes it also comes without any warning..
I was trying to make a page where the user's can paste thier code and get the link to share it. The thing work's, but the error(s) on the main page are annoying.
Here's my full page code:
<?php
header("X-XSS-Protection: 1");
date_default_timezone_set("America/New_York");
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
// for generating random filenames
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$namelength = 35;
$randomfilename = '';
for($i = 0; $i < $namelength; $i++)
{
$randomfilename .= $chars[mt_rand(0, 36)];
}
if($_POST)
{
$title = $_POST['postTitle'];
$content = $_POST['postContent'];
$filename = $randomfilename;
$fname = $filename;
$filename = 'pastes/' . $filename . '.html';
$refresh = "Refresh:0; url=" . $filename;
$date = date("Y.m.d");
$time = date("h:i:sa");
if(strlen($title) > 100)
{
echo "<script>alert('Max 100 Characters Allowed!');</script>";
}
else if(strlen($title) <= 100)
{
$content = nl2br($content);
$content = filter_var($content, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_SANITIZE_ENCODED);
$title = filter_var($title, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_SANITIZE_ENCODED);
$fname = filter_var($fname, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_SANITIZE_ENCODED);
$link = 'http://openpaste.000webhostapp.com/' . $filename;
$handle = fopen($filename, "a");
fwrite($handle, "<html><head><title>" . $fname . "</title><link rel='stylesheet' href='style.css'></head><body><h1>" . $title . "</h1>" . "DATE: " . $date . "<br>TIME: " . $time . "<h2>Your File Link: " . $link . "</h2><p>" . $content . "</p><br></body></html>");
fclose($handle);
$f = fopen("ip.txt", "a");
fwrite($f, $user_ip . "\n");
fclose($f);
header($refresh);
}
}
?>
<html>
<head>
<title>OpenPaste | Home</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="overlay.css">
<style>
body{
margin: 0px;
font-size: 17px;
}
.nav{
background-color: royalblue;
padding: 2px;
font-family: georgia, sans-serif, tahoma, arial;
}
.nav font,a{
font-size: 25px;
text-decoration: none;
}
#icomenu{
width: 30px;
height: 30px;
margin-left: 10px;
margin-right: 10px;
border: none;
border-radius: 5px;
opacity: 0.7;
}
#icomenu:hover{
cursor: pointer;
opacity: 1.0;
box-shadow: 0px 0px 5px black;
}
.overlay-content a{
color: #ffffff;
}
.overlay-content a:hover{
color: yellow;
}
.content{
margin: 0;
padding: 1em;
background-color: firebrick;
}
form{
margin: 30px 0px 30px 0px;
font-family: sans-serif, georgia, sans, tahoma, arial;
font-size: 17px;
}
form input{
width: 50%;
text-align:center;
border:none;
border-radius: 10px;
padding: 2px;
margin-top: 5px;
font-family: sans-serif, georgia, sans, tahoma, arial;
font-size: 17px;
text-shadow: 5px 5px 10px #333;
}
form textarea{
width: 50%;
margin-top: 10px;
border: none;
border-radius: 10px;
padding: 2px;
height: 50%;
font-family: sans-serif, georgia, sans, tahoma, arial;
font-size: 17px;
}
form button{
border: none;
background-color: lime;
color: black;
padding: 5px 25px;
margin-top: 5px;
font-family: sans-serif, georgia, sans, tahoma, arial;
font-size: 17px;
}
form button:hover{
background-color: royalblue;
color: white;
cursor: pointer;
}
</style>
<script type="text/javascript">
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>
</head>
<body>
<!-- NAVIGATION -->
<div id="myNav" class="overlay">
×
<div class="overlay-content">
Home<br>
Our Projects<br>
About<br>
Contact<br>
</div>
</div>
<div class="nav">
<img id="icomenu" src="img/menu.png" onclick="openNav();">
<font color="white">OpenPaste</font>
</div>
<!-- BODY -->
<div class="main">
<div class="content">
<center>
<form action="" method="POST">
<input type="text" name="postTitle" placeholder="Your Title"><br>
<textarea rows="" cols="" name="postContent" placeholder="Your Paste.."></textarea><br>
<button type="submit" name="submit" value="Submit">Create Post</button>
</form>
</center>
</div>
</div>
</body>
</html>
I have tried setting the error message to off, but still want to know why I get the error?
Here is the image of the error: Error Image Here.
You can find my project files here: GitHub Project Repo incase you think that some asset is giving the problem.
Thanks in advance :)
EDIT: Thanks for replies :D
You need to change:-
$randomfilename .= $chars[mt_rand(0, 36)];
to
$randomfilename .= $chars[mt_rand(0, strlen($chars)-1)];
Because last index of $chars is 35 not 36 (as it started from 0 index).

This code push Null notification

I have this code to push notification (GCM) but when i am trying to push notification i got null notification (the string of my message is missing)
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.container{
width: 950px;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
}
ul.devices li{
float: left;
list-style: none;
border: 1px solid #dedede;
padding: 10px;
margin: 0 15px 25px 0;
border-radius: 3px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 50px;
}
ul.devices li textarea{
float: left;
resize: none;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
echo "in send message class";
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
GcmIntentService.java
package com.example.provenlogic1.myapplication;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
String TAG="pavan";
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
Log.d("pavan","in gcm intent message "+messageType);
Log.d("pavan","in gcm intent message bundle "+extras);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
String recieved_message=intent.getStringExtra("text_message");
sendNotification("message recieved :" +recieved_message);
Intent sendIntent =new Intent("message_recieved");
sendIntent.putExtra("message",recieved_message);
LocalBroadcastManager.getInstance(this).sendBroadcast(sendIntent);
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_signin_btn_text_disabled_dark)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Any idea would be appreciated.

Send values from one PHP file to another with JavaScript/AJAX

I have this form in a PHP file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function sendPushNotification(id){
var data = $('form#'+id).serialize();
// $('form#'+id).unbind('submit');
$.ajax({
url: "table_ready.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.bigcontainer{
width: auto;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
list-style: none;
}
.smallcontainer {
border: 2px solid #ccc;
width: 300px;
height: 100px;
overflow-y: scroll;
}
ul.devices li{
float: left;
display: inline;
padding: 10px;
margin: 0 15px 25px 0;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 150px;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<div class="bigcontainer">
<?php
include_once 'include/DB_Functions.php';
$db = new DB_Functions();
$state = $db->checkTableState();
if ($state != false)
$no_of_state = mysql_num_rows($state);
else
$no_of_state = 0;
if ($no_of_state > 0) {
?>
<ul class="devices">
<?php
while ($staterow = mysql_fetch_array($state)) {
$items = $db -> displayTable($staterow["state"]);
?>
<li>
<form id="<?php echo $staterow["state"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $staterow["state"] ?>')">
<h1>Τραπέζι: <?php echo $staterow["state"]; ?></h1>
<div class="smallcontainer">
<ul>
<?php
// $num_of_items = mysql_fetch_array($items);
while($row = mysql_fetch_array($items)){
$food = Array();
$quan = Array();
$food[] = $row['food'];
$quan[] = $row['uquantity'];
foreach( $food as $index => $f){
?>
<li>
<label>
<?php echo $f; ?> <?php echo $quan[$index]; }?>
</label>
</li>
<div class="clear"></div>
</form>
</li>
<?php
}
?>
</ul>
</div>
<div class="send_container">
<input type="hidden" name="table" value="<?php echo $staterow["state"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
<?php
}
} else {
?>
<li>No Users Registered Yet!</li>
<?php
}
?>
</ul>
</div>
</body>
</html>
I am using this function to send the value with name table, to my table_ready.php file:
<script type="text/javascript">
function sendPushNotification(id){
var data = $('form#'+id).serialize();
// $('form#'+id).unbind('submit');
$.ajax({
url: "table_ready.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
For some reason it doesn't work. My knowledge of JavaScript is very bad, and I can not figure out what I am doing wrong. The table_ready.php works fine but it doesn't accept the value and so it doesn't work. Any hint on what I am doing wrong?
I'm supposing you omitted part of the script (connection and query itself) and that is working correctly.
The second thing is the usage of jQuery serialize() (http://api.jquery.com/serialize/) it will convert form elements (input, textarea, select) to be sent, and your data is just inside <label>, try using some hidden fields so serialize will find and encode it to be sent to the other script.

Sending Push Notification on multiple devices

I'm trying to make an push notification on my android app by following this tutorial
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
I already got this tutorial working, but my problem is. It only send notification one by one. I need to send the notification to all gcm_id or registered id by just sending once.
Do anyone already solved this issue?
here is my index.php
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.container{
width: 950px;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
}
ul.devices li{
float: left;
list-style: none;
border: 1px solid #dedede;
padding: 10px;
margin: 0 15px 25px 0;
border-radius: 3px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 50px;
}
ul.devices li textarea{
float: left;
resize: none;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
send_message.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
GCM.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GCM
*
* #author Ravi Tamada
*/
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
I am not having exp in PHP but I can tell you the places where you can modify your code.
Make an array of ids and put into registration_ids.
At the end you must have all ids into registatoin_ids at
$fields = array(
'registration_ids' => $registatoin_ids, // HERE IT IS
'data' => $message,
);
into send_notification($registatoin_ids, $message).
In current it having single reg_id so it is sending notification to single device.

Categories