How to get onclick to display contents of php file - javascript

I am having a problem getting an onclick function to work.
Clicking on "units" in the HTML file, "unit_test" disappears and the contents of unit_display.php shows up instead. This is what I want to happen.
If I click on "Phoenix", however, "prop_test" remains and the results of prop_display.php do not appear.
I can browse to prop_display.php?city=Phoenix and it will pull up the list of properties from that table, so this rules out prop_display.php code as the culprit.
Here is my html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script>
function showProp(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("propDisplay").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","prop_display.php?city="+str,true);
xmlhttp.send();
}
function showUnit(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("unitDisplay").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","unit_display.php?prop_id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div onclick="showProp(Phoenix)">Properties</div>
<div onclick="showUnit(8)">units</div>
<br>
<div id="propDisplay">prop_test</div>
<div id="unitDisplay">unit_test</div>
</body>
</html>
Here is prop_display.php:
<?php
include('vars.php');
$city = strval($_GET['city']);
print $city;
if (!$link) {
die('Could not connect: ' . mysqli_error($con));
}
if ($prop_query = mysqli_query($link, "SELECT * FROM property WHERE city='$city' ORDER BY street asc")){}
while ($prop_array = mysqli_fetch_array($prop_query, MYSQLI_BOTH)){
$prop_id=$prop_array['prop_id'];
print " <li><div onclick=\"showUnit($prop_id)\"><a href=\"#\">" . $prop_array['name'] . "<br>
" . $prop_array['street'] . "</a></div>
";
}
mysqli_close($link);
?>
And here is unit_display.php:
<?php
include('vars.php');
$prop_id = intval($_GET['prop_id']);
print $prop_id;
if (!$link) {
die('Could not connect: ' . mysqli_error($con));
}
if ($unit_query = mysqli_query($link, "SELECT * FROM units WHERE prop_id='$prop_id' ORDER BY unit asc")){}
while ($unit_array = mysqli_fetch_array($unit_query, MYSQLI_BOTH)){
print " <li>" . $unit_array['unit'] . "</li>
";
}
mysqli_close($link);
?>

It seems like you are trying to have them click with Phoenix being an object when it should be a string.
Replace this:
<div onclick="showProp(Phoenix)">Properties</div>
with this:
<div onclick="showProp('Phoenix')">Properties</div>

Related

Multiple XMLHttpRequest in one page

I have a situation where I am making the following requests and for some reason only one of them is working?
The expected result is that the second div which is populated by filter2 will bring in the necessary information, however this is not working even though this is following the same logic as filter 1?
The code for the actual requests is here:
Request 1:
function show1(str) {
if (str == "") {
document.getElementById("id1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter1.php?q=" + str, true);
xmlhttp.send();
}
Request 2:
function show2(str) {
if (str == "") {
document.getElementById("id2").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id2").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter2.php?p=" + str, true);
xmlhttp.send();
}
The php code is as follows for both of the requests is as follows:
Filter1:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$q = strval($_GET['q']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE type = '".$q."'";
$result = mysqli_query($mysqli,$search);
echo "<ul id=\"list\">";
while($row = mysqli_fetch_array($result)) {
echo "<li>";
echo "<a class=\"class\">" . $row['column'] . "</a>";
echo "<a class=\"class\"><strong>" . $row['column'] . "</strong></a>";
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(this.value)\" value=\"" . $row['column'] . "\" class=\"class\"></button>";
echo "</li>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
Filter2:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$p = strval($_GET['p']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE name = '".$p."'";
$result = mysqli_query($mysqli,$search);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr id=\"id\"><td><strong>" . $row['column'] . "</strong></td></tr>";
echo "<tr id=\"id\"><td>TestContact</td></tr>";
echo "<tr id=\"id\"><td>" . $row['column'] . "</td></tr>";
echo "<tr id=\"id\"><td>Website ></td></tr>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
I am not sure if this is a common mistake or I have some kind of clash/stupid syntax error, but this is driving me crazy and I would be forever grateful for anyone to help?
Like I said in a comment ( and was also stated in the 1st comment by #jcubic ) an img element doesn't have a value attribute which is, I suspect, the reason your function is passing undefined
Instead you can use a dataset attribute and alter the parameter passed to the inline function / event handler:
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(event)\" data-value=\"" . $row['column'] . "\" class=\"class\"></button>";
and the javascript function
/* passing event allows access to event.target amongst other things - this is useful */
function show2( e ){
var el=e.target;
var str=el.dataset.value;
if( str )/* etc */
}
that said you'd be much better creating a generic ajax function ( or better yet look into the fetch api ) and write wrapper functions for each use case.

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

Retrieving large data amount as datalist from Remote PC

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.

How to refresh data in table using ajax?

I'm new to ajax. I just want to simply view my table from the database using ajax. I have 2 files listbarang.html and showlist.php.
Here's my code
PHP (showlist.php)
<?php
$link = #mysqli_connect("localhost", "root", "","projekpweb");
if($link->connect_errno)
{
echo "Failed to connect. " . $link->connect_error;
}
$sql = "SELECT * FROM `barang`";
$result = mysqli_query($link, $sql);
if(!$result)
{
die("SQL GAK KONEK : " . mysqli_error($link));
}
echo "<table>
<tr>
<th>idbarang</th>
<th>nama</th>
<th>harga</th>
<th>ekstensi_gambar</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo " <tr>
<td>".$row["idbarang"]."</td>
<td>".$row["nama"]."</td>
<td>".$row["harga"]."</td>
<td>".$row["ekstensi_gambar"]."</td>
</tr>";
}
echo "</table>"; ?>
HTML (listbarang.html)
<!DOCTYPE html>
<html>
<head>
<title>LIST BARANG</title>
<script type="text/javascript">
function showList()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("tblList").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","showlist.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="tblList">
<script type="text/javascript">
showlist();
</script>
</div>
</body>
</html>
I wonder why the #tblList doesnt have the content of the the table.
Thanks in advance

Redirection in an ajax called page

I have read quite a bit and I still am missing something.
I have a page that has a button on it. When you click the button it will call an AJAX function that will then wait and refresh every 5 seconds in waiting for a MySQL database change. Once the change in the database is made, I would like to take the user to a new page all together.
I have tested the refreshing for the database changes and they work great with echos. I have tried to use windows.location and the php header redirect. Neither are working.
I am not using jquery for the ajax call. Any help would be greatly appreciated.
Thank you
code:
index.php
<?php
session_start();
$_SESSION = array(
'player' => 0
);
?>
<!DOCTYPE HTML>
<html>
<head>
<script src="ajax.js"></script>
<title></title>
</head>
<body>
<div id="join"><button type="button" onclick="startGame()">Throwdown!</button></div>
</body>
</html>
rpsjoin.php
<?php
include("db.php");
session_start();
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$gameStatus_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT game.game_status FROM game WHERE game.id =' . $lastId));
$gameStatus = $gameStatus_q['game_status'];
if ($gameStatus == 2) {
mysqli_query($con, "INSERT INTO game (game_status, player1_joined) VALUES(1,1)");
$_SESSION['player'] = '1';
$playerNumber = $_SESSION['player'];
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$_SESSION['lastId'] = $lastId;
} elseif ($gameStatus == 1 && $_SESSION['player'] != 1) {
mysqli_query($con, "UPDATE game SET player2_joined = 1 WHERE id = " . $lastId);
$_SESSION['player'] = '2';
$playerNumber = $_SESSION['player'];
$_SESSION['lastId'] = $lastId;
}
$player1_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player1_joined FROM game WHERE game.id =' . $lastId));
$player2_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player2_joined FROM game WHERE game.id =' . $lastId));
$player1_join = $player1_join_q['player1_joined'];
$player2_join = $player2_join_q['player2_joined'];
echo $lastId . "<BR>";
echo $gameStatus . "<BR>";
echo $player1_join . "<BR>";
echo $player2_join . "<BR>";
if ($player1_join == 1 && $player1_join == $player2_join) {
echo '<form action="rpsover.php" method="post">
<button type="submit" name="player" value="1">Rock</button>
<button type="submit" name="player" value="2">Paper</button>
<button type="submit" name="player" value="3">Scissors</button>
</form>';
} else {
echo "Locating player. Please be patient";
}
echo session_id();
?>
function startGame() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("join").innerHTML=xmlhttp.responseText;
setTimeout('startGame()',1000);
}
}
xmlhttp.open("GET","rpsjoin.php",true);
xmlhttp.send();
}
At the end of rpsjoin.php, instead of showing a form, i want to be redirected to another page.
Yes I know my code is bad and there are test echos in it.
Thank you

Categories

Resources