How do I insert $data and $param into body of email - javascript

I am not a programmer and using phprunner to create page to send an email to selected records.
I have used some pre-existing code via this link
https://phprunner.com/phprunner/docs/email_selected_users.htm
and a modification to it on stackoverflow (Thanks [Micheal.M][1]). I need to input the 'from' 'subject' and 'body' via a form. The 'subject' and 'from' parts works fine.
But how can I get the $params["emailBody"] and the $data["FirstName"] both to appear in the 'body' of the email?
'FirstName' field is from a table called Students_ALL.
Can someone please guide me? I have tried for two days and cannot figure it out. Please find the code below: THANK YOU SO MUCH in advance - Mayo
SERVER
if( $params["emailBody"] ||$params["emailSubject"] || $params["emailFrom"] )
{
$emails = array();
while( $data = $button->getNextSelectedRecord() )
{
// Send only if email field not empty
if( $data["Email1"] ) {
// This no longer should be an array of emails
$from = $params["emailFrom"];
$email = $data["Email1"];
$subject = $params["emailSubject"];
$body = $params ["emailBody"];
// Email will be sent for each record
$arr = runner_mail(array('to' => $email, 'subject' => $subject, 'from' => $from, 'htmlbody' => $body));
}
}
$result["txt"] = "Emails were sent.";
if (!$arr["mailed"])
{
$errmsg = "Error happened:
";
$errmsg.= "File: " . $arr["errors"][0]["file"] . "
";
$errmsg.= "Line: " . $arr["errors"][0]["line"] . "
";
$errmsg.= "Description: " . $arr["errors"][0]["description"] . "
";
$result["txt"] = $errmsg;
}
}
CLIENT BEFORE
if ( proxy["emailUsers"] === true ) {
params["emailFrom"] = proxy["emailFrom"];
params["emailBody"] = proxy["emailBody"];
params["emailSubject"] = proxy["emailSubject"];
proxy["emailUsers"] = false;
return true;
}
var selBoxes = pageObj.getSelBoxes( pageid ),
args = {
modal: true,
header: "Input from, subject and body",
html: '<div>'
+ '<div>From: <input type="text" id="emailFrom"s style="margin: 5px 0"></div>'
+ '<div>Subject: <input type="text" id="emailSubject"s style="margin: 5px 0"></div>'
+ '<div>Body: <textarea id="emailBody"></textarea></div>'
+ '</div>',
footer: '' + Runner.lang.constants.TEXT_SAVE + ''
+ '' + Runner.lang.constants.TEXT_CANCEL + '',
afterCreate: function( win ) {
$("#emailUsersSave").on("click", function( e ) {
var context = win.body();
proxy["emailUsers"] = true;
proxy["emailFrom"] = $("#emailFrom", context).val();
proxy["emailBody"] = $("#emailBody", context).val();
proxy["emailSubject"] = $("#emailSubject", context).val();
$('[id="' + ctrl.id + '"]').click();
e.preventDefault();
win.destroy();
});
$("#emailUsersCancel").on("click", function( e ) {
e.preventDefault();
win.destroy();
});
}
};
if ( selBoxes.length == 0 || !confirm('Do you really want to email these records?') ) {
return false;
}
Runner.displayPopup( args );
return false;
CLIENT AFTER
var message = result["txt"] + " !!!";
ctrl.setMessage(message);
[1]: https://stackoverflow.com/users/2432106/michal-m

Related

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

localstorage data not persisting between pages

I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});

Remove form submit button and replace with loading gif

I have a form with a submit button and would like to remove the button and replace it with a loading gif image. I don't want this to happen just on click, since the form is verified I want the button to disappear only when all input fields are correctly filled so that the gif image shows progress. How can I do this?
Note: This is not a event to fire on success either, I want it to be a progress indicator. On success the form fade and display a message: "Thanks for contacting us! We will get back to you very soon..." and the jQuery below already handles this.
Here is the php code:
<?php
// Email address verification
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
$subject = 'Query from My Domain';
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($number == '') {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
and here is the jQuery:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var numberLabel = form.find('label[for="contact-number"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Full name');
emailLabel.html('Email');
numberLabel.html('Contact number');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.numberMessage !== '') {
numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});
do an ajax .done() after your ajax call to replace the button back

Ui Autocomplete return all values online but in localhost works

I'm trying about 2 days to fix this I will blow my mind I can't anymore..When I am running it in localhost it's just working fine but when I am trying it online its just returns same values...and all values not returns the search term I can't understand why.
Jquery
$(document).ready(function($){
$('#quick-search-input2').autocomplete({
source:'All/home/directsearch.php',
minLength:2,
autoFocus: true,
select: function(event,ui){
var code = ui.item.id;
if(code != '') {
location.href = 'Movies/' + code;
}
},
html: true,
open: function(event, ui) {
$('ul.ui-autocomplete').slideDown(500)('complete');
$(".ui-autocomplete").css("z-index", 1000);
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("" + item.label + "")
.appendTo(ul);
};
});
PHP
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'search';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
$term = stripslashes($_GET ['term']);
$term = mysql_real_escape_string($_GET ['term']);
$a_json = array();
$a_json_row = array();
include '../../connect.php';
/* ***************************************************************************** */
if ($data = $mysqli->query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5")) {
while($row = mysqli_fetch_array($data)) {
$title = $row['title'];
$year = htmlentities(stripslashes($row['year']));
$type = $row['type'];
$customercode= htmlentities(stripslashes($row['link']));
$category= htmlentities(stripslashes($row['category']));
$synopsis= htmlentities(stripslashes($row['synopsis']));
$img= htmlentities(stripslashes($row['img']));
$id= htmlentities(stripslashes($row['id']));
$category = str_replace(" | ",", ", $category);
$shit = "'";
$ltitle = strtolower($title);
if ($type == "DL-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/HD.png">';
}
else if ($type == "Non-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/NonHD.png">';
}
else if ($type == "CAM")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/CAM.png">';
}
else
{
$qualityresponse = "";
}
$stitle = preg_replace("/[^A-Za-z0-9]/", "", $ltitle);
$a_json_row["id"] = $customercode;
$a_json_row["value"] = ''.$term.'';
$a_json_row["label"] = '
'.$qualityresponse.'<span class="titles">'.$title.'</span><p>'.$year.'</p></center>
';
array_push($a_json, $a_json_row);
}
}
$foundnum = mysql_num_rows(mysql_query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5"));
if ($foundnum == 0)
{
$a_json_row["label"] = '
<li class="ac-no-results ac-item-hover ac-item-selected">No Movies found</li>
';
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
$mysqli->close();
$term = mysql_real_escape_string($_GET ['term']);
to
$term = mysqli->real_escape_string($_GET ['term']);

Retrieving a JSON result

Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;

Categories

Resources