Ajax is not working in php statement - php

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

Related

Can we use xmlhttp.open(); in same file

I try to use these code from w3school but I have some problems.
My first file:
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
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","getresult.php?q="+str,true);
xmlhttp.send();
}
</script>
<?php
echo "First name: <input type=\"text\" id=\"txt1\" onkeyup=\"showHint(this.value)\" />";
echo "<p>Suggestions: <span id=\"txtHint\"></span></p>";
?>
My second file [getresult.php]:
<?php
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
// get the q parameter from URL
$q=$_REQUEST["q"]; $hint="";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
foreach($a as $key=>$name)
{
if ($q==$key)
{
if ($hint==="")
{
$hint=$name;
}
else
{
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>
if i want to have 1 file how should i do with
xmlhttp.open("GET","getresult.php?q="+str,true);
because I upload both file on my server it not work but i works when i run on my computer(localhost)
thanks.
You can use this
if (isset($_GET['q'])) {
//getresult.php contents
}
else {
//first file contents
}

javascript ajax php display

by using javascript ajax i have passed the values to php page...
display the values after retrieving from database and print in ajax page...it displaying in alert page...but i need to display in ajax page....
ajax coding
<script>
function optionsAlert()
{
alert("call");
var xmlhttp;
var qw=document.getElementById('c').value;
var qw1=document.getElementById('c1').value;
var qw2=document.getElementById('unit33').value;
var qw3=document.getElementById('dept').value;
var qw4=document.getElementById('class').value;
alert(qw);
alert(qw1);
alert(qw2);
alert(qw3);
alert(qw4);
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)
{
alert(xmlhttp.responseText);
if(xmlhttp.responseText==1){
alert("name already Exists" );
return false;
}
else if(xmlhttp.responseText==0)
{
alert("name available");
document.login.submit();
}
}
}
var queryString = "?q=" + qw + "&q1=" + qw1 + "&q2=" + qw2 + "&q3=" + qw3 + "&q4=" + qw4;
xmlhttp.open("get",'ques.php' + queryString,true);
xmlhttp.send();
}
php page
<?php
include('connection.php');
if(($_GET['q']!='') && ($_GET['q1']!='') && ($_GET['q2']!='') && ($_GET['q3']!='') && ($_GET['q4']!=''))
{
$a= mysql_query("select * from unit1 where unit='".$_GET['q']."' and stopic='".$_GET['q1']."' and qtype='".$_GET['q2']."' and dept='".$_GET['q3']."' and class='".$_GET['q4']."'");
//$a= mysql_query("select * from unit1 where unit='unit1' and stopic='Subtopic1' and qtype='normal questions'");
if(mysql_num_rows($a)>0)
{
while($row=mysql_fetch_array($a))
{
$a1=$row['qno'];
$a2=$row['ques'];
$a3=$row['ch1'];
$a4=$row['ch2'];
$a5=$row['ch3'];
$a6=$row['ch4'];
$a7=$row['ans'];
echo $a1."<br>";echo $a2."<br>";echo $a3."<br>";echo $a4."<br>";echo $a5."<br>";echo $a6."<br>";echo $a7."<br>";
echo 1;
}
}
else
{
echo 0;
}
}
?>
Below the ajax coding create div element with id
in your ajax method
if(xmlhttp.responseText==1){
document.getElementById("id").innerHTML = "name already Exists";
return false;
}
else if(xmlhttp.responseText==0)
{
document.getElementById("id").innerHTML="name available";
document.login.submit();
}
"id" your own div id

PHP generated javascript not executing

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.

Problem updating select tag with ajax on IE

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.

Simple PHP, AJAX request

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.');
}
}

Categories