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.
Related
I am making a chat box in codeigniter, but after enter the name and message, pop up box is coming showing 'Forbidden'.
I am really confused what I put instead shout.php here(chatbox.php')
$.post('shout.php', load_data, function(data) {
instead of 'shout.php' I put http://localhost/myfoldername/application/views/shout.php
my controller
money_c
function chat(){
$this->load->view('chatbox');
}
chatbox.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chat Box</title>
<style type="text/css">
<!--
.shout_box {
background: #627BAE;
width: 260px;
overflow: hidden;
position: fixed;
bottom: 0;
right: 20%;
z-index:9;
}
.shout_box .header .close_btn {
background: url(images/close_btn.png) no-repeat 0px 0px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .close_btn:hover {
background: url(images/close_btn.png) no-repeat 0px -16px;
}
.shout_box .header .open_btn {
background: url(images/close_btn.png) no-repeat 0px -32px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .open_btn:hover {
background: url(images/close_btn.png) no-repeat 0px -48px;
}
.shout_box .header{
padding: 5px 3px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: bold;
color:#fff;
border: 1px solid rgba(0, 39, 121, .76);
border-bottom:none;
cursor: pointer;
}
.shout_box .header:hover{
background-color: #627BAE;
}
.shout_box .message_box {
background: #FFFFFF;
height: 200px;
overflow:auto;
border: 1px solid #CCC;
}
.shout_msg{
margin-bottom: 10px;
display: block;
border-bottom: 1px solid #F3F3F3;
padding: 0px 5px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
color:#7C7C7C;
}
.message_box:last-child {
border-bottom:none;
}
time{
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: normal;
float:right;
color: #D5D5D5;
}
.shout_msg .username{
margin-bottom: 10px;
margin-top: 10px;
}
.user_info input {
width: 98%;
height: 25px;
border: 1px solid #CCC;
border-top: none;
padding: 3px 0px 0px 3px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.shout_msg .username{
font-weight: bold;
display: block;
}
-->
</style>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('.message_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
//reset value of message box
$('#shout_message').val('');
}).fail(function(err) {
//alert HTTP server error
alert(err.statusText);
});
}
});
//toggle hide/show shout box
$(".close_btn").click(function (e) {
//get CSS display state of .toggle_chat element
var toggleState = $('.toggle_chat').css('display');
//toggle show/hide chat box
$('.toggle_chat').slideToggle();
//use toggleState var to change close/open icon image
if(toggleState == 'block')
{
$(".header div").attr('class', 'open_btn');
}else{
$(".header div").attr('class', 'close_btn');
}
});
});
</script>
</head>
<body>
<div class="shout_box">
<div class="header">chat box<div class="close_btn"> </div></div>
<div class="toggle_chat">
<div class="message_box">
</div>
<div class="user_info">
<input name="shout_username" id="shout_username" type="text" placeholder="Your Name" maxlength="15" />
<input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" />
</div>
</div>
</div>
</body>
</html>
shout.php
<?php
####### db config ##########
$db_username = 'root';
$db_password = '';
$db_name = 'money1';
$db_host = 'localhost';
####### db config end ##########
if($_POST)
{
//connect to mysql db
$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
if(isset($_POST["message"]) && strlen($_POST["message"])>0)
{
//sanitize user name and message received from chat box
//You can replace username with registerd username, if only registered users are allowed.
$username = filter_var(trim($_POST["username"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$message = filter_var(trim($_POST["message"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$user_ip = $_SERVER['REMOTE_ADDR'];
//insert new message in db
if(mysqli_query($sql_con,"INSERT INTO shout_box(user, message, ip_address) value('$username','$message','$user_ip')"))
{
$msg_time = date('h:i A M d',time()); // current time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$username.'</span><span class="message">'.$message.'</span></div>';
}
// delete all records except last 10, if you don't want to grow your db size!
mysqli_query($sql_con,"DELETE FROM shout_box WHERE id NOT IN (SELECT * FROM (SELECT id FROM shout_box ORDER BY id DESC LIMIT 0, 10) as sb)");
}
elseif($_POST["fetch"]==1)
{
$results = mysqli_query($sql_con,"SELECT user, message, date_time FROM (select * from shout_box ORDER BY id DESC LIMIT 10) shout_box ORDER BY shout_box.id ASC");
while($row = mysqli_fetch_array($results))
{
$msg_time = date('h:i A M d',strtotime($row["date_time"])); //message posted time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$row["user"].'</span> <span class="message">'.$row["message"].'</span></div>';
}
}
else
{
header('HTTP/1.1 500 Are you kiddin me?');
exit();
}
}
but after entering name and message alert box will pop up showing 'Forbidden'.
I don't think you fully grasp MVC architecture and this is not really the place to explain it.
I suggest you study it more but what may work for you here is to modify your controller function to this:
function chat(){
$this->load->view('chatbox');
}
function shout(){
$this->load->view('shout');
}
You would then need to ensure that the URL(route) works.
Assume you current URL is www.mysite.com/someController/chat/
then the new URL would be www.mysite.com/someController/shout/
If this URL does not work then you would need to sort out your route to make it work.
If this URL works, then you need to update your JQuery URL from
.post('shout.php', load_data, function(data) {
to
.post('/someController/shout/', load_data, function(data) {
TL;DR
The jquery post function accesses the fule via the URL like a real person. It cannot load the file directly.
I had attempted with the following code and a little stuck now but here is what I'm wanting to achieve:
enter value in input and update preview html below
once user is happy with preview output can click generate
once clicked generate it will actually write the preview HTML to a first_name-last_name.html file within that same folder and then redirect to the first_name-last_name.html file
jQuery / HTML form:
<html>
<head>
<title>Ambient Lounge - Create eSig</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<!-- Include JS File Here -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url('http://fonts.googleapis.com/css?family=Open+Sans');
body {
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, sans-serif;
}
hr {
margin-bottom: 1.5em;
}
.error_wrapper {
color: #D8000C;
background-color: #FFBABA;
padding: 10px;
margin-bottom: 1em;
}
.success_wrapper {
color: #4F8A10;
background-color: #DFF2BF;
padding: 10px;
margin-bottom: 1em;
}
#main {
float: left;
width: 20%;
}
#preview {
float: left;
width: 80%;
}
form label {
display: none;
}
form input {
margin-bottom: 0.5em;
padding: 5px;
width: 80%;
}
</style>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".error_wrapper, .success_wrapper").hide();
var v_first_name = $("#first_name").val();
var v_last_name = $("#last_name").val();
var v_title = $("#title").val();
var v_address = $("#address").val();
var v_phone = $("#phone").val();
var v_mobile = $("#mobile").val();
var v_email = $("#email").val();
var v_web = $("#web").val();
$(".input_change").keyup(function(){
$("#btn").attr("disabled", "disabled");
var current_input = $(this).attr("id");
console.log(current_input);
$("#p_" + current_input).html($("#" + current_input).val());
});
$("#verify").click(function() {
var has_error = false;
$('#first_name, #last_name, #title, #address, #email, #web').each(function() {
$(this).attr('style', 'border: 0;');
if ($(this).val() == '') {
$(".error_msg").html("<strong>Error(s):</strong> You are missing some enteries, please check and try again.");
$(".error_wrapper").show();
$(this).attr('style', 'border: 1px solid red;');
has_error = true;
}
});
if (has_error != true) {
$(".error_wrapper").hide();
alert("You have verified changes, please double check and if happy click create otherwise change values and verify again.");
$("#btn").removeAttr('disabled');
}
});
$("#btn").click(function() {
$.post("create_post.php", { // Data Sending With Request To Server
first_name:v_first_name,
last_name:v_last_name,
title:v_title,
address:v_address,
phone:v_phone,
mobile:v_mobile,
email:v_email,
web:v_web
}, function(response,status) { // Required Callback Function
alert("*----Received Data----*\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
alert(response);
if(status == "success") {
$("#form")[0].reset();
} else {
}
});
});
});
</script>
</head>
<body>
<h2>Create e-mail signature</h2>
<hr>
<div class="error_wrapper">
<div class="error_msg"></div>
<ul></ul>
</div>
<div class="success_wrapper">
<div class="success_msg"><strong>Congraulations!</strong> You have successfully create your e-mail signature. You can view your e-mail signature by clicking here.</div>
</div>
<div id="main">
<form id="form" method="post">
<label>First Name</label>
<input type="text" name="first_name" id="first_name" class="input_change" placeholder="First name"/><br>
<label>Last Name</label>
<input type="text" name="last_name" id="last_name" class="input_change" placeholder="Last name"/><br>
<label>Title</label>
<input type="text" name="title" id="title" class="input_change" placeholder="Job title"/><br>
<label>Address</label>
<input type="text" name="address" id="address" class="input_change" placeholder="Business Address"/><br>
<label>Phone</label>
<input type="text" name="phone" id="phone" class="input_change" placeholder="Phone number"/><br>
<label>Mobile</label>
<input type="text" name="mobile" id="mobile" class="input_change" placeholder="Mobile number"/><br>
<label>Email</label>
<input type="text" name="email" id="email" class="input_change" placeholder="Email address"/><br>
<label>Web</label>
<input type="text" name="web" id="web" class="input_change" placeholder="Web address"/>
</form>
<button id="verify">Verify</button> <button id="btn" disabled>Create</button>
</div>
<div id="preview">
<!-- PREVIEW OF HTML EMAIL -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url('http://fonts.googleapis.com/css?family=Open+Sans');
.clear {
clear: both;
}
b {
font-weight: normal;
}
b.bold {
font-weight: bold;
}
.emailContent {
font-family:'Open Sans', 'Helvetica Neue', Helvetica, sans-serif;
width: 480px;
color: #767676;
}
.emailContent a {
color: #2A96B4;
text-decoration: none;
}
.emailName {
height: 62px;
}
.emailName img {
float: right;
margin-top: 1.2em;
margin-right: 0.8em;
}
.emailName p {
color: #767676;
font-size: 0.8em;
float: left;
}
.emailName p span {
color: #2A96B4;
font-weight: bold;
font-size: 1.2em;
}
.emailLogo {
height: 46px;
clear: both;
}
.emailLogo img {
float: left;
margin-top: 0.3em;
}
.emailLogo ul.socialList {
list-style: none;
border-left: 1px solid #aaaaaa;
padding-left: 1.5em;
margin: 0 0 0 1.5em;
float: left;
}
.emailLogo ul.socialList li {
display: inline-block;
}
.emailLogo ul.socialList li img {
margin: 0;
}
.emailDetails {
clear: both;
border-top: 5px solid #2A96B4;
margin-top: 1em;
}
.emailDetails p {
font-size: 12px;
margin: 0.3em 0;
}
.emailDetails p.larger {
font-size: 14px;
}
.emailDetails p span {
color: #2A96B4;
}
.emailNotice {
border-top: 1px solid #aaaaaa;
font-size: 0.6em;
padding-top: 0.8em;
margin-top: 2.5em;
}
</style>
<div class="emailContent">
<div class="emailName">
<p><span><b id="p_first_name" class="bold">James</b> <b id="p_last_name" class="bold">Brandon</b></span><br><b id="p_title">Global Technical Lead</b></p>
<img src="http://www.ambientlounge.com/emails/like-us-on-facebook.png" alt="Like us on Facebook" />
</div>
<div class="clear"></div>
<div class="emailLogo">
<img src="http://www.ambientlounge.com/emails/ambient-logo-email.png" alt="Ambient Lounge" />
<ul class="socialList">
<li><img src="http://www.ambientlounge.com/emails/icon-facebook.png" alt="Facebook" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-twitter.png" alt="Twitter" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-instagram.png" alt="Instagram" /></li>
</ul>
</div>
<div class="clear"></div>
<div class="emailDetails">
<p><span>a:</span> <b id="p_address">Old knows Factory, Unit 5C, Office 14, St Anns Hill Road, Nottingham, NG3 4GN</b></p>
<p><span>p:</span> <b id="p_phone">+44(0) 844 579 1112</b> | <span>m:</span> <b id="p_mobile">+44(0) 771 809 0 809</b></p>
<p class="larger"><span id="p_email">james#ambientlounge.com</b> | <b id="p_web">www.ambientlounge.co.uk</b></p>
</div>
<p class="emailNotice">This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.</p>
</div>
</div>
</body>
</html>
Current PHP Post file:
<?php
if($_POST["first_name"]) {
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$title = $_POST["title"];
$address = $_POST["address"];
$phone = $_POST["phone"];
$mobile = $_POST["mobile"];
$email = $_POST["email"];
$web = $_POST["web"];
$filePath == $first_name + "-" + $last_name + ".html";
if(file_exists($filePath)){
echo "Already exisits";
} else {
touch( $filePath ); //create file if it does not exist
fwrite( $file, '
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Ambient Lounge - e-Mail Signature (James Brandon)</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url("http://fonts.googleapis.com/css?family=Open+Sans");
.clear {
clear: both;
}
.emailContent {
font-family:"Open Sans", "Helvetica Neue", Helvetica, sans-serif;
width: 480px;
color: #767676;
}
.emailContent a {
color: #2A96B4;
text-decoration: none;
}
.emailName {
height: 62px;
}
.emailName img {
float: right;
margin-top: 1.2em;
margin-right: 0.8em;
}
.emailName p {
color: #767676;
font-size: 0.8em;
float: left;
}
.emailName p span {
color: #2A96B4;
font-weight: bold;
font-size: 1.2em;
}
.emailLogo {
height: 46px;
clear: both;
}
.emailLogo img {
float: left;
margin-top: 0.3em;
}
.emailLogo ul.socialList {
list-style: none;
border-left: 1px solid #aaaaaa;
padding-left: 1.5em;
margin: 0 0 0 1.5em;
float: left;
}
.emailLogo ul.socialList li {
display: inline-block;
}
.emailLogo ul.socialList li img {
margin: 0;
}
.emailDetails {
clear: both;
border-top: 5px solid #2A96B4;
margin-top: 1em;
}
.emailDetails p {
font-size: 12px;
margin: 0.3em 0;
}
.emailDetails p.larger {
font-size: 14px;
}
.emailDetails p span {
color: #2A96B4;
}
.emailNotice {
border-top: 1px solid #aaaaaa;
font-size: 0.6em;
padding-top: 0.8em;
margin-top: 2.5em;
}
</style>
<div class="emailContent">
');
fwrite( $file, '
<div class="emailName">
<p><span>'.$first_name.' '.$last_name.'</span><br>'.$title.'</p>
<img src="http://www.ambientlounge.com/emails/like-us-on-facebook.png" alt="Like us on Facebook" />
</div>
<div class="clear"></div>
<div class="emailLogo">
<img src="http://www.ambientlounge.com/emails/ambient-logo-email.png" alt="Ambient Lounge" />
<ul class="socialList">
<li><img src="http://www.ambientlounge.com/emails/icon-facebook.png" alt="Facebook" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-twitter.png" alt="Twitter" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-instagram.png" alt="Instagram" /></li>
</ul>
</div>
<div class="clear"></div>
<div class="emailDetails">
<p><span>a:</span> '.$address.'</p>
<p><span>p:</span> '.$phone.' | <span>m:</span> '.$mobile.'</p>
<p class="larger">'.$email.' | '.$web.'</p>
</div>
');
fwrite( $file, '
<p class="emailNotice">This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.</p>
</div>
</body>
</html>
');
$file = fopen( $filePath, "w" );
fwrite( $file, $data );
fclose( $file );
$data = file_get_contents( $filePath ); //do this after closing your writing
}
}
?>
You can write to a file with:
touch( $filePath ); //create file if it does not exist
$file = fopen( $filePath, "w" );
fwrite( $file, $data );
fclose( $file );
This will replace the entire file contents with what you fwrite().
You can check if a file already exists with
file_exists( $filePath );
You can define your custom file path in a manner like
$filePath = "whatever directory you want it to go to/". $firstnamevariable ."-". $lastnamevariable .".html";
You can keep a running $data variable that you write to the file at the end by appending to, like how $filePath above is appending. Or you can simply write to the file multiple time.
fwrite( $file, "<html><head></head><body>" );
fwrite( $file, "<div>First Name: ". $firstnamevaraible ."</div>" );
fwrite( $file, "<div>Last Name: ". $lastnamevariable ."</div>" );
fwrite( $file, "</body></html>" );
Once you've created your file, if you want to return the entire contents to the user you can do
$data = file_get_contents( $filePath ); //do this after closing your writing
Then you can echo $data to the user or if you want, just echo that function without the need for a variable.
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
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.
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.