My problem I think is simple (but I am really simple), I am not using jquery or any other plugin just pure JavaScript and PhP.
I have a simple form with a select field in which multiple items can be selected such as :
<form id="test" name="test">
<input type="hidden" id="norman" value="bates"/>
<select multiple="multiple" name="fred[]" id="fred[]">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
<input type="button" id="button" value="test" onclick="callAHAH('POST','my-page.php','container','loading...','modify-user')"/>
The callAHAH is the javaScript function that wraps up the data for the Ajax, the function is:
function callAHAH(method,url, pageElement, callMessage,form_name){
//window.location = url;
//document.getElementById(pageElement).innerHTML = callMessage;
try{
req = new XMLHttpRequest(); /* ff */
}
catch(e){
try{
req = new ActiveObject("Msxml2.XMLHTTP"); /* some ie */
}
catch(e){
try{
req = new ActiveXObject("Microsoft.XMLHTTP"); /*other ie */
}
catch(e){
req = false;
}
}
}
req.onreadystatechange = function(){responseAHAH(pageElement);};
var build_url=window.location.origin;
var url = "aj_scripts/"+url;
if(build_url=="http://localhost:8080"){
url=build_url+"/pitd_outer/pitd/"+url;
}
// Check request status
if(method=='POST'){
req.open("POST",url,true);
// adds a header to tell the PHP script to recognize the data as is sent via POST
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var the_data="";
///
var the_form=document.getElementById(form_name);
//alert(form_name);
for (var i=0;i<the_form.length;i++){
var the_type = the_form.elements[i].type;
var value;
if(the_type !="button"){
if(the_type =="checkbox"){
value = the_form.elements[i].checked
// alert("the array name is: "+the_array_name+" and it is checked:"+checked);
}else{
value=the_form.elements[i].value;
}
var id= the_form.elements[i].id;
the_data+=id;
the_data+="="+value+"&";
}
}
the_data=the_data.substring(0,the_data.length-1);//removing the last & symbol
// alert(the_data);
req.send(the_data); // calls the send() method with datas as parameter
}else if(method=="GET"){
req.open("GET",url,true);
req.send(null);
}
}
The JS handler has been working fine until I try and select multiple items and then the code only returns either the first or the last selected item.
I understand that the form is sending an array but I cannot seem to get the code to correctly test for an array I tried
var array_test=Array.isArray(the_form.elements[i]);
alert("array test:"+array_test);
But all I get is false so...
How can I get all of the select data that has been selected and then
How to I format it for the text string for the post is it
my_array[]=1$my_array[]=2 etc
thanks in advance for your help
Zen
OK I have the answer!
function callAHAH(method,url, pageElement, callMessage,form_name){
//window.location = url;
//document.getElementById(pageElement).innerHTML = callMessage;
try{
req = new XMLHttpRequest(); /* ff */
}
catch(e){
try{
req = new ActiveObject("Msxml2.XMLHTTP"); /* some ie */
}
catch(e){
try{
req = new ActiveXObject("Microsoft.XMLHTTP"); /*other ie */
}
catch(e){
req = false;
}
}
}
req.onreadystatechange = function(){responseAHAH(pageElement);};
var build_url=window.location.origin;
var url = "aj_scripts/"+url;
if(build_url=="http://localhost:8080"){
url=build_url+"/pitd_outer/pitd/"+url;
}
// Check request status
if(method=='POST'){
req.open("POST",url,true);
// adds a header to tell the PHP script to recognize the data as is sent via POST
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var the_data="";
///
var the_form=document.getElementById(form_name);
//alert(form_name);
for (var i=0;i<the_form.length;i++){
var the_type = the_form.elements[i].type;
var value;
if(the_type !="button"){
if(the_type =="checkbox"){
value = the_form.elements[i].checked
var id= the_form.elements[i].id;
the_data+=id;
the_data+="="+value+"&";
}else if(the_form.elements[i].hasAttribute('multiple') == true){
var test_data = "";
var the_multiples = the_form.elements[i].options;
if((the_form.elements[i].hasAttribute('getall')==true)&&(the_form.elements[i].getAttribute('getall')=="get_all")){
//a multiple select that we need to get all values from and not just those that are selected
alert("hi");
console.log("inside the_form_elements has attributes");
for(var j=0;j<the_multiples.length;j++){
test_data += the_form.elements[i].id+"="+the_multiples[j].value+"&";
}//end of for var j
}else{
//a select list with potentially multiple selections and only want the selected ones
for(var j=0;j<the_multiples.length;j++){
if(the_multiples[j].selected == true){
test_data += the_form.elements[i].id+"="+the_multiples[j].value+"&";
}//end of if the_multiples
}//end of for var j
}//end of the if the_form inner
test_data=test_data.substring(0,test_data.length-1);//removing the last & symbol
the_data +=test_data;
alert(test_data);
}else{
value=the_form.elements[i].value;
var id= the_form.elements[i].id;
the_data+=id;
the_data+="="+value+"&";
}//end of if the_form outer
}
}
the_data=the_data.substring(0,the_data.length-1);//removing the last & symbol
// alert(the_data);
req.send(the_data); // calls the send() method with datas as parameter
}else if(method=="GET"){
req.open("GET",url,true);
req.send(null);
}
}
function responseAHAH(pageElement){
var output='';
if(req.readyState == 4){
if(req.status == 200){
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
}
}
}
The important bit of the code is:
if(the_type !="button"){
if(the_type =="checkbox"){
value = the_form.elements[i].checked
var id= the_form.elements[i].id;
the_data+=id;
the_data+="="+value+"&";
}else if(the_form.elements[i].hasAttribute('multiple') == true){
var test_data = "";
var the_multiples = the_form.elements[i].options;
if((the_form.elements[i].hasAttribute('getall')==true)&&(the_form.elements[i].getAttribute('getall')=="get_all")){
//a multiple select that we need to get all values from and not just those that are selected
alert("hi");
console.log("inside the_form_elements has attributes");
for(var j=0;j<the_multiples.length;j++){
test_data += the_form.elements[i].id+"="+the_multiples[j].value+"&";
}//end of for var j
}else{
//a select list with potentially multiple selections and only want the selected ones
for(var j=0;j<the_multiples.length;j++){
if(the_multiples[j].selected == true){
test_data += the_form.elements[i].id+"="+the_multiples[j].value+"&";
}//end of if the_multiples
}//end of for var j
}//end of the if the_form inner
test_data=test_data.substring(0,test_data.length-1);//removing the last & symbol
the_data +=test_data;
alert(test_data);
}else{
value=the_form.elements[i].value;
var id= the_form.elements[i].id;
the_data+=id;
the_data+="="+value+"&";
}//end of if the_form outer
Essentially I needed to sue the JavaScript hasAttribute function which I know is apparently not supported by every browser but it worked on IE10, and latest builds of FF O and C.
From there I had to use the .options subselect to cycle through each of select options to find the selected ones.
Those checking the code will notice I have a weird condition in there, the hasAttribute('getall') as I have a very weird situation where I needed to get all of the values out of the multiple select regardless of whether or not they had been selected again I know that non-standard attributes are not sup[ported by all browsers but were with the ones I was using.
regards
Zen
Related
My code is like this i took it from a tutorial website dont remember where please tell me where to put a loading icon in this huge junk of code i dont understand.
Please show me an example via jsfiddle or anywhere else.
<script language = "javascript" type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name = 'myForm'>
Max Age: <input type = 'text' id = 'age' /> <br />
Max WPM: <input type = 'text' id = 'wpm' />
<br />
Sex: <select id = 'sex'>
<option value = "m">m</option>
<option value = "f">f</option>
</select>
<input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
</form>
<div id = 'ajaxDiv'>Your result will display here</div>
First, check this out for more info on ready states.
I'd put a loading just before ajaxRequest.open("GET", "ajax-example.php" + queryString, true); and remove it on if (xmlhttp.readyState==4.
1.
So add HTML where you'd like the loading icon to appear:
<span id="loading"></span>
2.
Then just before ajaxRequest.open... insert loading image:
document.getElementById("loading").innerHTML = '<img src="loading.gif" />';
3.
And inside if (xmlhttp.readyState == 4 put:
document.getElementById("loading").innerHTML = '';
I have two dropdown lists. Both are to be filled by PHP via a mysql query. My problem is I want the form to be responsive if these list selections change. For instance, I need to populate the second list via another query based upon the selection of the first list.
Problem is: I need "on_change" to POST the form data AND to trigger PHP instead of Javascript.
Is there a way to collect that selection in Javascript and then send it to PHP and then refill the form? Hope I'm making myself clear.
Thanks,
Dana
Use Javascript to detect a change of the list. When a change occurs, you can make an AJAX request using a PHP script to return a new list. Javascript can manipulate the new data set and replace the DOM with the new appropriate list.
<script type=\"text/javascript\">
function changeCountry(){
var e = document.getElementById(\"country_id\");
var country_id = e.options[e.selectedIndex].value;
if(country_id == 1){
// Display states
document.getElementById('display_province').style.display = \"none\";
document.getElementById('display_state').style.display = \"\";
document.getElementById('display_state').style.visibility = \"visible\";
}
else{
// Display Province
document.getElementById('display_state').style.display = \"none\";
document.getElementById('display_province').style.display = \"\";
document.getElementById('display_province').style.visibility = \"visible\";
// Remove current selection list
var select = document.getElementById('province_id');
for (var option in select){
select.remove(option);
}
// Get Provinces for country_id
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
// get each property
var x=xmlDoc.getElementsByTagName('province');
for (i=0;i<x.length;i++)
{
var e = document.getElementById('province_id');
var opt = document.createElement('option');
opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
e.appendChild(opt);
}
}
}
var url = 'get_provinces.php?country_id='+country_id;
// var url = 'provinces.xml';
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
}
}
function changeShippingCountry(){
var e = document.getElementById(\"shipto_country_id\");
var shipto_country_id = e.options[e.selectedIndex].value;
if(shipto_country_id == 1){
// Display states
document.getElementById('shipto_display_province').style.display = \"none\";
document.getElementById('shipto_display_state').style.display = \"\";
document.getElementById('shipto_display_state').style.visibility = \"visible\";
}
else{
// Display Province
document.getElementById('shipto_display_state').style.display = \"none\";
document.getElementById('shipto_display_province').style.display = \"\";
document.getElementById('shipto_display_province').style.visibility = \"visible\";
// Remove current selection list
var select = document.getElementById('shipto_province_id');
for (var option in select){
select.remove(option);
}
// Get Provinces for country_id
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
// get each property
var x=xmlDoc.getElementsByTagName('province');
for (i=0;i<x.length;i++)
{
var e = document.getElementById('shipto_province_id');
var opt = document.createElement('option');
opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
e.appendChild(opt);
}
}
}
var url = 'get_provinces.php?country_id='+shipto_country_id;
// var url = 'provinces.xml';
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
}
}
function addProvince(){
// Get input
var np = document.getElementById('new_province').value;
// Get country_id
var e = document.getElementById(\"country_id\");
var country_id = e.options[e.selectedIndex].value;
// Erase input
document.getElementById('new_province').value = \"\";
// Add to database
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
}
}
var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
changeCountry();
changeShippingCountry();
}
function addShippingProvince(){
// Get input
var np = document.getElementById('shipto_new_province').value;
// Get country_id
var e = document.getElementById(\"shipto_country_id\");
var country_id = e.options[e.selectedIndex].value;
// Erase input
document.getElementById('shipto_new_province').value = \"\";
// Add to database
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
}
}
var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
changeShippingCountry();
changeCountry();
}
function hideShipping(){
document.getElementById('shipping').style.display = \"none\";
document.getElementById('shipping').style.visibility = \"hidden\";
}
function displayShipping(){
document.getElementById('shipping').style.display = \"\";
document.getElementById('shipping').style.visibility = \"visible\";
}
You can make an ajax call to an endpoint you set up that runs some php code and returns some JSON that your javascript can then use to populate the second list. Your javascript would look something like:
$.ajax( "your-endpoint.php" )
.done(function(data) {
// use javascript to dynamically populate your list
var json = data;
//assuming data is a list you could iterate over it
$.each(data, function (k, v) {
//use this to populate your list
}
})
.fail(function() {
// show an error message on your form
});
Your PHP endpoint would have to return a JSON object so that your javascript can more easily use it.
Communcation betwen php and javascript is typically done by Ajax, which is very simple to use in jQuery. The basic syntax is something like this:
$.ajax({
type: "POST",
url: "yourFile.php",
data: "{data: " + yourData + "}", //yourData is javascript variable
success: function(result){
//do something with result from php file
}
});
Where variable yourData is what you want to send to php script and it would be accessible throught $_POST['data'].
Everyone answered that Ajax is the solution, and I agree, Ajax is more elegant, but Ajax is not the only solution. I post this answer only to show another way to do it : without Ajax.
The first code (combos.php) is the page with a combo that, when selected, calls PHP. The second code (combos_action.php) is the PHP that returns the values according to the option selected. To make this codes to work, create two text files with the given names, copy-paste the codes and run it from your browser with http://localhost/combos.php. If you change the filenames, change them in the code, also.
Here is how it works : the page shows a simple combo filled with the days of the week. When a day is selected the JavaScript's onchange event fires and the form is autosubmitted, PHP gets the selected day and stores some values in session, returns to the page that refreshes and fills the second combo with those values. Comments will help you to understand:
combos.php
<?php
session_start(); // NECESSARY TO RETRIEVE THE VALUE RETURNED FROM PHP.
?>
<html>
<head>
<title>By José Manuel Abarca RodrÃguez</title>
<script type="text/javascript">
// AUTOSUBMIT FORM #1 WHEN ANY OPTION IN COMBO #1 IS SELECTED.
function combo1_selected () {
document.getElementById( "form1" ).submit();
}
</script>
</head>
<body>
<!-- THIS IS COMBO #1. -->
<form id="form1" method="post" action="combos_action.php">
Select a day
<br/>
<select name="combo1" onchange="combo1_selected()"> <!-- NOTICE THE EVENT! -->
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
</select>
</form>
<?php
// DISPLAY COMBO #2 ONLY IF COMBO #1 WAS SELECTED.
if ( isset( $_SESSION[ "combo2" ] ) )
{ echo "<br/>" .
"<br/>" .
"Options for <b>" . $_SESSION[ "combo1" ] . "</b>" .
"<br/>" .
"<select name='combo2'>";
// SEPARATE THE OPTIONS RETURNED FROM PHP.
$options = explode( ",",$_SESSION[ "combo2" ] );
// DISPLAY THE OPTIONS FOR THE COMBO.
for ( $i = 0; $i < count( $options ); $i++ )
echo "<option>" . $options[ $i ] . "</option>";
echo "</select>";
}
?>
</body>
</html>
combos_action.php
<?php
session_start();
$_SESSION[ "combo1" ] = $_POST[ "combo1" ]; // SELECTED OPTION.
if ( $_SESSION[ "combo1" ] == "Monday" )
$_SESSION[ "combo2" ] = "mon 1,mon 2,mon 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Tuesday" )
$_SESSION[ "combo2" ] = "tue 1,tue 2,tue 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Wednesday" )
$_SESSION[ "combo2" ] = "wed 1,wed 2,wed 3"; // RETURN THESE VALUES.
header( "Location: combos.php" ); // RETURN TO PAGE.
?>
I am puzzled about this. I have two XMLHttpRequests that operate on Select elements of my HTML file (each one operates on a different Select element right when the HTML file is loaded). I am using a callback function as was recommended on W3CSchools. If my variable xmlHttp is defined outside of my callback function, only the second request works, and the first one gets deleted before it has a chance to finish. If I put 'var' in front of it the same thing happens. However, if my variable is inside the function with 'var' in front of it, then absolutely nothing happens. I have narrowed it down to where to the line that says "HERE!!!!!" is where the program seems to hang. I know the loadXMLDoc function does not actually finish because when I put an alert outside of it, nothing happens. I am supposing it has something to do with the 'if' part and the program not being able to recognize xmlHTTP, even though it was locally defined. I am still pretty new to JavaScript and just want to be able to run multiple XMLHttpRequest objects at once without them getting in each other's way but also without the page hanging. Any ideas why this does not work?
HTML:
<form>
<select id="stateSelectCities">
<!-- Will be populated with MySQL -->
</select>
<select id="citySelect">
<option>Select a State</option>
</select>
<br />
<br />
<select id="stateSelectCounties">
<!-- Will be populated with MySQL -->
</select>
<select id="countySelect">
<option>Select a State</option>
</select>
<p id="xmltest"></p>
<p id="currentState"></p>
<p id="sc"></p>
<p id="rs"></p>
<p id="st"></p>
</form>
JavaScript:
<script type="text/javascript">
function loadXMLDoc(method, data, url, cfunc) {
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.onreadystatechange = cfunc;
xmlHTTP.open(method, url, true);
if (data) {
xmlHTTP.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHTTP.send(data);
} else {
xmlHTTP.send();
}
}
function returnStateListForCounties() {
loadXMLDoc('GET', null, "stateslist.xml", function() {
document.getElementById('countySelect').disabled = true;
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// Read the XML Data and Populate Counties States Menu
var response = xmlHTTP.responseXML;
var states = response.getElementsByTagName('state');
for (i = 0; i < states.length; i++) {
var option = document.createElement('option');
option.innerHTML = states[i].childNodes[0].nodeValue;
option.setAttribute('onmouseup', 'returnCounties(this.innerHTML)');
document.getElementById("stateSelectCounties").add(option);
}
}
//document.getElementById("sc").innerHTML = 'statusCode: ' + xmlHTTP.status;
//document.getElementById("rs").innerHTML = 'readyState: ' + xmlHTTP.readyState;
//document.getElementById("st").innerHTML = 'statusText: ' + xmlHTTP.statusText;
})
}
function returnStateListForCities() {
loadXMLDoc('GET', null, 'stateslist.xml', function() {
document.getElementById('citySelect').disabled = true;
// HERE!!!!!
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// Read the XML Data and Populate Cities States Menu
var response = xmlHTTP.responseXML;
var states = response.getElementsByTagName('state');
for (i = 0; i < states.length; i++) {
var option = document.createElement('option');
option.innerHTML = states[i].childNodes[0].nodeValue;
option.setAttribute('onmouseup', 'returnCities(this.innerHTML)');
document.getElementById("stateSelectCities").add(option);
}
}
document.getElementById("sc").innerHTML = 'statusCode: ' + xmlHTTP.status;
document.getElementById("rs").innerHTML = 'readyState: ' + xmlHTTP.readyState;
document.getElementById("st").innerHTML = 'statusText: ' + xmlHTTP.statusText;
})
}
//returnStateListForCounties();
returnStateListForCities();
</script>
The problem here is xmlHTTP variable which is defined inside loadXMLDoc function and try to use again inside returnStateListForCounties function, I'll do it like this:
function loadXMLDoc(method, data, url, cfunc) {
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.onreadystatechange = function() {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200)
{
cfunc(xmlHTTP.responseXML); //Call passed func with the resulting XML
}
};
xmlHTTP.open(method, url, true);
if (data) {
xmlHTTP.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHTTP.send(data);
} else {
xmlHTTP.send();
}
}
This way you encapsulate the data recovery.
I have some links on a page. When a user clicks a link, it uses the text from the link in the WHERE clause of the mysql query and returns the result to the page using ajax.
I need multiple ids or classes to run the different queries. I've tried querySelectorAll with multiple ids (see below) and also getElementsByClassName() with multiple classes but the query returns undefined in the WHERE clause for both of these.
I can get it to work on one link using getElementById though.
What am I doing wrong?
Html:
<ul>
<li><a id="spquery" onclick='ajaxFunction()'>John</a></li>
<li><a id="spquery1" onclick='ajaxFunction()'>Jill</a></li>
</ul>
<div id='ajaxDiv'>Results will display here</div>
Javascript:
<script languspquery="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// below you can see I'm using querySelectorAll with multiple ids
var spquery = document.querySelectorAll('#spquery, #spquery1').text;
var queryString = "?spquery=" + spquery ;
ajaxRequest.open("GET", "/the-bootstrap/ajax-ped.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
The mysql query from /the-bootstrap/ajax-ped.php
$spquery = $_GET['spquery'];
$query = "SELECT * from people";
$query .= " WHERE personname = '$spquery'";
querySelectorAll will return an array of nodes. To use the value of each of the nodes you need to iterate the array like this
var arr_spquery = document.querySelectorAll('#spquery,#spquery1');
var spquery = '', sep='';
for(var i=0,len=arr_spquery.length; i<len; i++) {
spquery += sep + arr_spquery[i].innerHTML;
sep = ',';
}
console.log(spquery); /* optional - to log the value */
var queryString = "?spquery=" + spquery ;
ajaxRequest.open("GET", "/the-bootstrap/ajax-ped.php" + queryString, true);
ajaxRequest.send(null);
Then on the server side in php script you can use the string as you want. :)
I need the onkeyup to fire more than once, but it seems to be only firing once!
When I enter something into the input box, it searches, but then whenever I backspace and search something else, the div stay's the same..
Here is my code:
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'dam_search.php?dam_text=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
Here is dam_search.php
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
ALSO: I am wondering how I can put the return of the name's it has searched into a dropdown from the input box instead of into the div, so when I click on one of the names, it auto fills the input box.
Thank you!
Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.
The code requires that you download the AjaxRequest library I mentioned in an earlier comment.
(http://ajaxtoolbox.com/request/)
Here, I demo a few principles.
Arranging the data into a php class
constructing an array of instances of this class
returning this array as JSON
catching the JSON text and turning it back into an object in JS
Processing the data
I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.
The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!
Hope it's useful for you. Any questions, just ask. :)
1. jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
if (!isset($_GET['wildcard']))
$wildCard = "*.*";
else
$wildCard = $_GET['wildcard'];
foreach (glob($wildCard) as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. readDir.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/ajaxRequestCompressed.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function myGetAjaxResponseWithCallback(url, target, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target); }
}
);
}
function getResults1()
{
var url = "jsonDir.php";
var target = byId('resultsDiv');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}
function getResults2()
{
var url = "jsonDir.php?wildcard=*.png";
var target = byId('resultsDiv2');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}
function jsonDataReceived1(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mStr = "There were " + resultObject.length + " records returned" + "<br>";
var mSel = newEl("select");
mSel.addEventListener('change', doAutofill, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = mStr;
targetContainer.appendChild(mSel);
}
function jsonDataReceived2(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mSel = newEl("select");
mSel.addEventListener('change', showSelectedImg, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(mSel);
}
function doAutofill(e)
{
var curSelIndex = this.value;
var curText = this.options[curSelIndex].label;
byId('autofillMe').value = curText;
}
function showSelectedImg(e)
{
byId('previewImg').src = this.options[this.value].label;
}
</script>
<style>
img
{
border: solid 2px #333;
}
</style>
</head>
<body>
<button onclick='getResults1()'>Get *.* dir listing</button> <input id='autofillMe'/>
<div id='resultsDiv'></div>
<hr>
<button onclick='getResults2()'>Get *.png dir listing</button> <img id='previewImg' width='100' height='100'/>
<div id='resultsDiv2'></div>
</body>
</html>
Found out my problem. The query wasn't correctly being processed!
I had the variable $dam_text as the LIKE statement, when it should have been $dam:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
getSuggest($text);
}
function getSuggest($text) {
$dam = $_GET['dam_text'];
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!
OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();
To make sure your browser is working correctly try this
<script type="text/javascript">
function suggest1() {
document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
You should see the div change for every keystroke that occurs in the input.
There is two many unknowns for me to directly point at your actual issue.
Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup
T test to onkeyup on your system/browser:
Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).
Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/
Swapping out your PHP for the echo service works fine (with a bit of a typing delay)
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>