I posted this earlier but it incorrectly got marked as a duplicate of Can scripts be inserted with innerHTML?, which isn't my problem. I'm not trying to run any JavaScript through using innerHTML, I'm trying to run JavaScript that is located in a PHP file called through Ajax/XmlHttp. I am using innerHTML in that JS, but I'm not writing more JS within that. So it's not a duplicate of that question and I'm trying it again now.
Not sure what's going on here. I'll explain the organization of my files first and then get into the code.
The application- Allows the user to select different attributes (i.e. year or name) and view pictures of matching results from a database.
Files- I have a gallery.php file that has a series of HTML form elements acting as selectors to get filtered results from a database. Whenever a selector is set or changed, the file sends a new request to a get.php file that uses Ajax to refresh the results without loading a new page. All that works great. My next task is to implement a modal section where I can click on an image and view a bigger version which I plan to do with JavaScript and CSS, but my intermediate goal is to just change some text at the bottom of the results from get.php again using JavaScript, just as a first step. But I can't seem to get any JavaScript written in get.php to fire.
Code-
This is gallery.php:
<?php
include_once("./../php/navbar.php");
?>
<html>
<head>
<link href="/css/siteTheme.css" rel="stylesheet">
<style>
.attributes span {
margin-right: 1rem;
}
</style>
<script>
function changeParams() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
}
};
year = document.getElementById("years_select").value;
nameFirst= document.getElementById("nameFirst_select").value;
/* Ton of other getElementById statements here that I'm excluding to keep things shorter */
url = "get.php?year="+year+......;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} /* End function */
</script>
</head>
<body>
<div class="content">
<h1>Gallery</h1>
<form>Details:
<!-- -------------------- Year -------------------- -->
<select onchange="changeParams()" name="years" id="years_select">
<option value="All">Year</option>
<?php
include("/var/www/admin.php");
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = "select year from db group by year order by year desc";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value=" . $row['year'] . ">" . $row['year'] . "</option>";
}
mysqli_close($conn);
?>
</select>
<!-- A bunch of other selectors are created here following the same pattern as above of getting results from a DB -->
<!-- -------------------- Searchbar -------------------- -->
<input type="text" size="50" onkeyup="changeParams()" name="search" id="search" placeholder="Search"></input>
</form>
<div id="test">Choose some filters to see some results!</div>
</form>
</div> <!-- Ends content div -->
</body>
</html>
This is get.php:
<html>
<head>
<style>
/* Bunch of CSS that's not relevant here */
</style>
<script type="text/javascript">
console.log(".....");
var parts = document.querySelectorAll("div.imgContainer");
console.log("Found something:", parts);
parts.addEventListener("click", function(){
document.getElementById("anID").innerHTML = "Test...";
});
</script>
</head>
<body>
<?php
include("/var/www/admin.php");
$year = $_GET['year'];
//Bunch of other variables set here following the same logic, getting data from gallery.php
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
echo '$conn';
}
$sql = 'select * db';
/* ---------- Creating SQL statement ---------- */
$clauses = 0;
if ($year != "All") {
if ($clauses == 0) {
$sql = $sql . ' where year = "' . $year . '" and';
$clauses = $clauses + 1;
} else {
$sql = $sql . ' year = "' . $year . '" and';
}
} /* Bunch of other if statements to get set information and add to sql statement as such */
// Need to chop of the last ' and' from the sql statement
$sql = substr($sql, 0, -4);
$sql = $sql . ' order by year desc';
$result = mysqli_query($conn, $sql);
$num_results = mysqli_num_rows($result);
if ($num_results == 0 or $clauses == 0) {
echo "<p>No matches to your query. Try refining your search terms to get some results.</p>";
} else {
echo "<p>" . $num_results . " results matched your query.</p>";
echo "<div class=results>";
//echo "<div>";
echo '<script type="text/javascript">
function modalFunction() {
document.getElementById("anID").innerHTML = "test";
}
</script>';
while ($row = mysqli_fetch_array($result)) {
$pic = $row['pathToPic'];
$wwwImg = substr($pic, 13);
//echo "<span id=aCard><img src=" . $wwwImg . " height ='250px'>";
//echo "<span class=text>" . $row['fullCardInfo'] . "</span></span>";
echo "<div class=fullContainer><div class='imgContainer'><img class=image src=" . $wwwImg ."></div><p class=text>" . $row['fullInfo'] . "</p></div>";
} // End while of results
echo "</div>";// End results div//</div>";
//echo '<div class="modal"><p id="anID"></p></div>';
} // End else of "if results"
mysqli_close($conn);
?>
<script>
</script>
<div>
<p id="anID">This in a div</p>
</div>
<!--<span>
<p id="anID">This in a span</p>
</span>-->
</body>
</html>
Sorry if that was messy, I chopped out a bunch of stuff that just gets/selects/filters some data. All that works and all variables that are left in there are set in my full code.
But the issue I'm having is writing JavaScript in get.php to change the text in the <p id="anID"> tags. I've tried JS in a few different areas of get.php, from in the <head> tags, to echoing it in <script> tags in the PHP, to pure <script> tags after the PHP statements are done (I think I left them in a few different places).
Problem is that nothing I do works to change the text in the <p> tags I references. Additionally, the console.log statements in the header of get.php don't seem to get called either. They don't fire no matter where I place them in get.php. Console.log works fine in gallery.php so it's not some issue with my browser or anything.
Long term, I will be adding JS query selectors to bring up a bigger image when an image is clicked on, but for now I'm just trying to make ANY JavaScript work in get.php and I'm struggling to do so. I don't see how this is a duplicate of the suggested repeat as I'm not trying to run JavaScript through innerHTML here.
Scratch that, it actually is trying to pass JavaScript through innerHTML as the information from get.php comes from this section of gallery.php:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
console.log("Response: ", this.responseText);
}
So it appears this is a duplicate of the question I linked after all. Apologies. However, there are not great answers to that question, so any tips would be appreciated.
This line:
document.getElementById("test").innerHTML = this.responseText;
Is simply going to add the contents of this.responseText to the element test. I'm sure you understand that much, but what you want to do is completely wrong. The scripts within the output of get.php will NOT be executed at all and you have corrupted your HTML as well by including a second <html><head> and more.
A better approach would be if get.php returned the data from you DB query as a JSON string like so:
$data;
while ($row = mysqli_fetch_array($result)) {
$data[]['pic'] = $row['pathToPic'];
$data[]['wwwImg'] = substr($row['pathToPic'], 13);
}
echo json_encode($data);
exit;
And then back on gallery.php you do something like:
if (this.readyState == 4 && this.status == 200) {
formatResult(this.responseText);
}
// ... snip ...
function confirmJson(str) {
var j = null;
if (str) {
try { j = JSON.parse(str); }
catch (e) { j = null; }
}
return j;
}
function formatResult(str) {
var data = confirmJson(str);
if (! data) {
console.log("result is not JSON");
return;
}
// do stuff with the data
var i, max = data.length;
var h = document.createElement("div");
var img;
for(i=0;i<max;i++) {
img = document.createElement("src");
img.src = data[i].wwwImg;
img.addEventListener("click",function(){ alert("pic:["+ data[i].pic +"]"); },true);
h.appendChild(img);
}
document.getElementById("test").innerHTML = h;
}
Related
My site pulls test questions from a database, and some of these questions have images associated with them.
The images pull in fine and everything works as expected, but when trying to pull the answers for these questions, which sometimes also have images, there is a translation issue causing just the reference index to be called and no image displayed (the text still appears that is associated with the answer however).
Question Picture Example
Answer Picture Example - An image should appear in the highlighted area
I can't tell if the issue is caused in the HTML/PHP interpretation of calling an answer or in the function that defines the answer to be called. Code snippets below.
First is the HTML/PHP and JS. All things pertaining to answers are "Rationale" All things pertaining to images are "equations":
<?php
for ($i = 0; $i < $displayCount; $i++) {
$workingDate = date('Y-m-d', time()-($i*24*60*60));
$QID = updateQOTD($ar, $workingDate, $level);
$questionInfo = getQuestion($ar, $QID);
echo $workingDate."<br><br>";
if(isset($questionInfo->VIGNETTE)) {
echo "<strong>Vignette</strong>:<br>";
echo $questionInfo->VIGNETTE;
echo "<br><br>";
}
$equation = getEquation($ar, $QID);
$eq_text = '';
if (isset($equation)) {
$file = $equation->FILE_NAME;
$eq_text = '<img src="/lcms/images/equations/' . $file . '">';
}
echo "<strong>Question</strong>:<br><br>";
$qtext = $questionInfo->TEXT ;
$qtext = preg_replace('/<equation id="\d+"\/>/', $eq_text, $qtext);
echo $qtext;
echo "<br><br>";
?>
<div id='response_<?php echo $i; ?>'></div>
<div class='rationale margin-top-20'><br><strong>Rationale:</strong><br>
<?php echo $questionInfo->RATIONALE; ?>
</div>
<?php
}
?>
<button id="grade" class="btn-theme" type="button">Grade My Choices</button>
<? require_once(getenv("DOCUMENT_ROOT")."/inc/footer.pilot.php"); ?>
<script type="text/javascript">
$(document).ready(function(){
$(".rationale").hide();
$("response_1").hide();
$("response_2").hide();
$("response_3").hide();
$("response_4").hide();
$("response_5").hide();
$("#grade").click(function () {
$(".correctMark").html("<img src='../../images/600px-Green_check.png' />");
$(".incorrectMark").html("<img src='../../images/600px-Red_x.png' />");
$(".rationale").slideDown("fast");
if ($("input[name='question_1']:checked").val() == 'correct') {
$("#response_1").text("Your answer was correct!");
$("#response_1").slideDown("slow");
}
});
});
</script>
And here is the database code call SQL and function defining Rationale:
function getEquation($ar, $QID) {
if (isset($QID) && $QID > 0) {
$selectSql = sprintf("SELECT e.FILE_NAME FROM equation_tbl e, equation_question_link_tbl eq WHERE eq.QUESTION_ID = %s AND e.ID = eq.EQUATION_ID ",
$QID);
$equation = $ar->get_row($selectSql);
return $equation;
}
}
function getQuestion($ar, $QID) {
$selectSql = sprintf("SELECT case_tbl.TEXT as VIGNETTE, question_tbl.TEXT, question_tbl.ANSWER_1, question_tbl.ANSWER_2, question_tbl.ANSWER_3, question_tbl.ANSWER_4, question_tbl.ANSWER_5, question_tbl.ANSWER_6, question_tbl.ANSWER_7, question_tbl.ANSWER_8, question_tbl.RATIONALE FROM question_tbl LEFT JOIN case_tbl ON question_tbl.CASE_ID = case_tbl.ID WHERE question_tbl.ID = %s",
$QID);
$question = $ar->get_row($selectSql);
return $question;
}
function makeAnswerArray($questionInfo) {
$answers[0] = array($questionInfo->ANSWER_1, 'correct');
$answers[1] = array($questionInfo->ANSWER_2, 'incorrect');
$answers[2] = array($questionInfo->ANSWER_3, 'incorrect');
if(isset($questionInfo->ANSWER_4) && $questionInfo->ANSWER_4 > ' ') {
$answers[3] = array($questionInfo->ANSWER_4, 'incorrect');
if(isset($questionInfo->ANSWER_5) && $questionInfo->ANSWER_5 > ' ') {
$answers[4] = array($questionInfo->ANSWER_5, 'incorrect');
if(isset($questionInfo->ANSWER_6) && $questionInfo->ANSWER_6 > ' ') {
$answers[5] = array($questionInfo->ANSWER_6, 'incorrect');
if(isset($questionInfo->ANSWER_7) && $questionInfo->ANSWER_7 > ' ') {
$answers[6] = array($questionInfo->ANSWER_7, 'incorrect');
if(isset($questionInfo->ANSWER_8) && $questionInfo->ANSWER_8 > ' ') {
$answers[7] = array($questionInfo->ANSWER_8, 'incorrect');
}
}
}
}
}
return $answers;
}
Is there any reason why the images associated with Rationales are not pulling through when expected?
I would start by checking the values of $equation with var_dump($equation) and also var_dump($question) to look for any anomalies. I suspect you've got incomplete data creeping in that looks like /lcms/images/equations/NULL or something similar which should be obvious enough, when dumped.
If this is the case, look at extending your handling of these vars to be more strict about the expected value.
Truth be told, it's going to be difficult to help if we cannot run the code. But I would start by checking data integrity of the MySQL result. Bit of a SQL join in there too that only you will know the correct format of, which would be my next port of call.
I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.
I want to create a box to display the data from the event source using css.
For example,
In this picture, i want to create a box to load data from the php script. the new data appear at the top. i want to see new data at the top.As new data is being updated, the old data goes down and you cant see old data after 4 rows. I use css to achieve it. I use overflow to hide the the old data. Instead new data are at the bottom. Please help me. thank you.
my code is found below
php script
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "netwitness";
$dbname = "abdpractice";
$con = mysqli_connect ($dbhost, $dbusername, $dbpassword) or die ('Error in connecting: ' . mysqli_error($con));
//Select the particular database and link to the connection
$db_selected = mysqli_select_db($con, $dbname ) or die('Select dbase error '. mysqli_error());
//Make A SQL Query and link to the connection
$result = mysqli_query($con,"SELECT * FROM `countryattack` ORDER BY RAND() LIMIT 1");
while ($row = mysqli_fetch_assoc($result))
{
echo "data: [X] NEW ATTACK: FROM " . $row["countrysrc"]. " TO " . $row["countrydst"]. " \n\n";
}
mysqli_close($con);
?>
html code
<!DOCTYPE html>
<html>
<head>
<style>
div.hidden {
background-color: #00FF00;
width: 500px;
height: 100px;
overflow: hidden;
}
</style>
</head>
<body>
<h1>Getting server updates</h1>
<div class="hidden" id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("shownewattack.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
My output is like this
The output is that they show data at the bottom. This is not what I want.. Any ideas on how to do that..
My question is how to create a box to observe the data. As the script is being updated, the old data goes down. after the fourth row you cant see anything.new data will appear the top. Can you please help me. thank you..
You can substitute using Node.insertBefore() for concatenating .innerHTML of parent element.
const result = document.getElementById("result");
source.onmessage = function(event) {
const node = document.createTextNode(event.data + "\n");
if (!result.firstChild) {
result.appendChild(node);
else {
result.insertBefore(node, result.firstChild);
}
};
<pre id="result"></pre>
<script>
const result = document.getElementById("result");
let n = 0;
const interval = setInterval(() => {
let node = document.createTextNode(++n + "\n");
if (!result.firstChild) {
result.appendChild(node);
} else {
result.insertBefore(node, result.firstChild)
}
}, 500);
</script>
make sure u sort your query using DESC or ASC in order to make them arrive accordingly. that sure solve the problem.
$result = mysqli_query($con,"SELECT * FROM `countryattack` ORDER BY createdDate LIMIT 4");
while ($row = mysqli_fetch_assoc($result))
{
echo "data: [X] NEW ATTACK: FROM " . $row["countrysrc"]. " TO " . $row["countrydst"]. "";
}
echo "data: [X] NEW ATTACK: FROM " . $row["countrysrc"]. " TO " . $row["countrydst"]. "<br>";
That should do what you are looking for. Just add a createdDate into you Database when the row is added to the table and then order the data by that. Then Limit the records to 4. Also if you want the data on a new line you could add a < br > to the end of your echo. Good luck.
I've got a html file, in which I am dynamically loading data using AJAX and PHP.
They are no big deal, as they work fine, but I still have got a Problem.
I have (for showing purposes) created two divs, which are showing literally the same in DOM, but one is also shown in the source code. (The one div is loaded dynamically, in the other one I've loaded the results already from the start.)
Like this:
<div>
<ul>
<!-- Here is some data which is shown correct -- >
<!-- (too much to REALLY put it in here -->
</ul>
</div>
<div id="result">
<!-- This should show the exact same output, but well isn't... -->
</div>
I've already looked after some similar things, but nothing helped me solve my Problem, as my request for the "result" is
function kommissionsakte(o, s) {
$("#result").empty();
var xmlHttp = {};
xmlHttp = ajaxHandler(xmlHttp);
// Wenn das Objekt erfolgreich erzeugt wurde
var url = "ajax/getKommissionsakten.php";
suchwert = escape($("#suchwert").val());
var params = "o=" + o + "&s=" + s + "&suchwert=" + suchwert;
if (suchwert != '') {
$("#suchwert").css("border-color", "#31ae1c");
loading();
xmlHttp.open("POST", url, true);
//Headerinformationen für den POST Request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
$("#result").html(xmlHttp.responseText);
closeLoading();
}
};
xmlHttp.send(params);
} else {
$("#suchwert").focus();
$("#suchwert").css("border-color", "#b20e10");
}
}
My idea was to somehow get #result not as div id but INTO the div, but I am bad, so I have no idea how.
EDIT: Okay Long Explanation:
I try to load a Filetree using jquery into a page, that is already loaded. The Code creating the tree is working fine, it just doesn't work when I try to load it into this page. I've read that jquery is using DOM and not source code, so it should work properly, but it doesn't.
I can search for a keyword in a search function and the file tree is showing them. In the manually created div, is the Code, which creates the tree and jquery is manipulating it properly, if I now load that exact same Code into the other div, jquery isn't manipulating it.
Also i Am REALLY (like REALLY REALLY bad at JS) so it would be very, very nice to have a long Explanation in the answer.
EDIT2:
Requested PHP File Code:
<?php
include '../include/ebene.inc.php';
include $ebene.'include/error_reporting.inc.php';
include $ebene.'include/db.inc.php';
include $ebene.'include/getSprache.inc.php';
include $ebene.'include/funktionen-standard.inc.php';
include $ebene.'include/funktionen-individuell.inc.php';
include $ebene.'include/konfig.inc.php';
if(isset($_POST['suchwert'])){
$suchwert =($_POST['suchwert']);
$php_file_tree = '';
$first_call = true;
$neue_seite = false;
if($suchwert != ''){
$parentsql = "SELECT TOP 10 KOM_Nummer from dbo.V_Kommisions_Akte_EN WHERE KOM_Nummer LIKE '%$suchwert%' group by KOM_Nummer";
$parameter = array();
$optionen = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$parent = sqlsrv_query($dbD3, $parentsql, $parameter, $optionen);
$parentanzahl = sqlsrv_num_rows($parent);
if($parentanzahl != 0){
$neue_seite = true;
if($anzahl >= 200){
echo '<br /><div align="center">'.$var['verfeinern'].'</div>';
}else{
echo '<br /><div align="center">'.$var['anzahl_ergebnisse'].': '.$parentanzahl.'</div>';
}
$php_file_tree .= "<ul";
if($first_call) {$php_file_tree .= " class=\"php-file-tree\""; $first_call = false;}
$php_file_tree .= ">";
while($komnr = sqlsrv_fetch_array($parent, SQLSRV_FETCH_ASSOC)) {
$php_file_tree .= "<li class=\"pft-directory\">" . htmlspecialchars($komnr['KOM_Nummer']) . "<ul>";
$komnrregister = $komnr['KOM_Nummer'];
$subsql = "SELECT TOP 10 KOM_Nummer, Register from dbo.V_Kommisions_Akte_EN where KOM_Nummer = '$komnrregister' group by KOM_Nummer, Register";
$parameter = array();
$optionen = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$sub = sqlsrv_query($dbD3, $subsql, $parameter, $optionen);
$subanzahl = sqlsrv_num_rows($sub);
while($register = sqlsrv_fetch_array($sub, SQLSRV_FETCH_ASSOC)) {
$php_file_tree .= "<li class=\"pft-directory\">" . htmlspecialchars($register['Register']) . "<ul>";
$registerdokuid = $register['Register'];
$slavesql = "SELECT TOP 10 KOM_Nummer, Register, doku_id from dbo.V_Kommisions_Akte_EN where Register = '$registerdokuid' AND KOM_Nummer = '$komnrregister' group by KOM_Nummer, Register, doku_id";
$parameter = array();
$optionen = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$slave = sqlsrv_query($dbD3, $slavesql, $parameter, $optionen);
$slaveanzahl = sqlsrv_num_rows($slave);
while($doku = sqlsrv_fetch_array($slave, SQLSRV_FETCH_ASSOC)) {
$php_file_tree .= "<li class=\"pft-file ext-xls\">" . htmlspecialchars($doku['doku_id']) . "</li>";
}
$php_file_tree .= '</ul></li>';
}
$php_file_tree .= '</ul>';
}
$php_file_tree .= '</ul>';
}
echo $php_file_tree;
//return ($php_file_tree);
}
}
?>
My answer needs some edits, but you should try something like this :
function getMyPage(pageUrl,someData,callback){
$.ajax({
type : 'POST',
url : pageUrl,
data : {'postName':someData},
error : function(response){
console.log("something wrong "+response+" - "+response.responseText+" - "+JSON.stringify(response));
},
success : function(response){
callback(response);
}
});
})
Then somewhere in your code :
$("body").on("click","#yourButton",getMyPage('http://anything','your data',function(back){
$("#yourDiv").html(back);
});
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();