let me first say that I'm no expert in web development so I might have made a stupid mistake but no amount of googling seems to be helping. I need to have a single html page (preprocessed in php) to display occasional events fired by a "server" page residing on the same machine.
I've readapted the basic w3schools server sent events example as follows and it seemed to be working fine until last night, but today (still working when first tested) I added a simple table and a ref to an external (empty) js file to the html and events stopped being caught by the page. I decided to roll back to the working code but even that doesn't work anymore. I had to remove the files and restore from a backup!
I'm sure the sse.php code is being run since part of what it does is removing records from a sqlite3 database and that's happening.
Here's the code, I really hope you can help me because I really have no idea what's happening.
This was tested on Linux + Xampp + Firefox and sadly this is a mandatory combination, having it work under other conditions is not useful at the moment. (fyi: opening the mon.php page in Opera gave me a single event and then stopped working as well)
Thank you all.
mon.php
<?php
if ( ! isset($_GET['mon']) ) {
die('mon code missing');
}
?>
<html>
<head>
<script type="text/javascript">
var evtSourceUrl = "sse.php?mon=" + <?php echo '"'.$_GET['mon'].'"'?>;
if(typeof(EventSource) !== "undefined") {
var source = new EventSource(evtSourceUrl);
source.onmessage = function(event) {
document.getElementById("info").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("info").innerHTML = 'sse not supported';
}
</script>
</head>
<body>
<p>
<span id="info"></span>
</p>
</body>
</html>
sse.php
<?php
function output_sse($msg) {
echo "data: " . $msg . "\n\n";
ob_end_flush();
flush();
}
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
$mon = null;
if ( isset($_GET["mon"]) ) {
$mon = $_GET["mon"];
} else {
output_sse('mon code missing');
die();
}
while ( true ) {
usleep(1000 * 100);
$db = new PDO("sqlite:ch.sqlite3");
if ( $db === false ) {
output_sse('err:PDO');
die();
}
$stmt_select = $db->query("SELECT * FROM CH WHERE IDMON='$mon';");
$stmt_delete = $db->prepare("DELETE FROM CH WHERE IDMON='$mon';");
$db->beginTransaction();
$res = $stmt_select->fetch();
$stmt_delete->execute();
$db->commit();
$db->close();
if ( strlen($res['TK']) > 0 && strlen($res['SP']) > 0 ) {
$msg = "$res['TK'] :: $res['SP']";
output_sse($msg);
}
}
?>
add.php (to add new records to be displayed - this works)
<?php
$mon = isset($_GET["mon"]) ? $_GET["mon"] : die ('mon code missing') ;
$tk = isset($_GET["tk"]) ? $_GET["tk"] : die ('tk code missing') ;
$sp = isset($_GET["sp"]) ? $_GET["sp"] : die ('sp code missing') ;
$db = new SQLite3('ch.sqlite3');
if ( $db === false ) {
die('Cannot open db');
}
$res = $db->exec("INSERT INTO CH('IDMON','TK','SP') VALUES('$mon','$tk','$sp');");
if ( $res != 1 ) {
echo 'insert failed';
}
if ( $db->close() === false ) {
die('Cannot close connection to db');
}
echo('ok');
?>
This seems to be a problem related to the PDO interface in the sse.php file. I replaced it with the SQLite3 class like the add.php file and everything started working fine. The transaction seemed to get stuck.
Related
I'm trying to make a notification to my simple php/js chat:
First, I'm trying to compare my log.html (which containing the messages):
my original post.php ( //jQuery request. It posts the client's input and data being sent to the post.php file each time the user submits the form and sends a new message.) The. post.php is saving the messages into log.html file.
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, 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);
}
?>
my edited post.php (trying to set up a function, which is checking the "new" message - comparing with old ones).
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
// Check if content is different
function text_check(){
$ah = fopen("log.html", 'rb');
$aha = preg_match(fread($ah, 8192), $text_message);
$result = true;
while(!feof($ah)) {
if( $aha === false){
$result = false;
break;
}
}
fclose($ah);
return $result;
}
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
If post.php function "text_check()" return true in my index.php:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function checkUpdate()
{
$.post("post.php", function(text_check){
if (text_check.toString()=="true") {
playSound();
}
});
}
function playSound()
{
var audio = new Audio('my_audio');
audio.play();
}
Is it a OK conception?
And how can I make an "orang-red blinking" notification, when browser is minimized?
I read something about title - have to change it. Will it work, if I change it every second with JS?
Hello I am using spout to run some excel reports. I have a user interface where they input date, model, and other information then I do a GET to send it to a php script where I run a query and then put all the results into an excel file like this:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
ob_start();
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
$xlsData = ob_get_contents();
ob_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
);
}
die(json_encode($response));
Then on the AJAX call I have the following:
$.ajax({
url: 'modelData/excel-export.php',
method: "GET",
data: {'modelNumber':modelNumber,'convertedFrom':converted_from_UTC,'convertedTo':converted_to_UTC,'selectedLine':selectedLine},
dataType:'json',
success: function(fileCreated){
}
}).done(function(data){
console.log(local);
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","combined_report_"+local+".xlsx");
$a[0].click();
$a.remove();
});
now if I run this in Firefox everything works I am able to download up to 4 months of data which is >60,000 records this has no problem. If I run this in google chrome I cannot download more than 1 week about 20,000 records and U get a "download failed -network error" I was using PHPExcel but then found out it didn't support too many records so I switched to spout but I find the same issue only in google chrome but I don't understand where this limitation is coming from. I have read multiple posts and I have tried setting headers, lengths etc but nothing has worked also I chatted with a spout forum and they said none of the headers were necessary but they were still unable to help me.
I think this question Download failed - network error in google chrome but working in firefox may be going close to the same direction as my issue.
Also I have tried running incognito mode chrome I have tried disabling all extensions
As a side note...The firefox download appears to work fine but we don't "support" firefox so it would be hard for customers to go to multiple browsers specially when they're not tech savy
Any help will be greatly appreciated! :)
I was able to solve this issue by doing the following:
JS
window.open("modelData/excel-export.php?modelNumber="+modelNumber+"&convertedFrom="+converted_from_UTC+"&convertedTo="+converted_to_UTC+"&selectedLine="+selectedLine,
'_blank'// <- This is what makes it open in a new window.
);
then on the PHP side:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
The library I am using just doesn't work very well with AJAX so this approach solved my issue. Thanks for all the help :)
I used Blob Javascript for the same problem.
this link maybe help someone :
Blob
I coded a website using HTML5 Server Sent Events and it's working like charm on Godaddy shared hosting, however the same site with exactly the same code isn't working on 101domain shared hosting.
Rest all is working fine, except chat functionality using Server Sent Events.
How to find the errors in the script.
Here is the HTML page, with SSE javascript code.
<?php
$get_value_this_url = "globalchat";
?>
<div id="chat">
<div id="chats-div">
<p id="tip">(tip! kickstart a discussion by sharing this page)</p>
<ul id="chats-ul">
<?php
/*This session id will be used to fetch the latest chat via SSE*/
$_SESSION["id"] = 1;
if($stmt = $con->prepare("SELECT `icicinbbcts_id`, `icicinbbcts_user`, `icicinbbcts_chats` FROM `icicinbbcts_chats` WHERE `icicinbbcts_video_id` = ? ORDER BY `icicinbbcts_id` DESC LIMIT 25")){
$stmt->bind_param("s", $video_id);
$video_id = $get_value_this_url;
if ($stmt->execute()) {
$stmt->bind_result($id, $user, $chats);
$stmt->store_result();
if($stmt->num_rows() > 0){
$_SESSION["offset"] = $stmt->num_rows;
}
while ($stmt->fetch()) {
//print_r($user .": ". $chats."<br>");
echo '<li class="chats"><span id="nicknameChats">'.$user.'</span>: '.$chats.'</li>';
//echo '<span class="line-spacing"></span>';
$_SESSION["offset"] = $stmt->num_rows;
if($_SESSION["id"] < $id){
$_SESSION["id"] = $id;
}
}
}else
echo $stmt->error;
}else
echo $stmt->error;
$stmt->free_result();
$stmt->close();
?>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("auto_update.php?r=<?php echo $get_value_this_url; ?>");
source.onmessage = function(event) {
var obj = JSON.parse(event.data);
$("#chats-ul").append('<li class="chats"><span id="nicknameChats">'+obj.user+'</span>: '+obj.chats+'</li>');
$('#chats-ul').scrollTop($(window).height());
};
} else {
document.getElementById("chats-ul").innerHTML = "Your browser doesn't support a part of HTML5, so please use modern browsers like Chrome, Firefox, etc.";
}
</script>
</ul>
</div>
<input id="text-area" class="q" name="text-input" form="textForm" maxlength="140" placeholder="Type to comment" ></input>
</div>
And here's the server side PHP script.
<?php session_start(); ?>
<?php //error_reporting(E_ALL); ?>
<?php require "connection.php";?>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if($stmt = $con->prepare("SELECT `icicinbbcts_id`, `icicinbbcts_user`, `icicinbbcts_chats` FROM `icicinbbcts_chats` WHERE `icicinbbcts_video_id` = ? AND `icicinbbcts_id` > ? ORDER BY `icicinbbcts_id` DESC")){
$stmt->bind_param("si", $video_id, $row_id);
$row_id = $_SESSION["id"];
$video_id = mysqli_real_escape_string($con, strip_tags($_GET["r"]));
if ($stmt->execute()) {
$stmt->bind_result($id, $user, $chats);
$stmt->store_result();
if($stmt->num_rows > 0){
while ($row = $stmt->fetch()) {
if($_SESSION["id"] < $id){
$send = array("user" => $user, "chats" => $chats);
echo "retry: 100\n";
echo "data: ".json_encode($send)."\n\n";
ob_end_flush();
flush();
$_SESSION["id"] = $id;
}
}
}
}else
echo $stmt->error;
}else
echo $stmt->error;
$stmt->close();
?>
The same above code works perfectly on Godaddy shared hosting, however the save code just isn't working on 101domain.
I tried putting charset UTF-8 in both PHP and HTML, but that din't help, I tried adding ob_flush in server side PHP script and it din't help too.
There's nothing wrong with connection.php because same file on other pages works fine.
On chat functionality the chat messages are getting inserted into the database, however it's not showing on the page, unless we refresh the page.
How to check for errors and how to debug Server Sent Events?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I did console.log and didn't find the log in chrome, when I placed console.log code at the point shown below in the code.
<script>
if(typeof(EventSource) !== "undefined") {
console.log("SSE is supported"); //placing console.log here, displays the message in chrome developer tool
var source = new EventSource("auto_update.php?r=<?php echo $get_value_this_url; ?>");
source.onmessage = function(event) {
console.log("message isn't received from server"); //placing console.log here doesn't display any log message in Chrome Developer Tool
var obj = JSON.parse(event.data);
$("#chats-ul").append('<li class="chats"><span id="nicknameChats">'+obj.user+'</span>: '+obj.chats+'</li>');
$('#chats-ul').scrollTop($(window).height());
};
} else {
document.getElementById("chats-ul").innerHTML = "Your browser doesn't support a part of HTML5, so please use modern browsers like Chrome, Firefox, etc.";
}
</script>
So from the console.log above, we see that the SSE script is not receiving messages from backend, and backend code is shown above, can you show what's wrong with the backend code?
Since the result it works with one provider but not another, it is probably a server configuration issue.
Here are some things you can try to narrow down the issue:
In the javascript script use console.log(event) to check if you are getting anything from the server
Check the network tab in the developer tools area of browsers (in Chrome choose other to view server sent events).
If there is no output then try narrowing the problem down on the server. Resolev SSE output early to see if SSE mechanism works. Bit by bit resolve the SSE later and later until it breaks. If there is a difference on a specific line between providers it may be due to the PHP version. To compare php versions run <?php phpinfo() ? in a php file.
If you find a difference contact your provider!
You want to report errors?
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
Hello there overflowers!
I´m new to asking on here,
but i´ve been reading a lot on here, which has helped me already.
This time though i am encountering a problem,
to which i can not seem to find a thread nor a solution.
So the following situation occured:
I have a frontend in which people can change the design to use by clicking on a button.
That does work quite well. But it should save the themename to database.
It says it does, but it does not - if that saving is triggered on the site with JS/JQuery.
It does though, if i trigger it manually with the PHP-file:
./lib/savetheme.php?user=username&theme=themename
If i trigger it via JS it goes through the php, which really echoes the needed TRUE.
But it does not save to database. It does not throw any errors (it would die - but it echoes true..).
So here comes the code...
common.php
<?php
function m($str) {
$str = mysql_escape_string($str);
return "'".$str."'";
}
?>
db-connect-data.php
<?php
$dbname = "dbname";
$dbuser = "dbuser";
$dbpw = "dbpw";
$dbhost = "localhost";
$dbport = "3306";
?>
db-connect.php
<?php
if (!mysql_connect($dbhost.":".$dbport, $dbuser, $dbpw)) {
die();
}
if (!mysql_select_db($dbname)) {
die();
}
?>
savetheme.php
require "./common.php";
require "./db-connect-data.php";
require "./db-connect.php";
if(isset($_GET)) {
$user = "";
$theme = "";
if($_GET['user'] != "") {
$user = $_GET['user'];
}
if($_GET['theme'] != "") {
$theme = $_GET['theme'];
}
$sql = "UPDATE users SET
theme = ".m($theme)."
WHERE username = ".m($user);
if(mysql_query($sql)) {
echo "TRUE";
} else {
echo mysql_error();
}
}
?>
profile.php
<?php
foreach (glob("./themes/*",GLOB_ONLYDIR) as $file) {
$output = str_replace("./themes/", "", $file);
echo '<button class="buttons themebuttons" id="'
.$output.'">'.$output.'</button>';
}
?>
<div class="ui-widget" id="savethemeok">
<br>
<div class="ui-state-green ui-corner-all">
<p>
Theme saved successfully!
</p>
</div>
</div>
<div class="ui-widget" id="savethemeerror">
<br>
<div class="ui-state-red ui-corner-all">
<p>
Error! Theme could not be saved!
</p>
</div>
</div>
main.js
$(document).ready(function() {
$(".buttons").button();
$(".themebuttons").click(function() {
var themename = $(this).attr("id");
var themepath = "./themes/" + themename + "/jquery-ui.css";
console.log("Saving new theme...");
$.get( "./lib/savetheme.php" , {
user: $("#loggeduser").attr("value"),
theme: "'" + themename + "'",
}, function(status) {
if(status == "TRUE") {
console.log("New theme: " + themename);
$("#theme").attr({href: themepath});
$("#savethemeok").show();
window.setTimeout(function() {
$("#savethemeok").fadeOut();
}, 2500);
} else {
console.log("Error: " + status);
$("#savethemeerror").show();
window.setTimeout(function() {
$("#savethemeerror").fadeOut();
}, 2500);
}
});
});
});
There is more code, i hope i got all the relevant code out,
but i do not think it will be any more overseeable
if i copy the almost 1000 lines of code not regarding this particular issue.
If needed i will do though.
I am happy and thankful with any suggestions, as i have already buried some time into that issue and seemingly i do not have any clue as to why it does not save to db when i trigger it via JS but works just fine when manually triggering it with the php...
I am sorry if there is a thread about this somewhere which i have missed out on.
If there is, please let me know. I did not find any though.
Then again, maybe I´m too stupid to look for it,
i did struggle a bit with putting my problem in words...
Thank you all in advance!
the problem is fixed.
i had changed the user variable to another user - so naturally it did not save to the user i was looking at.
im sorry to have alerted you.
thanks for viewing into it - and in the honor of Robin Williams: CARPE DIEM.
From what you've posted in the question, your columns theme and username appear to be of varchar type. Try and modify your query to the following:
$sql = "UPDATE users SET theme = '".m($theme)."' WHERE username = '".m($user)."'";
Got this website --> http://www.secureshop.gr/POOL/acrosshotels/website/
If you check on the left sidebar there is the "find a hotel" sidebar where when you choose location from the drop down menu, the Hotel menu changes the options. This works with ajax. The problem is that it's not working with all versions of IE. When you choose a destination, the hotel drop down menu is empty/blank.
The javascript code is this. Pretty simple and works onclick of the destinations options
<script type="text/javascript">
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("hotelselection").innerHTML=xmlhttp.responseText;
}
}
if(str == 0) {
str = 0;
}
xmlhttp.open("GET","includes/ajaxlocationsearch.php?location="+str+"&language=<?php echo $language; ?>",true);
xmlhttp.send();
}
</script>
The ajax file is this
$language = $_GET["language"];
$location = $_GET['location'];
if($location == "0") {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' order by
appearance",$link_id);
}else {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' and
short_description='$location' order by appearance",$link_id);
} ?>
<option value="0"><?php $a = $language."_choose_hotel"; echo ${$a};
?></option>
<?php while($row = mysql_fetch_assoc($result)) { ?>
<option value="<?php echo $row['appearance']; ?>"><?php echo
$row['title']; ?></option>
<?php } ?>
Thank you in advance :)
I made some testing and I found out that your code had some issues with the structure. You should always have the code properly formatted in order to find errors and problems faster. I formatted your code and found some problems with nesting and your query.
I would also like to warn you that you had a pretty serious SQL injection problem, which I fixed in this code by using prepared statements and a small extra preg_replace to strip all unwanted characters from the query and table in general. You should totally go and learn a little bit more about preventing SQL injections. There are great topics here that are dedicated to the subject and I made a list of these articles to you:
stackoverflow.com - How can I prevent SQL injection in PHP
php.net - SQL Injection
Here is the code I formatted and fixed. I have tested it by using no parameter, an empty parameter, a value that does not exist in the database, and a value that does exist in the database. Each one returned the value accordingly: three first ones return null, while the real query returns true; in this case it returns "No hotels available" if none found, or a list of these hotels if found. If the database query fails, it will by default return null, and then return "No hotels found".
I am sorry for changing the code layout a little bit, feel free to edit it back as you like, that's up to you. I highly recommend proper formatting however (might have been because of your code editor as well).
index.php
<?php
$language = "en";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hotel Selection</title>
</head>
<body>
<select id="hotelselection">
<option value="null">No hotels available</option>
</select>
<script>
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("hotelselection").innerHTML = xmlhttp.responseText;
}
}
if (typeof(str) == "undefined" || str == null) {
str = "";
}
xmlhttp.open("GET", "run.php?location=" + str + "&language=<?php echo($language); ?>", true);
xmlhttp.send();
}
selecthotel();
</script>
</body>
</html>
run.php
<?php
$phrases = array(
"en_error_db" => "No hotels available...",
"en_choose_hotel" => "Choose a hotel..."
);
$link_id = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno($link_id)) {
die("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
error_log("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
exit(1);
}
$language_raw = isset($_GET["language"]) ? $_GET["language"] : "en";
$location_raw = isset($_GET['location']) ? $_GET["location"] : "";
$language = preg_replace("/[^\w.-]/", "", $language_raw);
$location = preg_replace("/[^\w.-]/", "", $location_raw);
if (empty($location)) {
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' ORDER BY `appearance` ASC";
}else{
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' AND `short_description` = ? ORDER BY `appearance` ASC";
}
if ($stmt = mysqli_prepare($link_id, $query)) {
if (!empty($location)) {
mysqli_stmt_bind_param($stmt, "s", $location);
}
mysqli_stmt_execute($stmt);
// Thanks to Bruce Martin on php.net for the SELECT * via _fetch (http://www.php.net/manual/en/mysqli-stmt.fetch.php#107034)
$metaResults = mysqli_stmt_result_metadata($stmt);
$fields = mysqli_fetch_fields($metaResults);
$statementParams = "";
foreach ($fields as $field) {
$statementParams .= (empty($statementParams) ? "\$column['" . $field->name . "']" : ", \$column['" . $field->name . "']");
}
$statment = "\$stmt->bind_result($statementParams);";
eval($statment);
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_choose_hotel"] . '</option>');
while (mysqli_stmt_fetch($stmt)) {
print('<option value="' . $column['appearance'] . '">' . $column['title'] . '</option>');
}
exit(1);
}else{
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_error_db"] . '</option>');
error_log("The script was unable to prepare a MySQLi statement (" . $query . ").");
exit(1);
}
?>
I switched over to MySQLi database extension instead of your deprecated MySQL extension. It should no longer return PHP errors over PHP error logs. I highly recommend switching to MySQL PDO if just possible. It's very simple, easy and works a lot better in my opinion!
Also, a note on your XMLHttpRequest/ActiveXObject usage: if you want to be able to support IE 5, create a class for that and load the script if the client is using that browser, otherwise use jQuery Ajax, which is very easy to use and you will not need to worry about query strings or so. The reason for having the ActiveXObject script out there, is because jQuery is not supported on IE 5, which is a common browser despite the known security issues. IE 5 is used by old computers, some banks, offices and other businesses that have not looked into the security details.
Hopefully this helped you.
Ajax-requests are cached in Internet Explorer. Try to delete the cache and then add a random parameter to the request-URL:
var url = "http://example.com/ajax.php?random="+new Date().getTime();
You shouldn't reinvent the wheel, there are some mature cross-browsers solutions out there already.
You should try using jQuery library and it's ajax method.
https://api.jquery.com/jQuery.ajax/
If you don't want to use a library you can find some solutions to your problem already, it involves creating different types of objects for IE:
http://www.quirksmode.org/js/xmlhttp.html
Internet Explorer caches content a lot, so you might need to force it to grab new data instead of taking it from the cache. You can add a GET parameter with a timestamp which is generated client side to the URL to which you're pointing.
In jQuery you can simply do it like this:
jQuery.ajax({
type: "GET",
url: "http://example.com/",
cache: false,
success: function (data) {
// do something here
}
});
Without jQuery you would need to add it manually to the url:
var url = "http://example.com" + "?_=" + (newDate()).getTime();