Jquery only working with source code? - javascript

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);
});

Related

How to execute JavaScript in PHP file executed from Ajax

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;
}

Set the value/text of a div using javascript/jquery - inside a php LOOP

I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.
Objectives:
Retrieve data from database.
Set the value of an element using javascript/jquery (inside a loop) from the database.
Make the value a link
I have this a_link column from links table with the ff. values:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
And here is my code:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
<?php
}
?>
Any help would be highly appreciated. Thanks.
#aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
I think you're trying to:
display a <div> of class 'row'
with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
The href for the tag must always have a scheme (http://).
Just PHP and HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("#((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php }
}
?>
This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.
Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so:preg_match("#^((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);)
A (better|different) solution could use parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php
}
?>
However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.
That's not how it works, that's not how any of this works
Now let's assume that you really need to use Javascript to process your generated links (which is not).
You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.
I guess you just want some kind of working code
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink)) :
$link = $rowlink['a_link'];
?>
<div class="row">
</div>
<?php
endwhile;
?>
<script type="text/javascript">
$(function() {
$('.row a').each(function() {
var urlified = urlify($(this).data('url'));
$(this).attr('href', urlified.url)
.text(urlified.label);
});
});
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var label = (c == 'www.') ? 'http://' +url : url;
return {url: url, label: label};
});
}
</script>
First i want to advice that use PDO or mysqli instead of mysql. as it
is vulnerable to sql injection and its depreciated.
"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."
for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.
below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
echo '<div class = "row">
<span id = "linkhere">
</span>
</div>';
}
?>
<script>
$("#linkhere a").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
You can implement this using php with parse_url function (http://php.net/manual/en/function.parse-url.php) to get different components.
In parse_url, there is 'scheme' key for http or https.
Then to do this with php, just call formatUrl function to make the url
<?php
function formatUrl($url)
{
$urlData = parse_url($url);
if(!isset($urlData['scheme'])) {
$url = 'http://' . $url;
}
return '' . $url . '';
}
?>
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id="linkhere"><?php echo formatUrl($thelink)?></span>
</div>
<?php
}
?>

InnerHTML creation issue, doesn't load in the correct order, possible processing issue

I am using a series of JavaScript functions to load information from a database and use the information in the creation of a thumbnail image and a radio button corresponding to each 'comic' record that the user has theoretically created and uploaded to the database.
My problem arises when the HTML tags are created. While the image and button are both created correctly with no errors, they are outputted in the wrong order. They should be loaded alphabetically by 'comicName', which is represented in the radio button's text, for example:
Comic A (img)
Comic B (img)
Comic C (img)
I have checked the array 'arr' of 'comicID's that determine the order of outputted html objects at several stages in the code using window alerts, and at all stages the comics are ordered correctly in the array, even when outputting incorrectly. There is an odd circumstance when I have quite a lot of alerts opening up at once; the items DO in fact output in the correct order. (In this case there were around six 'comicID's in the array and each ID had an alert pop up for it at three different times).
I therefore think that the code is creating them in the correct order and trying to output them as such, but some items may be loading sooner than others due to image size or some other processing reason. If this is indeed the case how would I go about sorting it to make sure they load correctly?
Thanks in advance.
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
document.getElementById("uploadTagID").innerHTML="";
document.getElementById("uploadTagID").innerHTML="No Comics Uploaded";
document.getElementById("btnDeleteComic").disabled=true;
document.getElementById("btnEditComic").disabled=true;
document.getElementById("btnDelAllComics").disabled=true;
$("#listButtons").hide();
}
else
{
document.getElementById("loadList").innerHTML="<br>";
for(i = 0; i < arr.length; i++)
{
tempID = (arr[i].comicID);
getCoverJSON(arr, i, tempID);
}
document.getElementById("uploadTagID").innerHTML="";
document.getElementById("uploadTagID").innerHTML="<u>Uploaded Comics</u>";
document.getElementById("btnDeleteComic").disabled=false;
document.getElementById("btnEditComic").disabled=false;
document.getElementById("btnDelAllComics").disabled=false;
$("#listButtons").show();
}
}
</script>
<script>
// Function to prevent $.get from technically being inside a loop (fixes an issue when loading more than one item).
function getCoverJSON(arr, i, tempID)
{
$.get("getCover.php", {'comicID': tempID}, function(result)
{
getCover(result, arr, i);
}
);
}
</script>
<script>
// Function to create a list of radio buttons and associated images from a user's comic list.
function getCover(result, arr, i)
{
var buildLine = document.getElementById("loadList").innerHTML;
if (result[0].pageLocation == "nocvr")
{
var out = "<hr><br><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='assets/img/nocvr.jpg'><br><br>";
document.getElementById("loadList").innerHTML="";
document.getElementById("loadList").innerHTML=(buildLine + out);
}
else
{
var getImg = result[0].pageLocation;
var out = "<hr><br><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + getImg + "'><br><br>";
document.getElementById("loadList").innerHTML="";
document.getElementById("loadList").innerHTML=(buildLine + out);
}
}
</script>
PHP (loadCom.php):
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$user = $_GET['userID'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE userID = '$user' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[")
{
$outp .= ",";
}
$outp .= '{"comicID":"' . $rs["comicID"] . '",';
$outp .= '"comicName":"' . $rs["comicName"] . '"}';
}
$outp .="]";
$conn->close();
echo ($outp);
?>
PHP (getCover.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if (isset($_GET["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_GET["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0)
{
$outp = '[{"pageLocation":"nocvr"}]';
echo ($outp);
}
else
{
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[")
{
$outp .= ",";
}
$outp .= '{"pageLocation":"' . $rs["pageLocation"] . '"}';
}
$outp .="]";
$conn->close();
echo ($outp);
}
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
You're using AJAX calls, which are by default asynchronous - there is NO guarantee whatsoever as to what order the responses come back in. e.g. if you have requests A,B,C, then the response to A might come 20 minutes after the C response, because someone's backhoe severed an optic cable somewhere and caused the A request to take a much longer path to the server than C's.
You can switch to synchronous, but that will lock the browser while the requests are pending, which is a bad user experience.
You'd be better off simplifying the code. Instead of doing one ajax call per fetch, you should have ONE call, and send over all of the ids you want to fetch.
In other words, instead of
$.get('getCover.php', {id:1});
$.get('getCover.php', {id:2});
$.get('getCover.php', {id:3});
switch your code over to
$.get('getCover.php', {ids:[1,2,3]});
Now it's one single ajax request, one single json response, and within that response, you can order your data however you want.

Ajax not working on IE

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();

PHP to Jquery through json ruins array

I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]

Categories

Resources