Ajax mysql query based on link text with multiple links on page - javascript

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. :)

Related

Where to put a loading icon in this ajax form please anyone tell me?

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 = '';

radio button values send using ajax php mysql

Please help me with this.
It could be a duplicate question, but I couldn't find the solution anywhere.
I am creating an objective type questionnaire and the options are in radio buttons. Some of the options are mandatory and if the user click that option the comment box will change to a required field. The name of the answers are the question Id. Here is the input field which I am using
<input type='radio' name='answer_value[<?php echo $gques; ?>]' value='<?php echo $gans; ?>' id="rtr" onclick='ajaxFunction()'/>
I want to do it with ajax, because when the user select the mandatory option it has fetch the answer id and use that id to execute a query to check whether that answer is mandatory or not. If true it will make the comment box a required text area. The ajax code I used is
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var ans_id = $("input[id=rtr]:checked").val();
var dataString = 'id='+ ans_id;
alert(dataString);
ajaxRequest.open("POST", "anschq.php" +dataString,true);
ajaxRequest.send();
}
In the anschq.php I put an alert script to check whether the value is sent or not. But when I click on the radio button the alert box is not displayed from the other page.
But the alert(dataString) here is displaying the value of the checked button.
Can anyone find the solution for this problem.....
This is not a GET request. You have to pass the data in the body of the response not in the url (see RFC).
Replace:
ajaxRequest.open("POST", "anschq.php" + dataString, true);
ajaxRequest.send();
by
ajaxRequest.open("POST", "anschq.php", true);
ajaxRequest.send(dataString);

Retrieve from database using PHP and pass to javascript as JSON

I am creating a weather widget using javascript . In this widget the user can select the town they wish to see and the widget will display outlook , min and max temperature without refreshing using ajax . I have stored the city information in a database and had written PHP script to retrieve the data and pass it to js as JSON object
<?php
/**************************
* code to connect to your database here
*/
$con = mysqli_connect("localhost", "user", "pass");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:".mysqli_connect_error();
}
mysqli_select_db("weather", $con);
$town = $_GET['town'];
/***************************
*
* Query the DB for weather information for the given town.
*
* A PHP array object containing the weather data.
* Return a JSON encoded version of the array to the browser.
*
*/
$sql = "SELECT * from weather where town = $town";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$arr = array(
"town" => $row[town],
"outlook" => $row[outlook],
"min_temp" => $row[min_temp],
"max_temp" => $row[max_temp]
);
}
echo json_encode($arr);
mysqli_close();
?>
And in js i want to show the weather only for selected town . How to parse the JSON object to get only the information of the town selected by the user . Like
if(jsondata == "sydney")
return "sydney information";
I did this using DOJO as
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
// The method that handles the request's successful result
// Handle the response any way you'd like!
load: function(result) {
data = result;
}
});
return data;
}
However , i dont want to use dojo . how do i do that . Any suggestions ?
Suppose you have a select tag with id "town".
<select id="town" onchange="handler(this)"></select>
Now, for the Javascript part. You need to use XMLHttpRequest to make an ajax call.
function handler(elem){
var tname = elem.value;
var request_url = "PHP/weather.php?town=" + tname;
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Some error occured");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
//Update your page here
}
}
http_request.open("GET", request_url);
http_request.send();
}
<body>
<div id="townInfo">
<div id="town"></div>
<div id="outlook"></div>
<div id="min_temp"></div>
<div id="max_temp"></div>
</div>
<script>
var town = document.getElementById('town');
var outlook = document.getElementById('outlook');
var min_temp = document.getElementById('min_temp');
var max_temp = document.getElementById('max_temp');
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
load: function(result) {
data = result;
town.innerHtml = data['town'];
outlook.innerHtml = data['outlook'];
min_temp.innerHtml = data['min_temp'];
max_temp.innerHtml = data['max_temp'];
}
});
</script>
</body>
warning: not tested

ajax form issue: cannot get data from a select multiple

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

XML Parsing with Javascript

I have an XML file which consists of multiple records and I want to display all of them on one page. I have written some code but it's not helping me out.
Here some tags are optional so how I can I show "--" in that optional tag where it is not appearing?
XML File
<doctors>
<doctor specialization="Gynaecologist">
<name>Alex Mashkin</name>
<bachelor_degree>MBBS</bachelor_degree>
<master_degree>Master in Gynaecology</master_degree>
<experience>7 Years</experience>
<available_timings>12PM to 5PM</available_timings>
<fees>500</fees>
<operation_charges>20000</operation_charges>
<special_visit_charges>1000</special_visit_charges>
</doctor>
<doctor specialization="Sergeon">
<name>Dazy Deepy</name>
<bachelor_degree>MBBS</bachelor_degree>
<master_degree>Master in Surgery</master_degree>
<experience>10 Years</experience>
<available_timings>11AM to 2PM</available_timings>
<fees>900</fees>
<operation_charges>25000</operation_charges>
<special_visit_charges>1800</special_visit_charges>
</doctor>
<doctor specialization="Dentist">
<name>Mona Bralia</name>
<bachelor_degree>BDS</bachelor_degree>
<experience>3 Years</experience>
<available_timings>4PM to 8PM</available_timings>
<fees>300</fees>
<special_visit_charges> 600</special_visit_charges>
</doctor> </doctors>
HTML Code
(snippet)
<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", "XMLFile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("doctor");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getAttribute("specialization"));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("bachelor_degree")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("master_degree")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("experience")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("available_timings")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("fees")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("operation_charges")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("special_visit_charges")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
So, you want to iterate all <doctor> elements, and check the children of each. That means you can't just get all xmlDoc.getElementsByTagName("master_degree") from the document and think it's ith item would match the current doctor, as some doctors do not have a <master_degree> elemenent. Instead, check it for each of them by applying getElementsByTagName on the doctor itself, and count how many master degrees you have selected (might be none, might be more than one?).
// a mapping from HTML ids to XML tag names, to make it more programmatical
var map = {dname:"name", bdegree":"bachelor_degree", mdegree:"master_degree", exp:"experience", availibity:"available_timings, fee:"fees", opcharge:"operation_charges", spcharge:"special_visit_charges"};
// and from HTML ids to XML attribute names of the doctor
var attrmap = {spec:"specialisation"};
… // load XML etc - you should do it asynchronous, btw
var doctors = xmlDoc.getElementsByTagName("doctor"),
doctorCount = doctors.length;
for (var i=0; i<doctorCount; i++) {
var doc = doctors[i];
for (var id in map) {
var elements = doc.getElementsByTagName(map[id]),
var result = "";
if (!elements.length)
result = "---";
for (var j=0; j<elements.length; j++)
if (elements[i].firstChild)
result += elements[i].firstChild.data;
document.getElementById(id).innerText += result;
}
for (var id in attrmap) {
document.getElementById(id).innerText += doc.getAttribute(attrmap[id]);
}
}
After lot of research I have find out shortest way to iterate all the elements with attribute.
Here is the code:
<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", "XMLFile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
y=xmlDoc.documentElement.childNodes;
for (i=0;i<y.length;i++)
{
if (y[i].nodeType!=3)
{
//This code for printing attribute of a tag(you have to give attribute name).
document.write("<br>" + y[i].getAttributeNode('specialization').nodeName + ": ");
document.write(y[i].getAttributeNode('specialization').nodeValue + "<br>");
for (z=0;z<y[i].childNodes.length;z++)
{
if (y[i].childNodes[z].nodeType!=3)
{
//This is for Node Name.
document.write(y[i].childNodes[z].nodeName + ": ");
//This is for Node Value.
document.write(y[i].childNodes[z].textContent + "<br>");
}
}
}
}
</script>

Categories