The browser cannot connect to the server in SSE - javascript

I am setting up a Server Sent Event connection between my instant messaging page and my sse page in php. But firefox tells me that it could not connect to the server. I followed an article telling me to put in php.ini : output_buffering = Off and zlib.output_compression = Off.
Then I arrived at this result by adding my personal code so that the code does what I want:
client code:
<script type="text/javascript">
var eventSource = new EventSource("includes/load_chat.php");
eventSource.onmessage = function(event) {
document.getElementById("message").innerHTML += event.data;
console.log('messsssage!!!!')
};
</script>
server code :
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include 'database_message.php';
global $msg_bdd;
$from = '2';
$to = '1';
$id_discution = "ezdhnijkezd&ézuoijde_hjé_àe'dzunbfezd";
// test values
$dmd_last_id_msg = $msg_bdd->prepare('SELECT * FROM message WHERE discution_id = :id ORDER BY creation_date DESC');
$dmd_last_id_msg->execute([
'id' => $id_discution
]);
while($message = $dmd_last_id_msg->fetch()){
$last_msg_date = $message['creation_date'];
$last_msg_id = array($message['id']);
break;
}
while (true) {
if(connection_aborted()) exit();
$dmd_if_new_msg = $msg_bdd->prepare('SELECT * FROM message WHERE discution_id = :id AND creation_date >= :last_creation ORDER BY creation_date');
$dmd_if_new_msg->execute([
'id' => $id_discution,
'last_creation' => $last_msg_date
]);
$data = 'data: ';
echo $data;
while($message = $dmd_if_new_msg->fetch()){
if(in_array($message['id'],$last_msg_id)){}
else{
if($message['user'] == $from){$id_div = "from";}
elseif($message['user'] == $to){$id_div = "to";}
$data = '<div class="message" id="' .$id_div. '"><p>' .$message['message']. '</p></div><br><br><br>';
$data = htmlspecialchars($data);
echo $data;
if ($message['creation_date'] > $last_msg_date) {
$last_msg_date = $message['creation_date'];
$last_msg_id = array($message['id']);
}
elseif($message['creation_date'] = $last_msg_date){
array_push($last_msg_id, $message['id']);
}
}
}
flush();
sleep(1);
}
?>
Where can the problem come from ? client ? server ? What is the problem? Thanks for reading

Related

Get json encode data from another ajax function

I'm using prestashop 1.6, I have an ajax function where I encode some data which I successfully retrieved on console withecho. Now I have to decode this json data in another ajax function to get a value for a specific variable. Sorry I'm a newbie with prestashop 1.6.
My first ajax function :
public function ajaxProcessAddQrVideo(){
$target_dir = _PS_IMG_DIR_.DS.'video_qr';
$id_product = Tools::getValue('id_product');
$stamp = strtotime('now');
$filename = 'video_qr_'.$id_product.'_'.$stamp.'.jpg';
$target_file = $target_dir.DS.$filename;
$upload = $_FILES['video_qr_attachment_file'];
$err = array();
$uploaded = false;
if($upload['type'] !='image/jpeg'){
array_push($err,"Veuillez entrer un fichier JPG");
}
if(empty($err)){
$uploaded = #move_uploaded_file($upload['tmp_name'], $target_file);
$this->context->smarty->assign('uploaded', $uploaded);
$this->context->smarty->assign('filename', $filename);
}
$this->json =array(
'uploaded'=>$uploaded,
'err'=>$err,
'id_product'=>$id_product,
'stamp'=>$stamp,
'file_name'=>$filename,
);
echo json_encode($this->json);
exit;
}
And I want to get the value of 'file_name' in my second ajax function:
public function ajaxProcessAddVideo(){
$img_path = json_decode($this->json,true);
$filename = $img_path['file_name'];
$id_lang = Context::getContext()->language->id;
$script = Tools::getValue('script');
$id_product = Tools::getValue('id_product');
$id_group_vid = Tools::getValue('cust_group');
//add qr_code video
$qr_code =$filename;
$err = true;
$insert = false;
$videos = array();
$vid = new MpsVideo();
$vid->id_product = $id_product;
$vid->url = $script;
$vid->cust_group = $id_group_vid;
$vid->date_add = date('Y-m-d H:i:s');
$vid->active = 1;
$vid->qrcode = $qr_code;
$is_existing = Db::getInstance()->getValue("SELECT COUNT(id_mps_video) FROM `ps_mps_video` WHERE id_product=$id_product AND url = '$script'");
if($is_existing==0){
$insert = $vid->save();
$id_group = explode(',',$id_group_vid);
$group_name = array();
foreach($id_group as $k){
$group = new Group($k);
$group_name[] = $group->name[$id_lang];
}
$vid->group_names = implode('<br/>',$group_name);
}
echo json_encode(array(
'err'=>$err,
'video_exists'=>$is_existing,
'insert'=>$insert,
'vid'=>$vid,
));
exit;
}
I don't know how to achieve this but I know its possible. If someone can help understand this, I would be very grateful.
the result of the first function is a json, that result must be read from another file and then passed to your second function. Or else the same function should read that json:
$data = file_get_contents("file/file_json_result.php");
$img_path = json_decode($data, true);

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

how do i manipulate a countdown timer using button in php?

I'm working on a bidding system. I have the timer to read from the database and display a message when it reaches 00:00. Now i want to manipulate the timer in such a way that when it is <= 10secs(00:00:00:10), and a button is clicked then it should reset back to 00:00:00:10 and continue. The timer display is in day, hour, minute, and seconds.
Here is the javascript code
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined")
BackColor = "white";
if (typeof(ForeColor)=="undefined")
ForeColor= "black";
if (typeof(TargetDate)=="undefined")
TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
FinishMessage = "";
if (typeof(CountStepper)!="number")
CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);
Here is the php code
<body>
<?php
$mysqli = new mysqli("localhost","root","", "auction");
if (!$mysqli)
{
die('Could not connect: ' . mysql_error());
}
else{
$sql = "INSERT INTO bids (id, description, closing_date) VALUES
(NULL, 'Acer Aspire 4736', '2011-10-22 18:50:26')";
}
$result = $mysqli->query("SELECT * FROM bids WHERE id = 1");
$row = mysqli_num_rows($result);
if ($row == 0)
{
die('No record found.');
}
$row = $result->fetch_array();
echo "Description: " . $row[1] . "<br />";
$closedate = date_format(date_create($row[2]), 'm/d/Y H:i:s');
echo "Closing Date: " . $closedate;
?>
<p>Time Left:
</p>
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "blue";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown.js"></script>
</body>
here is the code for the display in html
<?php
$A=0;
if ($A%4 ==0):;?>
<?php
while ($auction=$result->fetch_assoc()):;?>
<div class = "grid ">
<h4 class="c-head"><?=$auction['item_name']?></h4>
<img src='<?=$auction['item_image']?>' class="img-responsive">
<span class="timer">
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "";
ForeColor = "";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%%, %%H%%:%%M%%:%%S%%";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown\countdown.js">
</script>
</span>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="digit" class="form-control"
name="duration">
<span class="input-group-btn "><button class="btn btn-
primary c-button" type="button" name="bid">Bid now!</button></span>
</div>
</div>
<?php endwhile; $A++; endif;?>
I'm novice in php...just started learning it a couple of weeks ago. Your time is greatly appreciated.
I wroted that to help your start. I haven't currently a dev environment under hands so I didn't run this code,.
All the php files have to be put in the same directory to communicate
This file when required should allow you to communicate with your database. Moreover I used PDO that is good practice when requesting database to avoid SQL injections.
Please check the php documentation http://php.net/manual/fr/class.pdo.php
// database_connection.php
$host = 'localhost';
$user = 'root'; // Bad idea to user root user ^^'
$password = 'yourpassword';
$dbname = 'auction';
try {
$dsn = sprintf('mysql:host=%s;dbname=%s', $host, $dbname);
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // I active errors, if you are a beginner that'll help you, comment this in prod env
// I use PDO to avoid SQL injections, this line open a mysql connection, check the documentation
$connection = new PDO($dsn, $user, $password, $pdo_options);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
exit;
}
You have to implement a HTML POST form with a description input which will submit to this PHP file
This file handle the creation of a bid
// addBid.php
// You have to implement a HTLM POST form with the needed fields which will submit to this PHP file
// The url yourdomain.fr/addBid.php
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}
if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}
header('Location: ' . $url, true, $statusCode);
exit;
}
$description = isset($_POST['description']) ? $_POST['description'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended description isn't valid
if(empty($description) || !is_string($description)) {
redirectTo($urlListing);
}
// You should do some verification on the string that send the user, it can be malicious html/javascript code, XSS attack
// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'INSERT INTO bids(description, closing_date) VALUES(":description", ":closing_date")';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':description' => $description
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}
$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the bid is created
$urlListing .= '?created=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page
This third file handle the update of bid that is in the database
// updateBid.php
// The url yourdomain.fr/updateBid.php?bidId=6 will update the bid with id 6 into database
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}
if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}
header('Location: ' . $url, true, $statusCode);
exit;
}
$bidId = isset($_GET['bidId']) ? $_GET['bidId'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended bidId isn't valid
if(empty($bidId) || !is_numeric($bidId)) {
redirectTo($urlListing);
}
// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'UPDATE bids SET closing_date = ":dateToModify" WHERE id = :id';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':id' => $bidId
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}
$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the $bidId is present in database
$urlListing .= '?updated=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page
You should do some tutorials learn PHP and MYSQL, that'll help you a lot :)
Moreover when you use a PHP framework it is more difficult at the start but after that you'll learn a lot reading code. And the framework help you to stay in the "good practices", it very easy in php to do some shit code.
I hope I didn't so many syntax or logic error but I know that the stackoverflow community will correct me if needed
Sorry for my english !!
An up vote would be greatly appreciated :)

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

Weird Question Marks in JavaScript

I'm trying to create a script that pings my Minecraft server to check how many players are online, but for some reason question marks are getting displayed and it makes the whole website look like crap. Here's my PHP file.
<script>
function setOnline(online,max) {
var on = online;
var mx = max;
var main = document.getElementById('status_main');
main.className = "panel panel-success server-status";
var title = document.getElementById('status_title');
title.innerHTML = "Online";
var body = document.getElementById('status_body');
body.innerHTML = on + "/" + mx + " Players Online";
}
</script>
<script>
function setOffline() {
var bar = document.getElementById('status');
bar.className = "panel panel-danger server-status";
bar.text = "Offline";
}
</script>
<?php
$host = "localhost"; //IP/host of Minecraft server
$port = 25565; //Minecraft server port, not query port
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //Create the socket
$connected = socket_connect($socket, $host, $port); //Try and connect using the info provided above
if (!$connected)
die(); //No connection could be established
socket_send($socket, "\xFE\x01", 2, 0); //Send the server list ping request (two bytes)
$retVal = socket_recv($socket, &$data, 1024, 0); //Get the info and store it in $data
socket_close($socket); //Close socket
if ($retVal != false && substr($data, 0, 1) == "\xFF") //Ensure we're getting a kick message as expected
{
$data = substr($data, 9); //Remove packet, length and starting characters
$data = explode("\x00\x00", $data); //0000 separated info
$protocolVersion = $data[0]; //Get it all into separate variables
$serverVersion = $data[1];
$motd = $data[2];
$playersOnline = $data[3];
$playersMax = $data[4];
echo ("<script>setOnline('$playersOnline','$playersMax');</script>");
}
else
{
die();
}
?>
Here's what the result looks like when it's called:
http://cl.ly/image/3o2f3P121q0m
How can I get rid of the question marks?
This is likely a charset issue. The information is not being presented in the way that it was encoded.
You can var_dump $data to see its Content-Type.
Here is just a hypothesis: the actual encoding is ISO-8859-1, but it is being interpreted as UTF-8 (or UTF-16).
To make the browser use the correct encoding, you can add an HTTP header:
header("Content-Type: text/plain; charset=ISO-8859-1");
or use a meta tag.

Categories