I'm basically copying this example from w3c schools and when you start typing in a name a few suggestions get added. No suggestions are getting added for me.
nameguess.html
<!DOCTYPE html>
<html lang="en-ca">
<head>
<meta charset="utf-8" />
<title>Ajaxing</title>
<script type="text/javascript">
<!--
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","gethint.php?q="+str,true);
xmlhttp.send();
}
//-->
</script>
</head>
<body>
Hello.<br />
<form method="GET" action="">
Name: <input type="text" id="txt1" /><br />
Suggestions: <span id="txtHint"></span>
</body>
</html>
gethint.php
<?php
// Fill up array with names
$a[]="Anna";
//removed code to save space
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
I have both files located in the www folder of WAMP and have the virtual server running.
I can see that others have already answered what you are trying to do but I would suggest not making your ajax requests like that example.
Instead try using the jQuery library to make your ajax requests. I was able to shorten up the code above into this.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$.get(
'gethint.php', //Code behind
{q : $("#txt1").val()}, //json string of variables to post
function(data){$("#txtHint").html(data);}, // What to do with return data
'json'); //Specify json
</script>
It will make life much easier in the long run, because it stinks to have to go through that whole mess and have to worry about cross-browser compatibility.
You can find more information here JQuery
You have missed the key press event binding:
<input type="text" id="txt1" onkeyup="showHint(this.value)">
Also, your PHP could be simplified as
<?php
if(!isset($_GET['q']) exit;
// Fill up array with names
$names = array("Anna", "Vicky");
//get the q parameter from URL
$q=$_GET["q"];
$hints = array();
foreach($names as $name) {
if (stripos($name, $q) !== -1) $hints[] = $name;
}
if(count($hints) == 0) die("no suggestion");
echo implode(', ', $hints);
?>
change this
<input type="text" id="txt1" />
to
<input type="text" id="txt1" onkeypress="showHint(this.value)"/>
and see if this helps
Related
I want to create error message like this
SPACE Not Allowed Please Try Again
If input is space in firstname and do I need to repeat the ajax for the lastname? It is not conflict while using another action update.php in form html?
<!DOCTYPE html>
<html>
<head>
<script>
function showError(str) {
if (str == "") {
document.getElementById("txtError").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtError").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","resident/residenterrormessage.php?g="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="update.php" meth="POST">
<div id="txtError">Error Message</div>
<input onchange="showError(this.value)" title="First Name" name="firstname" type="text">
<input title="Last Name" name="lastname" type="text" value="">
<input type="submit" name="submit">
<input>
</form>
</body>
</html>
this is my residenterrormessage.php in folder resident
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="css/w3.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php
$firstname = str_replace(" ", "", $_GET["g"]);
if(empty($firstname) ){
echo '<h1>"SPACE Not Allowed Please Try Again"</h1>';
}
?>
</body>
</html>
Based on your code you are appending an whole page inside the div. So i did some editing in your code. You might wanna try to edit your residenterrormessage.php to this
<?php
if(empty(str_replace(" ","",$_GET["q"]))){
echo '<h1>SPACE Not Allowed Please Try Again</h1>';
}
else
{
echo "a";
}
?>
I have a jquery code that shows for me collapsibles, when i put the code in html5 it works , But i need that code to came from a php page and being shown in a div in the html5, but it doesn't work ,here is the code that i put in the php + the sql connection and the files of jquerys .....
echo"<div data-role='collapsible'>";
while($row=mysqli_fetch_array($result))
{
echo " <h4>" .$row['Nom']. "</h4>";
echo " <p>" .$row['Nom']. "</p>";
}
echo"</div>";
but it just shows me in my div the two lines of rows ...
ADD:
This is my php file :
<?php
$host = "localhost";
$port = number;
$socket = "";
$user = "root";
$password = "";
$dbname = "database name";
$value =$_GET['value'];
$con = new mysqli($host, $user, $password, $dbname, $port, $socket);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="request";
$result = mysqli_query($con,$sql);
echo'<div id="accordion">';
while($row=mysqli_fetch_array($result))
{
echo" <h3>test</h3>
<div>
<p>test </p>
</div>";
}
echo" </div>";
echo"</div>";
mysqli_close($con);
?>
and the html5 file is :
<!DOCTYPE html>
<head>
<LINK rel="stylesheet" type="text/css" href="style.css">
<script src="log.js" charset="ISO-8859-1"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title> réclamation Interne </title>
<script>
$(function() {
$( "#accordion" ).accordion();
});
function showUser(str)
{
var x=document.getElementById('matr');
var str = x.value;
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","http://IP/File name/test.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
</div>
<div class="login">
<center><h1>Datas </h1></center>
<div id="landmark-1" data-landmark-id="1">
<div>
<center>
<form name="data" >
<input type="text" id="matr" onchange="showUser()" >
</form></center>
</div>
<br>
<center>
<div id="txtHint"><b>Click here to show data</b></div></center>
</div>
<div class="login-help">
</div>
</body>
</html>
You are trying to initialize the jQuery plugin on an element that does not exist yet. I think it is important to understand what is going wrong, so you can avoid this problem in the future, since this is a very common pattern you're using.
We'll look at your code, starting with this bit...
$(function() {
$( "#accordion" ).accordion();
});
...which is executed immediately, as the page loads. Since there is no element with the id accordion at that moment, nothing happens (check your console -- probably have an error).
Then, you have the onchange code on the input element, which uses non-jQuery ajax to send a request on to your php file. The php file generates some html, wrapped in a div with the id accordion, and adds it to the page. That element has never had the accordion-related javascript applied to it, and thus sits there with no functionality.
You've got some of the concepts right, but your timing is wrong. First of all, let's use the jQuery ajax method to simply that code. Also, since you're already paying a performance/load time cost to include jQuery in your project, you should take full advantage of the functionality and use the utility element selector as well:
The new javascript
(function ($) {
// used to keep a reference to the ajax request object
var searchQuery = false;
var showUser = function (str) {
if (searchQuery != false) // if there is a pending request, cancel it
searchQuery.abort();
var searchTerm = $('#matr').val();
if (searchTerm .trim().length < 1) {
$("#txtHint").html('');
return;
}
// clean up the old accordion
if ($("#accordion").length > 0)
$("#accordion").accordion('destroy');
$("#txtHint").html('seaching...');
searchQuery = $.ajax({
'url':'http://IP/file_name/test.php?q='+searchTerm,
'success':function (response) {
searchQuery = false;
$('#txtHint').html(response);
$('#accordion').accordion();
},
'error': function () {
searchQuery = false;
$('#txtHint').html('Sorry, there was an error');
}
});
};
// add the change event to the text field, once the page loads
$(document).ready(function () {
$('#matr').change(showUser);
});
})(jQuery);
The HTML
The only change required to the HTML is that you remove the inline onClick event from the input. That said, you are using center to center text, which is not a good practice. Use css text-align:center; instead -- the less tags, the better (generally speaking).
The PHP
Nothing needs to change here, but be certain you are correctly treating the user input that you're getting from $_GET. Using mysqli_* alone does not protect against SQL injection, if you don't use it correctly. We don't see that code here, so consider this a standard disclaimer: never trust user input!
Documentation
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
jQuery UI Accordion widget - http://jqueryui.com/accordion/
I'm trying to display data from database(MySQL) based on the option fields selected. I have two fields as shown below :
Select a Health Block : .......(list)
Select the year : .......(list)
When I select health block and year, data from database should be displayed on the same page itself. I've tried the following code. Actually the code works if I've only one option ('year') to be selected. What I need is to pass both the values (Health block and Year) to the page (getblock2.php) where I've written the code to retrieve data from database. Can anybody please help me to figure out where the problem is?
Mainpage
<html>
<head>
<script type="text/javascript">
var str11;
var str22;
function showB(str2)
{
str22=str2;
}
function showBlock2(str)
{
showB();
str11=str;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getblock2.php?q="+str11+"&h="+str22,true);
xmlhttp.send();
}
</script>
</head>
<body>
Select a Health block
<select name="h" onChange="showB(this.value)">
<option value="1">H1</option>
<option value="2">H2</option>
</select>
<br/>
Select a year
<select name="yr" onChange="showBlock2(this.value)">
<option>2012</option>
<option>2013</option>
</select>
<div id="txtHint" style="width:570px; height:auto" >
</div>
</body>
</html>
getblock2.php
<?php
include("connect.php");
$q=$_GET["q"];
$h=$_GET['h'];
$q="select Total_Cases from epidemics where Year1=$q and Hid=$h";
$r=mysql_query($q);
$i=0;
while($row=mysql_fetch_row($r))
{
$i++;
echo $i." ".$row[0]."<br/>";
}
?>
Variable str22 is not being assigned when you call showBlock2() on changing year. So replace the line
showB();
with
showB(document.getElementsByName("h")[0].value);
This would work when you select health and then year, no need to call showB() on changing health list.
EDITED (Optimized Code):
The following code has been altered from your source.
Mainpage
<html>
<head>
<script type="text/javascript">
function showBlock2()
{
var str11=document.getElementsByName("h")[0].value;
var str22=document.getElementsByName("yr")[0].value;
document.getElementById("txtHint").innerHTML="";
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getblock2.php?q="+str11+"&h="+str22,true);
xmlhttp.send();
}
</script>
</head>
<body>
Select a Health block
<select name="h" onChange="showBlock2()">
<option value="1">H1</option>
<option value="2">H2</option>
</select>
<br/>
Select a year
<select name="yr" onChange="showBlock2()">
<option>2012</option>
<option>2013</option>
</select>
<div id="txtHint" style="width:570px; height:auto" >
</div>
</body>
</html>
Note that only function showBlock2() is used for onchange on both dropdowns, so the div txtHint is updated at each change. Also no parameters passed.
Just remove
showB()
It will work fine. As you have already values in both variables. Just showB() function is making the variable empty again.
Here is the optimized code. It can work in both cases, which ever select option you select first.
<script type="text/javascript">
var healthValue = "";
var yearValue = "";
function showB(str2)
{
healthValue = str2;
if(yearValue != '')
{
callAjax();
}
}
function showBlock2(str)
{
yearValue = str;
if(healthValue != '')
{
callAjax();
}
}
function callAjax()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getblock2.php?q="+healthValue+"&h="+yearValue,true);
xmlhttp.send();
}
</script>
I have a form that let user to choose where them come from..
I have list out the country list by select box..
and i success to do it onchange and use ajax to read out all the state list..
actually i have two php file.. one is the main one that contain all the code include the form.. another one is generate state list.. my ajax code and form are in the main php
this is the one that generate state list...
$cID = $_GET["country"];
$sql = "SELECT * FROM States WHERE CountryID=$cID";
$result = $db->get_results($sql);
if (isset($result)) {
foreach ( $result as $states ) {
?>
<input type="checkbox" name="chkState[]" value="<?=$states->StateID?>" /> <?=$states->StateName?><br />
<?php
}
}
this is part of my code that read out..
but my problem is...
where i submit the form..
i only get the variable of country.. i cannot take the data of state that use ajax to generate out...
sample of my form
<form action="" name="place">
<select name="cboCountry" class="drop" onchange="showState(this.value)">
//some php code the list out the country
</select>
<div id="txtHint">
</div>
<input type="submit" name="submit" value="submit" />
</form>
and here my ajax code
<script>
function showState(str)
{
alert('xxx');
var xmlhttp;
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","state_list.php?country="+str,true);
xmlhttp.send();
}
</script>
so when i submit the from with a save button... i only get the date of country and state are missing.. any body can help me? or having any way to do what i want?
This ajax test should (by the will of about 2 hours now) return the request result into a textarea. The request is being made to the same page, and I have a $_POST isset test at the top of the body to check whether the request is coming from my POST request (I need to have the code all in one file). The result is that "text to appear in the textarea box" is returned by itself, and isn't placed inside the textarea.
//name of this page is testing.php
<html>
<head>
function loadXMLDoc()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("testTextarea").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.open("POST","testing.php",true);
xmlhttp.send("test");
}
</head>
<?
if (isset($_POST["testName"])) {
die("text to appear in the textarea box");
}
?>
<body>
<form action="testing.php" method="POST" onsubmit="loadXMLDoc(this.form); return false;">
<input class="command" type="text" name="testName" />
<div><textarea id="testTextarea"></textarea></div>
</body>
</html>
Try moving the die() to the top so that nothing else is outputted before die()
<?
if (isset($_POST["testName"])) {
die("text to appear in the textarea box");
}
?>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("testTextarea").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","testing.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("testName=blah");
}
</script>
</head>
<body>
<form action="testing.php" method="POST" onsubmit="loadXMLDoc(this.form); return false;">
<input class="command" type="text" name="testName" />
<div><textarea id="testTextarea"></textarea></div>
</form>
</body>
</html>