Update several elements via Ajax from PHP array result - php

I am trying to generate some invoices based on user's input (date selection). That is something like this:
The invoice.php file would let the user select a date from a form, and based on that selection the contents of the invoice (like amount, customer, etc.) on that same page would be updated through Ajax.
The ajaxInvoice.php would generate a MySQL query and in the end create an array with the corresponding table row based on date selection and merchant (unique row).
invoice.php
...
<body>
<script language="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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var date = document.getElementById('date').value;
var merchant = document.getElementById('merchant').value;
var queryString = "?date=" + date + "&merchant=" + merchant;
ajaxRequest.open("GET", "ajaxInvoice.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
...
<form name="invoiceDate">
<input type="hidden" id="merchant" value="<?php echo $merchant; ?>" />
Date: <select id="date">
<option>2013-07-23</option>
<option>2013-07-25</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Select Date" />
</form>
...
<div id="field_1">FIELD 1</div>
...
<div id="field_2">FIELD 2</div>
...
<div id="field_3">FIELD 3</div>
...
ajaxInvoice.php
include_once('includes/db.php');
$merchant = $_GET['merchant'];
$date = $_GET['date'];
$merchant = mysql_real_escape_string($merchant);
$date = mysql_real_escape_string($date);
$query = "SELECT * FROM settlements WHERE datePayment = '$date' AND merchant = '$merchant'";
$result = mysql_query($query) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
I was wondering if I could have access to that array this way:
echo $array[0]['fieldName'];
and update selected elements on the page based on different row fields. Not sure if getElementById or getElementByName should be used.
My question would be how to actually access the php array within the script part and also within the rest of the page, so that I can update the various div elements with the corresponding data obtained from the DB query after the user selects the date from the form.
In fact, if only one div has to be updated, the code works just fine, but I don't know how to extend the logic to update more than one div.
Any help or hints on the syntax or code logic would be greatly appreciated.
Thank you very much in advance!

I usually use JSON:
PHP at the server: echo json_encode($array)
JavaScript on the client: var response = JSON.parse(ajaxRequest.responseText)
Implemented:
invoice.php
...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = JSON.parse(ajaxRequest.responseText);
// Now you can use:
response[0]['fieldName'];
// Like this
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = response[0]['field_1'];
}
}
...
ajaxInvoice.php
...
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
// Encode to JSON
echo json_encode($array);

Related

Alternative to innerHTML for IE select box

I have a problem that is php data not showing in select box. innerhtml not working in Internet Explorer. long_description_detail_list data not showing in select box.please help me
first page:
<div id="long_description_detail_list" style="display:none;">
<option value="0">Select..</option>
<?php
include_once('Model/Language.php');
$r = new Language();
$a = $r->Select();
for($i = 0; $i < count($a); $i++)
{
print '<option value="'.$a[$i][0].'">'.$a[$i][1].'</option>';
}
?>
</div>
<script language="javascript" type="text/javascript">
//Browser Support Code
function create_long_description_detail_div(){
if(count_table_long_description_detail() >=3) {
alert("You can not add more than 3 long_description Details");
}
else {
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var blank_long_description_detail = ajaxRequest.responseText;
document.getElementById('long_description_detail_counter').value ++;
$('#my-all-long_description_details-here').append(blank_long_description_detail);
set_new_height_of_step_2('inc');
var long_description_list_counter = document.getElementById('long_description_detail_counter').value;
var long_description_detail_list = document.getElementById('long_description_detail_list').innerHTML;
document.getElementById('llanguage[' + long_description_list_counter + ']').innerHTML = long_description_detail_list;
}
}
var long_description_detail_counter = document.getElementById('long_description_detail_counter').value;
var queryString = "?long_description_detail_counter=" + long_description_detail_counter;
ajaxRequest.open("GET", "Views/User/long_description/add_long_descriptions_detail.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
data not showing here in second page named add_long_descriptions_detail.php:
<select id="llanguage[<?php echo $counter; ?>]" name="llanguage[<?php echo $counter; ?>]" class="txtBox">
<option value="0">Select..</option>
</select>
IE doesn’t support updating the elements of a <select> with innerHTML, but what you can do is use the DOM, which is always the right way to go about things anyways.
Make your server-side script return a JSON array of options; it’ll make everything a lot easier.
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState === 4) {
// Parse the response
var options = eval('(' + ajaxRequest.responseText + ')');
// Get the box; I have no clue what this is
var box = document.getElementById('llanguage[' + long_description_list_counter + ']');
// Clear any current elements
while(box.childNodes.length > 0) {
box.removeChild(box.firstChild);
}
// Add new ones
for(var i = 0; i < options.length; i++) {
var newOption = document.createElement('option');
newOption.value = options[i].value;
newOption.appendChild(document.createTextNode(options[i].text));
}
}
};
(This is a little trimmed-down from your original code, but I’m sure you can fit it in.)
It’s also probably a good idea to use an old-IE-compatible JSON parser instead of eval.
The JSON should look like this:
[
{ "text": "Some text", "value": "some-value" }
]
You can use json_encode to produce it conveniently from a PHP array.

How to invoke PHP file in AJAX/JavaScript?

I have this code that GET the php file using an AJAX method. The goal is to inform the user if the movie table is empty or not. If the table is empty, it will display a confirm box that will ask if the user wants to add movies or not?
Here's my index.php file:
Movies
Here's my moviestbl.php:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
?>
<script language="JavaScript">
var option = confirm("No Movies found. Add Movies now?");
if(option ==true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
}
else{
//do nothing. return to current window.
}
</script>
<?php
}
?>
And finally, here's my AJAX file.
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
</script>
When I click the link, it is not doing or displaying anything. need help. thanks.
You will need to get the data from server using an ajax request , the response could be in JSON format.
Suggestions .
use jQuery and $.ajax - for pulling data from server
on getting the response - do the confirm and switch window
You can structure the logic to handle specific logics at client & server
PHP : logic on server could beCreate and interface for responding with JSON result for status of entries on movie table. your current query should work fine.
Javascript: Make use of the interface defined on php to to query data and make use of the 'confirm' javascript to do the switching.
Right now if you change
Movies
to
Movies
You should see it working with page reloads and redirects.
This will probably work better:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
echo "empty";
}
?>
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
if(XMLHttpRequestObject.responseText === "empty"){
var option = confirm("No Movies found. Add Movies now?");
if(option == true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
} else{
//do nothing. return to current window.
}
}
}
}
XMLHttpRequestObject.send(null);
}
</script>
I was able to make the code run now. Thanks to Firebug and coffee. The anchor tag is the problem. I don't know why, but when I used the img instead, it worked.
<img alt="movies" style="cursor:hand;cursor:pointer;" onclick="checkMovieTbl('/movies/ajaxphp/moviestbl.php')"/>
The PHP Script file:
<?php
//fetch the data from the table movies
include '../phpfunc/connect.php';
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
$json = json_encode($countRows);
if($json == 0){
echo $json;
}
?>
And lastly, the AJAX file.
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTbl(url){
//if not false
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("GET", url, false); //not sync
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var response = XMLHttpRequestObject.responseText;
//alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
if(response==0){
//execute something here
}
}
else{
alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
}
}
XMLHttpRequestObject.send();
}
}
Thanks to everyone who answered my questions and helped me. Chiao!

How to pass javascript variable to php in html? (wikipedia parsing)

Hi I'm trying to pass a javascript variable called $url to a function in php all located in the same html file. The logic here is that there is a text box and the user inputs a species and we call the wikipedia api to check if the input has a wikipedia page if it does I parse the page and bring the species info up, everything works independently 100% but I cant seem to connect them. However I cant get javascript to pass the url to the php function below. and innerHTML the php function with the url which is suppose to render the parsed species info. The error I get is that from the get go I just get the php function spit out with nothing.
Enter a species here : [text box here]
find('table.infobox'); foreach($html->find('img') as $element) { $image[]= $element; } Print $image[1]; $data = array(); foreach($table[0]->find('tr') as $row) { $td = $row->find('> td'); if (count($td) == 2) { $name = $td[0]->innertext; $td = $td[1]->find('a'); $text = $td[0]->innertext; $data[$name] = $text; } } print ""; foreach($data as $value => $before ) { print ""; } print "
$value $before
"; } ?>
Here is my attempt so far, I call the javascript and check if a link is found and call the parse function to innerthml out in the result div
<?php
//call the javascript
//if link found
//send ajax url variable to php function
//ajax call the function innerhtml in the result div
//We check if we have the param within the page call
$theDeletenode = false;
if(isset($_POST['deletenode']))
$theDeletenode = $_POST['deletenode'];
if($theDeletenode)
{
//The param 'deletenode' is given, so we juste have to call the php function "parse", to return the value
parse($theDeletenode);
}else
{
// No parametre, so we echo the javascript, and the form (without the quote and \n, it's much better)
?>
Here is the start of my html, the text box is connected to javascript which called the wikipedia api to check if the input has a wikipedia page.
<html><head>
<script type="text/javascript">
// create and return an XMLHttpRequest object
function createRequest() {
var ajaxRequest; // the xmlrequest object
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;
}
}
}
return ajaxRequest;
}; // end of createRequest
var spellcheck = function(data){
var found=false;var url='';
var text=data[0];
if(text!=document.getElementById('spellcheckinput').value) return;
for(i=0;i<data[1].length;i++)
{
if(text.toLowerCase()==data[1][i].toLowerCase())
{found=true;
url='http://en.wikipedia.org/wiki/'+text;
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';
}
}
if(!found)
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';
};
var requestone = createRequest();
var getjs= function(value)
{
if(!value) return;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck'; // this is the variable I want to pass
document.getElementById('spellcheckresult').innerHTML='Checking ...';
var elem=document.createElement('script');
elem.setAttribute('src',url);
elem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(elem);
// Ajax call to this page, this time with the 'deletenode' parameter
var vars = "url=" + encodeURIComponent(url);
requestone.open("POST", "parser.php", true); // parser.php : the name of this current page
requestone.onreadystatechange = handleRequest; // function to handle the response
requestone.send(vars);
};
function handleRequest()
{
//here we handle the php page response by echoing de result of the php page (normally the result of the parse function)
try{
if(requestone.readyState == 4 && requestone.status == 200)
document.getElementById('resultdiv').innerHTML= requestone.responseText;
} catch (e) {
//Wrong server answer...
}
};
</script>
</head>
<body>
<form action="#" method="get" onsubmit="return false">
<p>Enter a species here : <input id="spellcheckinput" onkeyup="getjs (this.value);" type="text">
<span id="spellcheckresult"></span></p>
</form>
<div id=resultdiv></div>
</body>
</html>
Here is my parse function which recieves a variable called url which is the validated wikipedia page and then it parses it for species info, this tested and it works but I cant get it to innerhtml this function along with the validated wikipedia url.
<?php
}
function parse($url){
print $url;
$html = file_get_html('http://en.wikipedia.org/wiki/Beaver');
$table = $html->find('table.infobox');
foreach($html->find('img') as $element)
{
$image[]= $element;
}
Print $image[1];
$data = array();
foreach($table[0]->find('tr') as $row)
{
$td = $row->find('> td');
if (count($td) == 2)
{
$name = $td[0]->innertext;
$td = $td[1]->find('a');
$text = $td[0]->innertext;
$data[$name] = $text;
}
}
print "<table class='infobox' style='text-align: left; width: 200px; font-size: 100%'>";
foreach($data as $value => $before )
{
print "<tr><td>$value</td><td>$before</td></tr>";
}
print "</table>";
}
?>
This question has many related answers 1234
If it helps, here is some JavaScript:
var form = document.createElement("form");
var input = document.createElement("input");
form.method="{post/get}";
form.action="{page}";
input.name="{name}";
input.value="{value}";
form.appendChild(input);
form.submit();

Sending Checkbox Values to PHP page using javascript Ajax and not jQuery

I have a situation in which i need to do insert queries for every check box selected through an ajax request sent to a php script which would do the insert in mysql.
i know how to do it without an ajax call via the simple form submission with a variable like groups[] as an array and running the foreach loop in php for every value in the array.
How do i send the array a via post ajax request?
a sample code:
<input type='checkbox' name='groups[]' value='1'>Group A
<input type='checkbox' name='groups[]' value='2'>Group B
<input type='checkbox' name='groups[]' value='3'>Group C
Please help, i know this might be easy but i am just not getting it. and guys, please don't give any example of jquery or the likes as i want pure html, javascript and php solution.
Thanks community...
Here's the Javascript function:
<script type='text/javascript'>
function addResp(tid){
a = encodeURIComponent(document.getElementById('course_add_resp').value);
b = encodeURIComponent(document.getElementById('term_add_resp').value);
c = encodeURIComponent(document.getElementById('paper_add_resp').value);
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&grp="+data;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('respBackground'));
document.body.removeChild(document.getElementById('respBox'));
contents = xmlhttp.responseText;
if(contents == "done"){
window.location = "teachers.php";
} else{
document.getElementById("studentBox").innerHTML = "There was a problem serving the request.";
}
}
}
xmlhttp.open("POST","assignresp.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
</script>
and the php script:
<?php
$tid = mysql_real_escape_string($_POST['tid']);
$cid = mysql_real_escape_string($_POST['course']);
$sem = mysql_real_escape_string($_POST['sem']);
$paper = mysql_real_escape_string($_POST['paper']);
$session = 12;
$type = 1;
$groups = $_POST['grp'];
foreach ($groups as $value ) {
$q1 = "insert into iars(sessionid,teacherid,courseid,semester,paperid,groupid,type) values('$session','$tid','$cid','$sem','$paper','$value','$type')";
$r1 = mysql_query($q1) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo "done";
}
else{
echo "fail";
}
}
?>
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data.join('&'));
//for get
//xmlhttp.open("GET",url+"?"+data.join('&'),true);
//xmlhttp.send();
EDIT
Change these two lines.
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&"+data.join('&');
$groups = $_POST['groups'];
you can do this with two way,
you can use the post type ajax call
You can get the all selected checkbox values with JavaScript make comma separated string and just pass it in one variable
that's all you can do .... :)

XMLHttpRequest returning in FF but not IE

I'm trying to do an AJAX call to pull back data to popluate a drop down box based off the select of another drop down box. My code is working fine in FF 9.0.1 (used for firebug), but failing in IE 7 (which is my company standard). I've tried several ways to show the data, and I don't have the time right now to learn how to do this in jQuery. I'm sure this will be a head smacker, but what about IE is causing this issue?
Here are my code pages. First is the trimmed down version of the form calling the JavaScript.
<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
<table align='left'>
<tr>
<td class='reporttd'>Vendor</td>
<td>
<select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
<option value='' selected='selected'></option>
<?php echo $vendorOptionList; ?>
</select>
</td>
</tr>
<tr>
<td class='reporttd'>Service Code</td>
<td class='reporttd'>
<select name='selServiceCode' id='selServiceCode'>
<option value='' selected='selected'></option>
</select>
</td>
</tr>
</table>
</div>
</div>
</form>
JavaScript page
//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlhttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new Activexobject(xmlHttpVersions[i]);
}
catch(e) {}
}
}
if (!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
//Call page to get all service codes for a vendor.
function getServiceCode(){
if (xmlHttp){
try{
var vCode = document.getElementById("selVendorCode").value;
var parms = "vCode=" + vCode;
//Call Transaction_AJAX.php to pass back an XML.
xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e){
alert("Can't connect to server:\n" + e.toString());
}
}
}
//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
handleServerResponse();
}
catch(e){
alert("Error reading the response: " + e.toString());
}
}
else{
alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
}
}
}
//Handles response from the server
function handleServerResponse(){
var xmlResponse = xmlHttp.responseXML;
if (!xmlResponse || !xmlResponse.documentElement){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == "parsererror"){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
xmlRoot = xmlResponse.documentElement;
if(rootNodeName != "root" || !xmlRoot.firstChild){
throw("Invalid XML structure:\n" + xmlHttp.responseText);
}
//Get response and load it into drop down
responseText = xmlRoot;
var sel = document.getElementById("selServiceCode");
sel.options.length = 0;
var opt = document.createElement("option");
document.getElementById("selServiceCode").options.add(opt);
for(var i=0; i < responseText.childElementCount; i++){
var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
sel.options[sel.options.length] = newOpt;
}
}
The PHP page creating the XML file
<?php
header('content-type:text/xml; charset=utf-8');
include("../includes/DBConn.php");
$vCode = $_GET['vCode'];
///Setup cursers and proc command
$curs = OCI_New_Cursor($c);
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");
OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);
//execute statment and cursors
oci_execute($stmt);
oci_execute($curs);
//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) {
//Add node for each row
$occ = $dom->createElement("cell");
$occ = $root->appendChild($occ);
//Id Value
$id = "value";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
//Id text
$id = "text";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();
//Echo XML back to Transaction_Update.js
echo $xmlString;
?>
Here is how you do it in jQuery
1) Include jQuery library in your head section of the page. (here i am refering it from the google cdn)
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
In your javascript
$("#stateDropDown").change(function(){
var stateId=$("#stateDropDown").val();
$.ajax({
url: 'getcities.php?stateid='+stateId,
success: function(data) {
$("cityDropDown").html(data);
}
});
});
Assuming you have a HTML select element with id "stateDropDown" for states and another one with id "cityDropDown" for cities.
The above code will do the follolwing
1) When the value of state dropdown changes, it executes the inside code.
2 ) Reade the selected item value and store it in a variable called stateId.
3) Using the jQuery ajax method , it makes a call to getcities.php page with a query string key called stateid
4) when we get a response from the ajax call, the control flow will be in the part called "success" handler. there we are receiving the response in a variable called data.
5) setting the received response (data) as the inner html of the city dropdown.
Assuming the getcities.php page will return some output like this
<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>
jQuery will take care of your cross browser issues. Yes its is well tested and everybody is using it.
http://www.jquery.com
You can change your for loop in handleServerResponse to the following to fix this issue:
for(var i=0; i < responseText.childNodes.length; i++){
var node = responseText.childNodes[i];
var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
var newOpt = new Option(text,value);
sel.options[sel.options.length] = newOpt;
}

Categories