php code send notification to all devices GCM - php

I need a little help to send notification to all devices at once.
I know array need to be used for that but can't get the idea. A little hint will also work
DB table design
id gcm_regid name email created_at
Currently i have to fill out the form for all the devices and send notification one by one.
PHP code:
<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>
</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>
send_message.php
<?php
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;
}
?>
EDIT: Or can anyone tell me how do i use checkbox for select all "id"s?

Related

How can I reload images on a main page after uploading images to a form in the sub page?

I am using Tutor LMS with WordPress. There is a dashboard page and it has sub pages. I have a sub page called My Organization that allows the user to update a form and also upload a logo and backdrop image. The logo and backdrop are the images used for the main dashboard page and shows on top for all sub pages.
The good thing is that if I update the form fields and hit the update button, it will refresh and then the fields will be updated thereafter (got some major help for that one). The dingy thing is that the logo and backdrop don't update unless I refresh again.
Here is a screen recording
I have been looking for a fix but I can't seem to find anything. I tried using
<script>
window.opener.location.reload();
</script>
but it did not work.
Please let me know if you have a lead!
Here is my code for the subpage called My Organization:
<?php
global $wpdb;
$user_id = get_current_user_id();
$org_id = get_user_meta($user_id, '_org_id', true);
if (isset($_POST['update']) && wp_verify_nonce( $_POST['logo_url_nonce'], 'logo_url' ) && wp_verify_nonce( $_POST['backdrop_url_nonce'], 'backdrop_url' )) {
$orgs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_organization` WHERE id = $org_id"));
$user_org = null;
foreach($orgs as $org) {
$user_org = $org;
}
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
if ($_FILES['logo_url']['size'] > 0) {
$logo_attachment_id = media_handle_upload( 'logo_url', $_POST['post_id']);
$logo_url = wp_get_attachment_url($logo_attachment_id);
} else {
$logo_url = $user_org->logo_url;
}
if ($_FILES['backdrop_url']['size'] > 0) {
$backdrop_attachment_id = media_handle_upload( 'backdrop_url', $_POST['post_id']);
$backdrop_url = wp_get_attachment_url($backdrop_attachment_id);
} else {
$backdrop_url = $user_org->backdrop_url;
}
$name = isset($_POST['org_name']) ? $_POST['org_name'] : "";
$short = isset($_POST['shortname']) ? $_POST['shortname'] : "";
$ind = isset($_POST['industry']) ? $_POST['industry'] : "";
$desc = isset($_POST['description']) ? $_POST['description'] : "";
$logo = isset($_FILES['logo_url']) ? $logo_url : "";
$backdrop = isset($_FILES['backdrop_url']) ? $backdrop_url : "";
$wpdb->query(
$wpdb->prepare("
UPDATE `wp_organization` SET
name = %s,
shortname = %s,
industry = %s,
description = %s,
logo_url = %s,
backdrop_url = %s
where id = %s
",
$name, $short, $ind, $desc, $logo, $backdrop, $org_id
)
);
$orgs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_organization` WHERE id = $org_id"));
$user_org = null;
foreach($orgs as $org) {
$user_org = $org;
}
?>
<!-- organization info form -->
<div class="tutor-px-20">
<form class="py-4 col-md-6 mx-auto" method="post" action="" enctype="multipart/form-data">
<div class="d-flex tutor-justify-center tutor-fs-3 tutor-fw-bold tutor-mb-20">
Organization Information
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Name</label>
<input type="text" required name="org_name" value="<?php echo $user_org-> name; ?>" class="form-control mb-3" />
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Industry</label>
<input type="text" name="industry" value="<?php echo $user_org-> industry; ?>" class="form-control mb-3" />
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Short name (4 characters)</label>
<input type="text" name="shortname" required maxlength="4" value="<?php echo $user_org-> shortname; ?>" class="form-control mb-3" />
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Description</label>
<textarea class="form-control mb-3" name="description" rows="5" cols="50"><?php echo trim(stripslashes($user_org-> description)); ?></textarea>
</div>
<div class="d-flex tutor-justify-around">
<div class="tutor-form-group">
<label class="tutor-form-label">Logo (Size: 200x200px Limit: 200kb)</label>
<div class="input-group mb-3">
<input type="file" accept=".png,.jpg,.jpeg" name="logo_url" id="logo_url" multiple="false">
<input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID()?>"/>
<?php wp_nonce_field( 'logo_url', 'logo_url_nonce' ); ?>
</div>
</div>
<div class="tutor-form-group">
<label class="tutor-form-label">Backdrop (Size: 1140x275px Limit: 600kb)</label>
<div class="input-group mb-3">
<input type="file" accept=".png,.jpg,.jpeg" name="backdrop_url" id="backdrop_url" multiple="false">
<input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID()?>"/>
<?php wp_nonce_field( 'backdrop_url', 'backdrop_url_nonce' ); ?>
</div>
</div>
</div>
<div class="tutor-mt-32 d-flex tutor-justify-center">
<input type="submit" name="update" value='Update' class='btn btn-primary'>
</div>
</form>
</div>
The images are used in the main page called Dashboard and here is a snip of the code:
<div class="tutor-wrap tutor-wrap-parent tutor-dashboard tutor-frontend-dashboard tutor-dashboard-student tutor-mt-80 tutor-pb-40">
<div class="tutor-container" >
<?php if($org_id) { ?>
<div class="tutor-row tutor-d-flex tutor-justify-between tutor-mb-20"
style="background-image: url('<?php echo $user_org->backdrop_url; ?>'); background-size: auto; height:275px; border-radius: 20px;">
<div class="tutor-d-flex tutor-justify-center tutor-mb-60 ">
<div class="tutor-avatar tutor-avatar-xl" style="width:150px; height:150px; position: absolute; top:155px">
<img src="<?php echo $user_org->logo_url; ?>">
</div>
I would add an "id" to the div containing the image (and background). Then using ajax to push the code snip again.
Build a little example, not perfect, but should give you an idea. You can pass data to another php page, do stuff and return the data in JSON to work on it.
Note : Make sure you do thing securely (aka, use sessions to pass critical data, else someone could pass other data and get informations from other users).
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div id="logo"><img src="loading.jpg" /></div>
<script>
function UpdateLogo() {
$.ajax({
url: "ajax.php",
type: "POST",
dataType: "json",
data: {
action: "updateLogo",
},
success: function (response) {
console.log(response);
if (response["STATUS"] == "OK") {
$("#logo").html('<img src="' + response["logo"] + '">');
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#logo").html("Error;" + errorThrown);
},
});
}
UpdateLogo();
</script>
</body>
</html>
ajax.php
<?php
if ($action = "UpdateLogo") {
//do stuff using sessions variable or whatever secure.
$return['STATUS'] = 'OK';
$return['logo'] = 'bla.jpg';
echo json_encode($return);
}

PHP-How to add an "Enter passcode" screen before user accesses website

So I have a chatting site in PHP, but the problem is that anyone can access any "chatroom". Is there a way to add an "Enter passcode" text box to the site before they are able to access the real thing? And if possible I would prefer not using those JavaScript pop-ups. And for the people who really want to help, I don't need any CSS.
My code:
index.php:
<?php
session_start();
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: ../../index.php"); //Redirect the user
}
if(isset($_POST['enter'])){
if($_POST['name'] != ""){
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
function loginForm(){
echo
'<div id="loginform">
<p>Please enter your name to continue!</p>
<form action="index.php" method="post">
<label for="name">Name —</label>
<input type="text" name="name" id="name" />
<input type="submit" name="enter" id="enter" value="Enter" />
</form>
</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Chat</title>
<meta name="description" content=" Chat Application" />
<link rel="stylesheet" href="../../css/chat.css" />
</head>
<body>
<?php
if(!isset($_SESSION['name'])){
loginForm();
}
else {
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
$.post("post.php", { text: clientmsg });
$("#usermsg").val("");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 2500);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to end the session?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
<?php
}
?>
post.php:
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>

Error in adding details by Ajax

Hello frndz i need a help i am trying to add detail by my form but no getting any value..and error is reflecting as "add request fails"..can anyone solve my error i am not getting what to do for this.. ther is my code
webapp.js
// Add company button
$(document).on('click', '#add_employee', function(e){
e.preventDefault();
$('.lightbox_content h2').text('Add Employee');
$('#form_employee button').text('Add');
$('#form_employee').attr('class', 'form add');
$('#form_employee').attr('data-id', '');
$('#form_employee .field_container label.error').hide();
$('#form_employee .field_container').removeClass('valid').removeClass('error');
$('#form_employee #ID').val('');
$('#form_employee #Name').val('');
$('#form_employee #Lastname').val('');
$('#form_employee #Email').val('');
$('#form_employee #Username').val('');
$('#form_employee #Password').val('');
$('#form_employee #Mobile').val('');
$('#form_employee #Website').val('');
show_lightbox();
});
// Add company submit form
$(document).on('submit', '#form_employee.add', function(e){
e.preventDefault();
// Validate form
if (form_employee.valid() == true){
// Send company information to database
hide_ipad_keyboard();
hide_lightbox();
show_loading_message();
var form_data = $('#form_employee').serialize();
var request =
$.ajax({
url: 'data.php',
cache: false,
data: {job:"add_employee",form_data},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output){
if (output.result == 'success'){
// Reload datable
table_employee.api().ajax.reload(function(){
hide_loading_message();
var Name = $('#Name').val();
show_message("Employee Name '" + Name + "' added successfully.", 'success');
}, true);
} else {
hide_loading_message();
show_message('Add request failed', 'error');
}
});
request.fail(function(jqXHR, textStatus){
hide_loading_message();
show_message('Add request failed: ' + textStatus, 'error');
});
}
});
data.php
<?php
// Database details
$db_server = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'example1';
// Get job (and id)
$job = '';
$id = '';
if (isset($_GET['job'])){
$job = $_GET['job'];
if ($job == 'get_employee' ||
$job == 'get_employee_detail' ||
$job == 'add_employee' ||
$job == 'edit_employee' ||
$job == 'delete_employee'){
if (isset($_GET['id'])){
$id = $_GET['id'];
if (!is_numeric($id)){
$id = '';
}
}
} else {
$job = '';
}
}
// Prepare array
$mysql_data = array();
// Valid job found
if ($job != ''){
// Connect to database
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()){
$result = 'error';
$message = 'Failed to connect to database: ' . mysqli_connect_error();
$job = '';
}
if ($job == 'add_employee'){
// Add company
$query = "INSERT INTO employees SET ";
if (isset($_GET['ID'])) { $query .= "ID = '" . mysqli_real_escape_string($db_connection, $_GET['ID']) . "', "; }
if (isset($_GET['Name'])) { $query .= "Name = '" . mysqli_real_escape_string($db_connection, $_GET['Name']) . "', "; }
if (isset($_GET['Lastname'])) { $query .= "Lastname = '" . mysqli_real_escape_string($db_connection, $_GET['Lastname']). "', "; }
if (isset($_GET['Email'])) { $query .= "Email = '" . mysqli_real_escape_string($db_connection, $_GET['Email']) . "', "; }
if (isset($_GET['Username'])) { $query .= "Username = '" . mysqli_real_escape_string($db_connection, $_GET['Username']). "', "; }
if (isset($_GET['Password'])) { $query .= "Password = '" . mysqli_real_escape_string($db_connection, $_GET['Password']). "', "; }
if (isset($_GET['Mobile'])) { $query .= "Mobile = '" . mysqli_real_escape_string($db_connection, $_GET['Mobile']) . "', "; }
if (isset($_GET['Website'])) { $query .= "Website = '" . mysqli_real_escape_string($db_connection, $_GET['Website']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'add Employee error';
} else {
$result = 'success';
$message = 'Employees added success';
}
// Close database connection
mysqli_close($db_connection);
}
// Prepare data
$data = array(
"result" => $result,
"message" => $message,
"data" => $mysql_data
);
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
?>
**index.html**
<!doctype html>
<html lang="en" dir="ltr">
<head>
<title>Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=1000, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Oxygen:400,700">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="design.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script charset="utf-8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<script charset="utf-8" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"> </script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script charset="utf-8" src="webapp.js"></script>
</head>
<body>
<div id="page_container">
<h1>Details of Employees</h1>
<button type="button" class="button" id="add_employee">Add Employees</button>
<table class="datatable" id="table_employee">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Mobile No</th>
<th>Website</th>
<th>Functions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="lightbox_bg"></div>
<div class="lightbox_container">
<div class="lightbox_close"></div>
<div class="lightbox_content">
<h2>Add Employees</h2>
<form class="form add" id="form_employee" data-id="" novalidate>
<div class="input_container">
<label for="Name">Name: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Name" id="Name" value="" required>
</div>
</div>
<div class="input_container">
<label for="Lastname">Lastname: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Lastname" id="Lastname" value="" required>
</div>
</div>
<div class="input_container">
<label for="Email">Email: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Email" id="Email" value="" required>
</div>
</div>
<div class="input_container">
<label for="Username">Username: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Username" id="Username" value="" required>
</div>
</div>
<div class="input_container">
<label for="Password">Password: <span class="required">*</span></label>
<div class="field_container">
<input type="password" class="text" name="Password" id="Password" value="" placeholder="eg. X8df90EO" required>
</div>
</div>
<div class="input_container">
<label for="Mobile">Mobile: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Mobile" id="Mobile" maxlength="10" pattern="[7-9]{1}[0-9]{9}" placeholder="Only 10 digit Mobile no"required>
</div>
</div>
<div class="input_container">
<label for="Website">Website: <span class="required">*</span> </label>
<div class="field_container">
<input type="text" class="text" name="Website" id="Website" value="" placeholder="https://www.domain.com" required>
</div>
</div>
<div class="button_container">
<button type="submit">Add Employees</button>
</div>
</form>
</div>
</div>
<div id="message_container">
<div id="message" class="success">
<p>This is a success message.</p>
</div>
</div>
<div id="loading_container">
<div id="loading_container2">
<div id="loading_container3">
<div id="loading_container4">
Loading, please wait...
</div>
</div>
</div>
</div>
</body>
</html>
Change your submit HTML code to <input type="submit" value="Add Employees"></input>
And use my javascript source
<script type="text/javascript">
$( "#form_employee" ).submit(function( event ) {
var data = $(this).serializeArray();
data.push(
{name: "job", value: "add_employee"}
);
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "jsOnChange.php", //Set-Your-URL-Here
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
error: function(e)
{
alert(JSON.stringify(e, null, 4));
},
success: function(strDrivers){
alert(JSON.stringify(strDrivers, null, 4));
}
});
});
</script>
In .php listener
<?php
ini_set("allow_url_fopen", true);
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
echo $jsonStr;
?>
You will get
Hope this help!!!
I think you code have some mistake at this place
var form_data = $('#form_employee').serialize();
var request =
$.ajax({
url: 'data.php',
cache: false,
data: {job:"add_employee",form_data},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
Replace it with
var form_data = $('#form_employee').serialize();
form_data.job='add_employee';
var request =
$.ajax({
url: 'data.php',
cache: false,
data: form_data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
Also in PHP side before print json_encode string add ob_clean() because you have mentioned dataType: json in ajax request.
ob_clean();
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;

PHP:unable to echo a variable from DB

I'm writing a chat script but I have problem with echo some variables!
I have written this piece of code in chat.php to show the messages:
<?php
session_start();
$id=$_GET['id'];
if(isset($id)){
global $id;
global $qs;
global $answerer;
global $sp;
global $name;
include('config.php');
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$id=$conn->quote(htmlentities($id));
$find=$conn->prepare("SELECT * FROM qs WHERE id=:id");
$find->bindParam(':id',$id);
$find->execute();
if($rows=$find->fetch(PDO::FETCH_ASSOC)){
$qs=$rows['question'];
$answerer=$rows['answerer'];
}
$answerer=explode("(",$answerer);
$ansgiver=$conn->prepare("SELECT * FROM ruhani WHERE name=:answerer");
$ansgiver->bindParam(':answerer',$answerer[0]);
$ansgiver->execute();
if($row=$ansgiver->fetch(PDO::FETCH_ASSOC)){
$name=$row['username'];
$avatar=$row['avatar'];
$sp=$row['sp'];
}
class chat {
public function fetchMessage() {
include('config.php');
global $id;
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$ans=$conn->prepare("SELECT answere FROM ans WHERE q_id=:id ");
$ans->bindParam(':id',$id);
$ans->execute();
}
public function throwMessage($id, $text,$sayer){
include('config.php');
global $id;
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$send=$conn->prepare("INSERT INTO ans(q_id,answere,sayer) VALUES(:q_id,:text,:sayer) ");
$send->bindParam(':q_id',$id);
$send->bindParam(':text',$text);
$send->bindParam(':sayer',$sayer);
$send->execute();
}
}
$chat = new chat();
?>
<!DOCTYPE html>
<head>
<title>Example Title</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style/style.css" media="screen, projection" />
<script src="js/jquery-1.6.3.min.js"></script>
<script src="js/chat.js"></script>
</head>
<body>
<div class="all">
<div class="env">
<span><?php echo $name ?>|<?php echo $sp ?></span>
<span>Hi,Can I help you?</span><br>
<span>me:<?php echo $qs ?></span>
<div class="messages"></div>
</div>
<textarea name="ask_ans" class="ask_ans" id="ask_ans" placeholder="Please write here!"></textarea><br>
<input type="submit" class="submit" name="submit" value="send" />
<input type="hidden" id="hidden" value=<? echo $id ?> />
<input type="hidden" id="hidden2" value=<? echo $_SESSION['$username'] ?> />
</div>
</body>
<?php
}
?>
and this code for Ajax part(chat.js):
var chat = { }
chat.fetchMessage=function (){
$.ajax({
url:"send.php",
type: 'POST',
data: {method : 'fetch'},
cache:false,
success: function(data){
$(".all .env .messages").html(data)
}
});
}
chat.throwMessage=function (id,message,sayer){
if($.trim(message).length != 0 ){
$.ajax({
url:"send.php",
type: 'POST',
data: {method : 'throw' , id : id , message : message , sayer : sayer },
cache:false,
success: function(data){
chat.fetchMessage();
$(".ask_ans").val('');
}
});
}
}
chat.entry=$(".all .submit");
chat.entry.bind('click',function (evt){
evt.preventDefault();
chat.throwMessage($("#hidden").val(),$(".ask_ans").val(),$("#hidden2").val());
});
chat.interval=setInterval(chat.fetchMessage(),5000);
chat.fetchMessage()
And this is send.php:
<?php
require('chat.php');
if (isset($_POST['method']) and !empty($_POST['method'])){
$chat =new chat();
$method =trim($_POST['method']);
if ($method === 'fetch'){
$messages=$chat->fetchMessage();
if (!empty($messages)){
while($r=$messages->fetch(PDO::FETCH_ASSOC)){
$sayer=$r['sayer'];
if($sayer===$starter){
?>
<span class="text" style="float:left"><? echo $r['answere'] ?></span>
<?php
}else{
?>
<span class="text" style="float:right"><? echo $r['answere'] ?></span>
<?php
}
}
}
}else if ($method === 'throw'){
$message=trim(htmlentities($_POST['message']));
$id=trim(htmlentities($_POST['id']));
$sayer=trim(htmlentities($_POST['sayer']));
if(!empty($message) and !empty($id) and !empty($sayer)){
$chat->throwMessage($id,$message,$sayer);
}
}
}
?>
I am getting an error:
Undefined index:id
My problem is that I can't echo $qs,$name,$sp in chat.php.
Can anyone understand the wrong part of my code?
After long time I checked my code,I understand the problem:)
As you see I'm using PDO::quote() and it puts ' ' over the word.So that When I was exploding the variable here:$answerer=explode("(",$answerer);,it couldn't find the correct word to search in DB and didn't echo the variable.
And now I have deleted PDO::quote() and my code is working correct.:-)

how to push notification on all user in database with php

this is my file php use jquery to send text from view to send_message.php based only for one id. i want change this code become send text from view to send_message.php to all id registered. you can see this code
<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>
</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 } ?>
<?php
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
this code send input from "txt_message" to user based id and "gcm_regid" so one txt_message for one id, but i try to send same txt_message for multiple id. help me, thank yuo

Categories