I got a page where a table is supposed to reload when I click a link. The script works, and the variable is updated (I've tested that, see code), but the table doesn't reload with new data from the SQL query.
Page
<!-- SCRIPT START -->
<script type='text/javascript'>
function getResultat(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getResultat.php?klasse2="+str,true);
xmlhttp.send();
}
}
</script>
<!-- SCRIPT END -->
<!-- LINK -->
<a style="cursor:pointer" onclick='javascript:getResultat("KSenior")'> KSenior </a>
<!-- DATA get inserted here -->
<div id="txtHint"><?php include("getResultat.php"); ?></div><br>
getResultat.php
<?php
if(isset($_REQUEST['klasse2'])) {
$klasse2=$_REQUEST['klasse2'];
// Used to check if variable updates (for debuging only)
echo $klasse2;
$klasse2= $_REQUEST['klasse2'];
} else {
$klasse2="MSenior";
// Used to check if variable updates (for debuging only)
echo $klasse2;
}
$query = "SELECT DISTINCT *
FROM resultat
WHERE resultat.klasse = '$klasse2'
ORDER BY resultat.plassering ASC ";
// THIS SEND THE QUERY TO A CRUD
$selection= array("plassering", "navn","lagnavn", "tid_liten");
$records_per_page=5;
$newquery = $crud->paging($query,$records_per_page);
$crud->dataview($newquery, $selection, $records_per_page, $sesong, $bestetid['tid_ny']);
?>
I can post the CRUD if needed, but hopefully there is some common mistake I'm making?
When calling this page with a button the echo in the start reloads, but not the query.
Related
I am trying to create a ajax function to just reload a <div> and not the entire page.
What is working:
-during writing in the input field the div is reloaded after every character correctly.
What is not working:
-when the input field is complete empty again, it is not showing the whole entries I have in the database.
this is what I have in the php file where the div is:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").innerHTML = "";
return;
} else {
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("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
} }
this is what I have in the search.php
<?php
include 'test/database.php';
$pdo = Database::connect();
if($_GET['game'] == "") {
$sql="SELECT * FROM games WHERE active=1";
echo "<script type='text/javascript'>alert('Should be empty')</script>";
} else {
$q = $_GET['game'];
$sql="SELECT * FROM games WHERE gamenamelong LIKE '%".$q."%'";
}
$stmt = $pdo->prepare($sql);
$stmt->execute();
$gameResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowCount1 = count($gameResults);
Is anybody able to help me?
Thank you!
since we don't know how your form looks like, and what calls the function showGames how, I can only give a vague answer. But your main problem/misstake should be solved with that:
In your function showGames you never hit the ajax if the search string is empty, so you can't get back all results.
So I suggest to change that function like so:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").innerHTML = "";
//remove that: return;
}
// remove the 'else { '
// now you allways hit the ajax
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("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
// remove closing bracket of if-else: '}'
}
I am using "http://www.w3schools.com/Php/php_ajax_database.asp" for displaying data from database on onchange of dropdown list. I have a huge amount of data in database. So it's taking time to load. Hence I would like to display a loading message somewhere in the page until the data display.
Code:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
<form>
<select name="users" onChange="showUser(this.value)" style="margin-left: -680px;margin-top: -10px;">
<option value="1">Current Projects</option>
<option value="2">All Projects</option>
</select>
</form>
</div></div>
<div id="txtHint"> /*Content*/ </div>
getuser.php:
Database queries to display data.
In my opinion it is easier to juse a javascribt library/framework like JQuery for Ajax requests or plain everything javascript. If you want to do it the old school way, that this should be able to help you out:
if(obj.readyState == 0)
{
document.getElementById('copy').innerHTML = "Sending Request...";
}
if(obj.readyState == 1)
{
document.getElementById('copy').innerHTML = "Loading Response...";
}
if(obj.readyState == 2)
{
document.getElementById('copy').innerHTML = "Response Loaded...";
}
if(obj.readyState == 3)
{
document.getElementById('copy').innerHTML = "Response Ready...";
}
if(obj.readyState == 4)
{
if(obj.status == 200)
{
return true;
}
else if(obj.status == 404)
{
// Add a custom message or redirect the user to another page
document.getElementById('copy').innerHTML = "File not found";
}
else
{
document.getElementById('copy').innerHTML = "There was a problem retrieving the XML.";
}
}
It's pretty easy actually, just put the message / image you want in the div, like that :
<div id="txtHint"> Loading... </div>
And when the data is loaded and JS :
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
This will empty the div and replace with the Ajax content.
Actually, I think your code is already working.
Following dropdown:
<select id='dropdown' name='dropdown' onchange='showChart(this.value)'>
<option value="1">Foo</value>
<option value="2">Bar</value>
</select>
Calls this javascript function onchange:
<script type="text/javascript">
function showChart(str1) {
if (str1 == "") {
document.getElementById("chartContainer").innerHTML = "";
return;
}
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("chartContainer").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "../ajaxpage/chart.php?charttype=" + str1);
xmlhttp.send();
}
</script>
chart.php?charttype looks like this:
<?php
$charttype = $_GET['charttype'];
if ($charttype == "1") {
echo "<p>test1</p>";
echo "<script type='text/javascript'>
alert('test1');
</script>";
} else {
echo "<p>test2</p>";
echo "<script type='text/javascript'>
$(document).ready(function() {
alert('test2');
});
</script>";
}
?>
Everything seems to work. The test1 and test2 in paragraph tags are rendered correctly in the graphContainer div onchange of the dropdown. However, the javascript is not executing. How come generated javascript does not execute, and how do I fix this?
Thanks.
EDIT
Here is the extremely foul (but working) workaround:
<img src="../images/loaded.gif" alt=""
onload="Code To Execute Here;this.parentNode.removeChild(this);" />
JavaScript is not evaluated with innerHTML.
I have implemented a dynamic creation of a HTML table using AJAX.
Here's what I've created:
index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="ContactController.js">
</script>
</head>
<body>
<div class="main-wrapper">
<div id="menu">
<a href="javascript:void(0)" onclick="getAllContacts()">
Go to contacts
</a>
</div>
<div id="main-content">
</div>
</div>
</body>
</html>
ContactsController.js
function getAllContacts() {
// Manage new XmlHttpObject creation
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.send(null);
}
function stateChanged() {
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
document.getElementById("main-content").innerHTML = xmlHttp.responseText;
}
}
// Creates a new XmlHttpObject
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// XmlHttpObject constructor for Chrome, Firefox, Opera, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v6.0
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v5.5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
getAllContacts.php
<?php
include 'connectToMySQL.php';
$command = "SELECT * FROM contact";
$result = mysql_query($command);
echo "<table id='contactsTable' border='1'>";
// Table headers
echo "<tr>
<th>Name</th>
</tr>";
// Print all contacts
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='#'
onclick=\"getContact('" . $row['DisplayName'] . "')\">"
. $row['DisplayName'] .
"</a>
</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
So, clicking on a Go to contacts link activates a getAllContacts javascript function. That function calls getAllContacts php function which retrieves the data from MySQL database and places it in the contactsTable table.
What I need is to tell the function to place that table in the main-content div located in the index.php page. How do I achieve this? Thanks.
ok, so going from your comment about wanting two different possible target divs, just define your onreadystatechanged event inline and use a local variable to refer to the div...
function getAllContacts() {
// Manage new XmlHttpObject creation
var xmlHttp = GetXmlHttpObject(); // MAKE THIS LOCAL INSTEAD OF GLOBAL!
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
var targetDiv = document.getElementById(whateverIdYouWant);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = function(){
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
targetDiv.innerHTML = xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
Right now I'm struggling to get this simple PHP AJAX request to work.
<html>
<head>
<script type="text/javascript">
function getSuggestions(type){
if(type == "")
{
document.getElementById("entries").innerHTML="test"
return;
}
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("entries").innerHTML=xmlHttp.response;
}
}
xmlHttp.open("GET","getData.php?status="+type,true);
xmlHttp.send();
}
</script>
</head>
<body>
<div id="A" onclick='getSuggestions("A")'>Click for A</div>
<div id="P" onclick='getSuggestions("P")'>Click for P</div>
<div id="R" onclick='getSuggestions("R")'>Click for R</div>
<div id="entries"></div>
</body>
</html>
Below is getData.php
<?php
$status = $_GET["status"];
echo $status;
?>
Everytime I click on any of the tags I get "undefined" in the "entries" tag. Could anybody explain why it's undefined?
use xmlHttp.responseText
This is how I handle AJAX. Essentially an example of akellehe's answer
function getSuggestions(type){
if(type == "") {
document.getElementById("entries").innerHTML="test"
return;
}
var r = getXmlObject();
var url= "getData.php?status="+type;
if (r.readyState == 4 || r.readyState == 0) {
r.open("POST", url, true);
r.onreadystatechange = function (){
if (r.readyState == 4) {
document.getElementById("entries").innerHTML= r.responseText;
}
};
r.send(null);
}
}
////////////////////////////////////
function getXmlObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.');
}
}