I have a multiple select form that I am now trying to use with AJAX. The drop down is supposed to act as a filter for images.
Index.php
<script>
function filterResults(str)
{
if (str=="")
{
document.getElementById("divResults").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("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter_ajax.php?filter="+str,true);
xmlhttp.send();
}
</script>
<form action="" class="css_form" id="picture_filter" name="picture_filter">
<select onchange="filterResults(this.value)" multiple="multiple" name="filter[]" id="filter">
<option value="filter_name_1">Filter name 1</option>
<option value="filter_name_2">Filter name 2</option>
<option value="filter_name_3">Filter name 3</option>
<option value="filter_name_4">Filter name 4</option>
</select>
<div id="divResults"></div>
and filter_ajax.php
<?php
include ("connect.php");
$filter = $_GET["filter"];
$filterIn = implode("','",$filter);
$result = mysql_query("SELECT * FROM edt_images
WHERE category1 IN ('$filterIn')
OR category2 IN ('$filterIn')
OR category3 IN ('$filterIn')
OR category4 IN ('$filterIn')
OR category5 IN ('$filterIn')
OR category6 IN ('$filterIn')")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<img src='files/small/thumb0_".$row['item_name'].".".$row['file_extension']."' border='0'/>";
}
?>
In my database each image has six entries which correspond to the categories, and are filled with subcategories. Thus whats supposed to happen is that when an item is selected from the "filter drop-down" it should query each six columns for that information. However I am receiving the following error and output:
implode(): Invalid arguments passed in ... Line 6.
For testing I have five entries. 3 which have all information filled in for the six categories entries, and two which were left blank.
The two that are left blank are always returned with the error above.
Anyone have any ideas as to why this is happening?
Thanks in advance
Modify <select>:
<select onchange="filterResults(this)" multiple="multiple" name="filter[]" id="filter">
and try this (note: you don't need to implode array with "," on server-side - that is already done with JS in the example):
function filterResults(sel)
{
var selectedOptions = [];
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
selectedOptions.push("'" + sel.options[i].value + "'");
}
}
if (selectedOptions.length == 0) {
document.getElementById("divResults").innerHTML="";
return;
}
str = selectedOptions.join(",");
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("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?filter="+str,true);
xmlhttp.send();
}
UPD:
Modify your SQL also:
$result = mysql_query("SELECT * FROM edt_images
WHERE category1 IN ($filterIn)
OR category2 IN ($filterIn)
OR category3 IN ($filterIn)
OR category4 IN ($filterIn)
OR category5 IN ($filterIn)
OR category6 IN ($filterIn)");
What you're sending to your PHP script, is not an array. So you cannot use implode() on it and implode() is returning an error. Run this:
var_dump($filter);
Then you can decide how to modify your code based on the result.
Related
I have this form which has one select field for main-category, one select field for sub-category and a hidden field. This hidden field is only displayed when a specific value chosen from sub-category.
This sub-category options are the result of ajax response from main-category.
Here is the form:
<form>
<select id='main-cat' name='maincat' onchange="sortSubcat(this.value)"/>
<option value="">Please select one category</option>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
</select>
<div id='subcat-more'>
<select id='subcat' name='subcat'>
<option value=''>Please select a subcategory</option>
</select>
</div>
<div id='morefield' style='display:none'>
<input type='text' name='option1'/>
</div>
</form>
I have a Jquery code which handle this form validation, and it tells whether the #morefield is displayed or not. Here is part of this code:
$("#subcat").change(function(){
if (subcat.val() == 'sub-cat-one'){
$("#morefield").css("display","block");
}else{
$("#morefield").hide();
}
});
Unfortunately, Ajax response only displays option on screen however, it did not change in html so when I viewed source code, I don't see any option for sub-cat. Thats why even I chose option sub-cat-one, I would show the div #morefield.
Is there anyway to solve this problem?
Best Regards,
More informaiton:
Here is my ajax call:
function sortSubcat(str)
{
if (str=="")
{
document.getElementById("subcat").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("subcat").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/member/sortsubcat.php?q="+str,true);
xmlhttp.send();
}
Here is the php file:
<?php
require_once("../configs/dbconnect.php");
if (!empty($_GET['q'])){
$q = basename($_GET['q']);
$sql="SELECT * FROM subcat WHERE maincat=:q";
$result = $conn->prepare($sql);
$result->bindParam(':q', $q);
$result->execute();
echo "<option value=''>Please select a sub cat</option>";
foreach($result as $row)
{
echo "<option value='$row[name]'>$row[name]</option>";
}
}
else{
echo "<option value=''>Please select a subcat</option>";
}
$conn=null;
?>
You have to use
if ($(this).val() == 'sub-cat-one'){
instead of
if (subcat.val() == 'sub-cat-one'){
to access the correct html element (#subcat) in your onchange eventhandler.
You also shouldn't use the id subcat for more than one element. Currently the div and the select are having id subcat.
You have two elements ( div and select ) with same id subcat. id attribute should be unique for all elements .
I think you should try below suggestions:
Use AJAX success callback instead of using onchange.
if ($(this).val() == 'sub-cat-one')
I think I see where your problem is coming from, on each iteration you echo the result. And only that result gets returned to your ajax script. Do this in your php file:
$returned_string = '[';
foreach($result as $row)
{
$returned_string .= '{"name" : "'. $row[name]. '", "value" : "'. $row[name]. '"},';
}
$returned_string = substr($returned_string, 0, -1); //remove trailing ','
$returned_string .= ']';
header("Content-type: application/json");
echo $returned_string;
exit;
Then in your successCallback function:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = JSON.parse(xmlhttp.responseText);
var selectElement = document.getElementById('subcat');
for(var i = 0; i < response.length; i++)
{
var idx = i+1;
selectElement.options[idx] = new Option(response[idx].value, response[idx].name, false, false);
}
}
}
}
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.
getsubcat.php
<?php
include("config.php");
error_reporting(0);
$checkedValue=$_GET['checkedValue'];
$options= "";
$s=mysql_query("SELECT * FROM `sub_category` INNER JOIN `category` on sub_category.cat_id=category.cat_id where category.cat_name='$checkedValue'");
while($rows=mysql_fetch_array($s))
{
$subcategory=$rows['sub_cat_name'];
echo '<input name="sub_category" type="checkbox" class="checkbox_check1" onclick="select_subcatinfo('.$subcategory.')" id="checkbox_check1'.$subcategory.'" value="'. $subcategory.'" > '.$subcategory.'<br /><br />';
}
?>
This is my php coding which ll be loaded through ajax in another page.. Below is my ajax script.
Ajax Script
function select_subcatinfo(name)
{
$("#wait").css("display","block");
var checkedValue1 = name;
if( $("#checkbox_check1"+name).is(':checked') )
{
var xmlhttp;
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)
{
$("#wait").css("display","none");
data = xmlhttp.responseText.split("[BRK]");
document.getElementById("DisplaySubcat").innerHTML = data[0]+" "+data[1];
}
}
xmlhttp.open("GET","getSubcatValue.php?checkedValue1="+checkedValue1,true);
xmlhttp.send();
}
else
{
$("#wait").css("display","none");
}
}
</script>
But inside that echo statement this function is not working.. any help here . thankss
Don't use inline Javascript, use jQuery to bind the event handler:
$(document).ready(function() {
$(".checkbox_check1").click(function() {
if (this.checked) {
$("#wait").show();
$.get('getSubcatValue.php', { checkedValue1: this.value }, function(response) {
var data = response.split('[BRK]');
$("#DisplaySubcat").text(data[0] + ' ' + data[1]);
$("#wait").hide();
});
}
});
});
I'm really not trying to answer this...just cleaned up the op's PHP
<?php
require("config.php");
error_reporting(0);
$checkedValue = $_REQUEST['checkedValue'];
$options = "";
$s=mysql_query("SELECT * FROM `sub_category` INNER JOIN `category` on sub_category.cat_id=category.cat_id where category.cat_name='$checkedValue'");
while($rows=mysql_fetch_array($s))
{
$subcategory=$rows['sub_cat_name'];
echo '<div><input name="sub_category" type="checkbox" class="checkbox_check1" onclick="select_subcatinfo('.$subcategory.')" id="checkbox_check1'.$subcategory.'" value="'. $subcategory.'" > '.$subcategory.'<br /><br /></div>';
}
?>
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 a problem with inner html funcion when updating tag options. In the first select tag I am chosing a country and ajax code must update cities in the other select tag. My code works in all major browsers except IE. Here is the js code for calling php script:
>function show_zones(str)
>{
>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('region_to').innerHTML="";
> jQuery.noConflict();
> (function($) {
> $('#region_to').append(xmlhttp.responseText);
> })(jQuery);
> alert(xmlhttp.responseText);
> }
> }
>xmlhttp.open("GET","ajax/zones.php?country="+str,true);
>xmlhttp.send();
>}
In all browsers alerted code returns appropriate option tags but in IE it returns "Undifined". I am using Jquery to append xmlhttp.responseText because IE does not support innerhtml for select tags. noConflict function is used to avoid conflict between mootolls and jquery libraries. I can`t just place select tag in a div and print it instead of printing just options because I am using custom select which is being created by js code when the window.onload event occurs.
here is the php code:
>require_once("../../connect.php");
>$country_query="SELECT* FROM `tour_countries` WHERE >country_name='".$_GET['country']."'";
>$country_result=mysql_query($country_query);
>$country_row=mysql_fetch_array($country_result);
>$zone_query="SELECT* FROM `tour_zones` WHERE country_ID='".$country_row[0]."'";
>$zone_result=mysql_query($zone_query);
>while($zone_row=mysql_fetch_array($zone_result))
>{
> echo '<option value="'.$zone_row[1].'">'.$zone_row[1].'</option>';
>}
Thanks for replys and sorry for my poor englesh.
I had the same issue with IE and .innerHtml() with ajax calls. I solved it by making the AJAX a POST request and using jQuery .html() instead of .innerHTML(), for some reason IE is pretty glitchy with innerHtml(). Here's the working function I used:
function getCitiesFromState(state, select, spinnerNum)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var ran = Math.round((new Date()).getTime() / 1000),
terms = "state="+state+'&r='+ran;
xmlhttp.open("POST","ajax5.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
/***********************************************************
* These two lines cause Chrome to throw non-fatal errors.
* Removing them didn't change the functionality of the
* request, but this may end up needing a conditional.
***********************************************************/
//xmlhttp.setRequestHeader('Content-length', terms.length);
//xmlhttp.setRequestHeader('Connection', 'close');
xmlhttp.onreadystatechange = function()
{
$('#spinner'+spinnerNum).fadeIn(300);
if (xmlhttp.readyState == 4
&& xmlhttp.status == 200)
{
$('#spinner'+spinnerNum).fadeOut(100);
$('#'+select).html(xmlhttp.responseText);
}
}
xmlhttp.send(terms);
}
And the ajax5.php file:
<?php
include 'db.class2.php';
$DB = new DB_MySql2;
$DB->connect();
$state = mysql_real_escape_string($_POST['state']);
$q = $DB->query("SELECT DISTINCT `city`, `zip_code`
FROM `usa_master`
WHERE `state` = '".$state."'
GROUP BY `city`
ORDER BY `population` DESC LIMIT 0, 150");
while($r = $DB->fetch_assoc($q)) {
$city[] = $r['city'];
$zips[] = $r['zip_code'];
}
array_multisort($city, $zips);
echo '<option value="" selected="selected">Select City</option>';
$size = sizeof($city);
for ($x = 0; $x < $size; $x++)
{
if (strlen($zips[$x]) == 4)
{
$zips[$x] = '0' . $zips[$x];
}
echo '<option class="city_list" value="'.$zips[$x].'">'.$city[$x].'</option>';
}
?>
Hope this helps.