PHP, AJAX, MYSQLI and IE9 not outputting as expected [duplicate] - php

This question already has answers here:
Error on IE 9 - 'SCRIPT600: Invalid target element for this operation
(3 answers)
Closed 9 years ago.
I am using a combination of PHP, AJAX, and MYSQLI to load suggestions of what a user is typing (fires off to load at each keypress). This is all working nicely in chrome, ie10, firefox, safari, etc. Then I tried it on IE9, and it just displayed "No Suggestions" (which I coded to do if it found no matches). My only thought was that it could be a caching issue that I read about on google, but on trying all the suggestions.. I ended up where I started.. "No Suggestions". So, I'm stumped. Here's the code for my AJAX:
function activelyLoad(passedInfo, insertInto, urlInLib)
{
if (passedInfo.length==0)
{
document.getElementById(insertInto).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(insertInto).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../lib/"+urlInLib+"?q="+passedInfo,true);
xmlhttp.send();
}
And here's one of the PHP files I'm loading in:
<?php
include('config.inc.php');
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Pragma: no-cache' );
$full = $_GET['q'];
$fullAr = explode(" ", $full);
$count = count($fullAr);
$var = $fullAr[0];
$query = "SELECT * FROM StudentInfo WHERE (StudentFirstName LIKE '%$var%' OR StudentPrefferedName LIKE '%$var%' OR StudentLastName LIKE '%$var%')";
$response = "";
if ($count >= 2) {
$var2 = $fullAr[1];
$query = "SELECT * FROM StudentInfo WHERE ((StudentFirstName LIKE '%$var%' OR StudentPrefferedName LIKE '%$var%') AND StudentLastName LIKE '%$var2%') OR ((StudentFirstName LIKE '%$var2%' OR StudentPrefferedName LIKE '%$var2%') AND StudentLastName LIKE '%$var%')";
}
$result = mysqli_query($connection, $query);
$num_results = mysqli_num_rows($result);
if ($num_results > 0) {
while ($row = mysqli_fetch_array($result)) {
$id = $row['StudentID'];
$functionList = "\"activelyLoad($id, 'detDiv', 'addtable.php'),showElem('#details')\"";
$functionList2 = "\"logLoad($id), showElem('#contactDets')\"";
if(strcmp($row['StudentPrefferedName'], '') != 0){
$response .= ("<tr><td>" . $row['StudentFirstName'] . " \"" . $row['StudentPrefferedName'] . "\" " . $row['StudentLastName'] . "</td><td><button type='button' onmousedown=" . $functionList . " onclick=" . $functionList2 . ">Get details</button></td></tr>");
}
else{
$response .= ("<tr><td>" . $row['StudentFirstName'] . " " . $row['StudentLastName'] . "</td><td><button type='button' onmousedown=" . $functionList . " onclick=" . $functionList2 . ">Get details</button></td></tr>");
}
}
}
else $response = "No suggestions";
echo($response);
mysqli_close($connection);
?>
Here is the relevant HTML output of this page in IE9:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<META HTTP-EQUIV=”Pragma” CONTENT=”no-cache”>
<title>XXXXXXX</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="../lib/searchScripts.js"></script>
</head>
<body>
<h1>XXXXXXXX</h1>
<p>Please select one of the following options:</p>
<ul>
<li><a id="searchLink" href="#" onclick="showElem('#search')">Search for a student</a></li>
<div id="search">
<p><b>To find a student, start typing a name in the input field below:</b></p>
<form>
Student Name: <input type="text" onkeyup="activelyLoad(this.value, 'txtHint', 'gethint.php'), showElem('#suggestions')">
</form>
<div id="suggestions"><h2>Suggestions:</h2> <div id="suggestionsBox"><table id="txtHint"><tr><td>No Suggestions</td></tr></table></div></div>
The only thing that makes me think it has to be a cache issue is that this WORKS on all modern up to date browsers. Any help is greatly appreciated.
EDIT IE9's console returns
SCRIPT600: Invalid target element for this operation. for 'document.getElementById(insertInto).innerHTML=xmlhttp.responseText;'
Is this my issue? How is it invalid? How is the browser able to get to the AJAX to load the "No Suggestions" if it errors out here?

Among many other issues you are trying to dump the AJAX results into a <table> element as the .innerHTML property.
Internet Explorer has a bug that won't let you set the content of a table tag via .innerHTML until the bug is fixed in IE10
Bug report: http://webbugtrack.blogspot.ca/2007/12/bug-210-no-innerhtml-support-on-tables.html
You would be better off to create a <div> and set the .innerHTML of that instead.

Related

How to dynamically open a new page using this php code?

I have this php code which basically retrieves information from a MySQL database and displays it in a table.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<?php
if ( !$conn = new mysqli("localhost", "root", "", "zendesk_data") ){
$output="Connection failed: " . $conn->connect_error;
} else {
$sql = "SELECT id, subject, requester FROM escalationreview";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
$output="<table>
<tr align='left'>
<th>ID</th>
<th>Subject</th>
<th>Requester</th></tr>";
while($row = $result->fetch_assoc()) {
$output.= "<tr><td>". $row["id"]. "</td><td>" . $row["subject"]. "</td><td>" . $row["requester"]. "</td></tr>";
}
$output.="</table>";
} else {
$output= "0 results";
}
} else {
$output="Error en la consulta: ".$conn->error;
}
$conn->close();
}
echo $output;
?>
</body>
</html>
This is what my index page looks like:
Now, what I want to achieve is that, when I click in the ticket ID, it opens up that ticket page. So, for example, if I click in ticket with ID 1234 it opens 1234.php and if I click in ticket with ID 1235 it opens 1235.php and so on.
I'm new to php and honestly I have no clue how to achieve this.
Thanks to anyone willing to assist and sorry if this seems like a dumb question. Thanks again.
You can use a common page to pass the ticket ID and retrieve the details.
First, you have to wrap the ticket ID as an anchor link to the page you want to redirect. The link also should have the Ticket ID as a parameter.
$output.= "<tr><td><a href='ticketpage.php?tid=".$row["id"]."'>". $row["id"]. "</a></td><td>" . $row["subject"]. "</td><td>" . $row["requester"]. "</td></tr>";
Then, create a new page with the name ticketpage.php (You can change this if you need to) and retrieve the ID we passed via the link earlier by using the code example below:
<?php
$tid = $_GET['tid'];
// Remaning code

Calling a random record on pageload via PHP, dynamically displaying result via AJAX

this is something I've been stuck on for around 7 hours total over the last 3 days, and it is driving me absolutely insane. Any assistance you could lend me with be greatly appreciated.
Basically I want to:
Call a PHP function on pageload which randomly selects a record from
my MySQL database
Dynamically display that record in a HTML page
(Once I've got that down, I also want to be able to trigger that this process on the click of a button.)
Before tackling this task, I put together a prototype which dynamically displays a specific record via a HTML dropdown menu: http://lrdondmt.com/week13/ajaxprototype1.html
I've been trying to modifications to this code to achieve the above.
My PHP looks like this:
<?php
// connect to database
$username= "**withheld**"'
$password="**withheld**";
$database="**withheld**";
$table="banddb";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// the query itself, selects random record from database
$sql="SELECT * FROM banddb WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM quotes ) ORDER BY id LIMIT 1";
$result = mysql_query($sql);
// echo result
while($row = mysql_fetch_array($result))
{
echo '<b>Band name:</b> ' . $row['bandname'] . '</br></br>';
echo '<b>Location:</b> ' . $row['city'] . ', ' . $row['state'] . '</br></br>';
echo '<b>Image:</b> </br></br>' . '<img src="http://lrdondmt.com/discovermusic/images/' . $row['imgpath'] . '" />' . '</br></br>';
echo '<b>About the band: </b>' . $row['abouttheband'] . '</br></br>';
echo '<img src="http://www.lrdondmt.com/discovermusic/images/bandcamp-icon.png" alt="Find on the band on Bandcamp" />' . '</br></br>';
echo '<img src="http://www.lrdondmt.com/discovermusic/images/facebook-icon.png" alt="Find on the band on Facebook" />' . '</br></br>';
echo '<b>Bandcamp player:</b> </br></br>' . '<iframe width="300" height="100" id=bandcampplayer src="http://bandcamp.com/EmbeddedPlayer/v=2/album=' . $row['bandcampid'] . '/size=grande/bgcol=e9e9e9/linkcol=890101/" allowtransparency="true" frameborder="0" >' . '</br></br>';
}
echo "</table>";
// close connection
mysql_close();
?>
My HTML document looks like this:
<!DOCTYPE html>
<html>
<head>
<title>AJAX prototype 2</title>
<script type="text/javascript" >
function showRecord()
{
{
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");
}
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","getmusic2.php",true);
xmlhttp.send();
}
</script>
<script type="text/javascript" >
$(document).ready(function(showRecord))
</script>
</head>
<body>
<div id="txtHint">
<em>Your content should appear here.</em>
</div>
</body>
</html>
If you need any further info, please just ask.
Since you are already using jQuery, you could replace your whole showRecord() function with this more simple jQuery function :
$.ajax({
url: 'getmusic2.php',
success: function(data) {
$('#txtHint').html(data);
}
});
Also, your on load call should look like that :
$(document).ready(function() {
showRecord();
});
Your closure looks wrong when calling your ajax function, fix this line
$(document).ready(function(showRecord))
to look like this
$(document).ready(function(){showRecord()})

populating two dropdown list using ajax

I have two dropdowns and I want the second dropdown to get populated on the basis of the data selected from the 1st dropdown
Here is my main.php:
<?php
include('connection.php');
$query_religion="SELECT DISTINCT religion FROM religion_caste_table";
$result_religion = mysql_query($query_religion, $con);
?>
<html>
<body>
<select name="religion" id="religion" style="width: 100px" onChange="showcaste(this.value)">
<?php
while($q_rel_data = mysql_fetch_array($result_religion))
{?>
<option value="<?php echo $q_rel_data[0]; ?>">
<?php echo $q_rel_data[0]; ?>
</option>
<?php }?>
</select>
<div id="view"></div>
<select name="caste" id="caste" style="width: 100px"></select>
</body>
</html>
And this is getcaste.php:
<?php
include('connection.php');
$string=$_GET["religion"];
$sql="SELECT caste FROM religion_caste_table WHERE religion = '".$string."'";
$result = mysql_query($sql,$con);
$myarray=array();
$str="";
while($result_caste=mysql_fetch_array($result))
{
$str=$str . "\"$result_caste[caste]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo $str;/*Stop hiding from IE Mac */
//echo $string;
mysql_close($con);
?>
<html>
</html>
now for the javascript ajax file,(religion_caste.js)
function showcaste(string)
{
if (string=="")
{
document.getElementById("caste").innerHTML="";
return;
}
alert(string);
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("view").innerHTML=xmlhttp.responseText;
//now how to catch the string from (getcaste.php), split it and save it into array
// and to populate the second dropdwn by the array;
}
}
xmlhttp.open("GET","getcaste.php?religion="+string,true);
xmlhttp.send();
}
For more better assistance, the database table contains two fields, religion and caste, where the first attribute is religion, and caste being the second.
If somehow I can catch the string str, then it could have solved the matter.
document.getElementById("view").InnerHTML=xmlhttp.responseText provides the string "str1","str2",... to be viewed in <div id="view">
But if I write the following code:
var string=(document.getElementById("view").InnerHTML);
alert(string);
Then a msgbox pops up with such view:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
"Catholic","Protestant"
If I could just get the string, I would be happy.
So in your place a would do a little remake in getcaste.php first - place all results from your query into an array and then use implode to get a string using delimiter - ;. (Optionaly you could use a json and decode it in js). In religion_caste.js use split to get an array back from it (; as delimiter);
Now use for cycle to cycle through all values, and every cycle add one option into select
example:
var select = document.getElementById("caste");
for (var key in values)
{
var OptNew = document.createElement('option');
OptNew.text = values[key];
OptNew.value = key;
try
{
select.add(OptNew, null); // doesn't work in IE
}
catch(ex)
{
select.add(OptNew); // IE only
}
}
Edit:
so json in php is easy - json_encode
json in js is a little bit more difficult. New browsers should support JSON.parse, for old ones you have to use this code(Not 100% sure here since I always use jQuery). Alternatively you could use jQuery and jQuery.parseJSON

Warning: mysql_fetch_array() expects parameter 1 to be resource, null given. [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
I'm trying to learn how to use AJAX correctly with PHP and MySQL. I've seen other people's posts on this site regarding the same example I'm working with, but I haven't seen anything about the same issues I'm having.
The site holding the source code is PHP - AJAX and PHP.The site I have hosting my code is here.
The first link has a working example and the second link shows you the error I'm trying to figure out.
I tried to use mysqli, but it said something about expecting two parameters, so I changed it back. If anyone has suggestions on how to get it to work, I'd greatly appreciate it.
Error: mysql_fetch_array() expects parameter 1 to be resource, null given in /data/multiserv/users/748953/projects/1801445/www/test/getuser.php on line 24
The html code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Ajax-PHP/MySQL Cooperation Test</title>
<script type="text/javascript">
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>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint">Person info will be listed here.</div>
</body>
</html>
PHP:
<?php
$q=$_GET["q"];
include("dbinfo.inc.php");
$con = mysql_connect(localhost, $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
$resul1 = mysql_query('SELECT * FROM `ajax_demo` WHERE id = \'\".$q.\"\'') or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
You have a spelling mistake you are assigning value in $resul1 and using mysql_fetch_array($result) notice $result
first try to check the data of $q
and after that try with this query:
mysql_query("SELECT * FROM `ajax_demo`
WHERE id = '" . mysql_real_escape_string($q) ."'");
You have a spelling mistake you are assigning value in $resul1 and using mysql_fetch_array($result) notice $result.
change your while statement into this:
while($row = mysql_fetch_array($result1))
Edit:
Make sure to always review your code and always use a consistent naming convention, the error indicated by the server is already enough to detect to which part of the program the issue is occuring (no need to run any other function if you want to have a complete debugging settings for you development server set it up on the configuration files instead of doing it on the application itself but turn it off for the live server for security purposes).
"Error: mysql_fetch_array() expects parameter 1 to be resource, null given in /data/multiserv/users/748953/projects/1801445/www/test/getuser.php on line 24"
which means that the error is happening on line 24 of the file "/data/multiserv/users/748953/projects/1801445/www/test/getuser.php" and that the variable on the first parameter you have used on the function "mysql_fetch_array" is the one causing the problem because of the statement "expects parameter 1 to be resource" so you should go directly to which part of the program this error is pointing which is helpful for any programmer. ;)
Change $resul1 to $result1, you did wrote wrong there.

Create custom XML which is then picked up via AJAX

For some reason, I keep getting XMLDoc is null, in firebug. I think that perhaps my program isn't parsing the XML that I am trying to generate (and that means I am likely not doing it correctly).
NOTE: I DO NOT WANT TO USE JQUERY HERE!
Here's my code that is supposed to generate the XML code:
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("generic");
$rescult = mysql_query("SELECT * FROM culture order by cult_id");
if (!$rescult) {
die('Invalid query: ' . mysql());
}
$row = mysql_fetch_row($rescult);
ECHO "<item>";
ECHO "<item1>" . $row[0] . "</item1>" . "<br />";
ECHO "<item2>" . $row[1] . "</item2>" . "<br />";
ECHO "</item>";
?>
And here's my code that is supposed to parse it:
<html>
<header>
<script type="text/javascript">
if (window.XMLHttpRequest)
{ // Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// Code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","testitout2.php",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("item1").value =
xmlDoc.getElementsByTagName("item1")[0].childNodes[0].nodeValue;
document.getElementById("item2").value =
xmlDoc.getElementsByTagName("item2")[0].childNodes[0].nodeValue;
</script>
</header>
<body>
<input type="text" id="item1">
<input type="text" id="item2">
</body>
</html>
Edit: I didn't notice the async flag. Guess my answer is irrelevant then.
You are trying to access XML before it was even loaded.
Set property onreadystatechange to xmlhttp:
xmlhttp.onreadystatechange = onStateChange;
function onStateChange() {
if (xmlhttp.readyState != 4) return; //4 means doc is ready
var xmlDoc = xmlhttp.responseXML;
}
You are using a wrong HTML tag: <header>...</header>.
Try replacing it with <head>...</head>, otherwise your script might be simply skipped by the browser.

Categories