populating two dropdown list using ajax - php

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

Related

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

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.

syntax highlighter doesn't work after call back

So I'm new to Js & php and I'm trying to print out a piece of code from a call back function
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","callback_json.php",true);
xmlhttp.send();
}
</script>
<title>Simple Cross Domain Ajax</title>
</head>
<body>
<h1>.....</h1>
<h2>.....</h2>
<button onclick="loadXMLDoc();">Get Data</button>
<div id="myDiv"><h2>...</h2></div>
</body>
</html>
and my php file goes like
<?php
$ch = curl_init();
$url='someurl';
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
echo "<script type='text/javascript' src='syntaxhighlighter/scripts/shCore.js'></script><script type='text/javascript' src='syntaxhighlighter/scripts/shBrushJava.js'></script><link href='syntaxhighlighter/styles/shCore.css' rel='stylesheet' type='text/css' /><link href='syntaxhighlighter/styles/shThemeDefault.css' rel='stylesheet' type='text/css' />";
echo "<pre class='brush:java;'>";
echo $data;
echo "</pre>";
echo '<script type="text/javascript">SyntaxHighlighter.highlight();</script>';
?>
And it seems syntax highlighter works on my php file but not after call back...I did some research and I know I'm supposed to use SyntaxHighlighter.highlight() instead of all() in the code but I've already done that. Is there any problem with my code structure?
<script> tags added by innerHTML are not executed by the browser. You need to execute them manually:
var scripts = document.getElementById("myDiv").getElementsByTagName("script");
if (scripts && scripts.length) {
for (var i =0; i<scripts.length; i++) {
eval(scripts[i].innerHTML);
}
}
Alternatively you can re-append the script nodes to the page instead of evaling it:
// ...
for (var i =0; i<scripts.length; i++) {
var s = document.createElement('script');
s.innerHTML = eval(scripts[i].innerHTML);
document.body.appendChild(s);
}
but this is exactly the same as evaling the code anyway (no really, think hard about it both methods execute the code unchecked).
A better way is to avoid script injection altogether by adding the Syntaxhighlighter files at the top of the page and calling SyntaxHighlighter.highlight() after you've innerHTMLed the 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()})

Ajax Base64 Image Response Text

I am sending ajax request to the server as :
Client Side Code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var imgVal='img_id'+1;
xmlhttp.open("GET","imageprovider.php",false);
xmlhttp.send();
if(xmlhttp.readyState==4)
{
alert(xmlhttp.responseText);
document.getElementById('img').appendChild(xmlhttp.responseText);
}
</script>
</head>
<body>
<div id='img'>
</div>
</body>
And here is the server side code that shows a simple image with base64 encode.How can i get the response from client the above code and show it.
Server Side PHP Code :
<?php
$img_src = "images/1.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>
Try replacing
document.getElementById('img').appendChild(xmlhttp.responseText);
with
document.getElementById('img').innerHTML = xmlhttp.responseText;
Or, if you need to continue using .appendChild(), try replacing
document.getElementById('img').appendChild(xmlhttp.responseText);
with
var o = document.createElement('img');
o.src = xmlhttp.responseText;
document.getElementById('img').appendChild(o);
And replacing
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
with
echo 'data:image/jpg;base64,'.$img_str;
you capture the response
you inject the response into the DOM
Whith jQuery the code would be something like this:
$.ajax({
url: "imageprovider.php",
context: document.body,
success: function(data){
$('#objectToAddImage').html(data);
}
});
Nevertheless I would advise against passing the image as a base64 as the browser will have no way to cache it. If passing the image as a base64 encode is not an absolute requirement of your project I would recommend the server simple pass a link to the actual image.

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