I'm trying to load an xml file using ajax. I tried to modify the example of W3Schools
<html>
<head>
<script>
function showBus(str) {
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", "getbus.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>Select your bus route:
<select name="NUMBER" onchange="showBus(this.value)">
<option value="">Select a Bus:</option>
<option value="102">102</option>
</select>
<div id="txtHint"><b>Bus info will be listed here...</b>
</div>
</form>
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("routes.xml");
$x = $xmlDoc->getElementsByTagName('NUMBER');
for ($i = 0; $i <= $x->length - 1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$BUS = ($y->childNodes);
for ($i = 0; $i < $BUS->length; $i++) {
//Process only element nodes
if ($BUS->item($i)->nodeType == 1) {
echo("<b>" . $BUS->item($i)->nodeName . ":</b> ");
echo($BUS->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
XML File:
<TT>
<BUS>
<NUMBER>102</NUMBER>
<DEPARTING_STOP>102</DEPARTING_STOP>
<DESTINATION>102</DESTINATION>
<TIME>102</TIME>
</BUS>
</TT>
This is what I get when I select the bus number from drop down menu:
Select your bus route:
load("routes.xml"); $x=$xmlDoc->getElementsByTagName('NUMBER'); for ($i=0; $i<=$x->length-1; $i++) { //Process only element nodes if ($x->item($i)->nodeType==1) { if ($x->item($i)->childNodes->item(0)->nodeValue == $q) { $y=($x->item($i)->parentNode); } } } $BUS=($y->childNodes); for ($i=0;$i<$BUS->length;$i++) { //Process only element nodes if ($BUS->item($i)->nodeType==1) { echo("" . $BUS->item($i)->nodeName . ": "); echo($BUS->item($i)->childNodes->item(0)->nodeValue); echo("
"); } } ?>
Open <yourserver>getbus.php?q=102 in your browser. Do you get something like this:
NUMBER: 102
DEPARTING_STOP: 102
DESTINATION: 102
TIME: 102
If you get something like:
load("routes.xml"); $x=$xmlDoc->getElementsByTagName('NUM...
I'd personally think you are not running an http server but are excuting everything locally.
Your getbus.php file is a php sourceode file that needs to be interpreted by a php processor. This is all being done by a webserver (if correctly configured). To get started you can use xampp ( https://www.apachefriends.org/ ) which has all the necessary modules for your sample. It is a preconfigured server to run php.
Then put all your files in the according htdocs folder in your xampp installation and the sample should work.
EDIT:
As it seems the getbus.php most of the time responses with an empty response. The problem apears to be the load(file) method by domdocument. loadXML seems to work better. So this always works for me:
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML("<TT>
<BUS>
<NUMBER>102</NUMBER>
<DEPARTING_STOP>102</DEPARTING_STOP>
<DESTINATION>102</DESTINATION>
<TIME>102</TIME>
</BUS>
<BUS>
<NUMBER>103</NUMBER>
<DEPARTING_STOP>104</DEPARTING_STOP>
<DESTINATION>105</DESTINATION>
<TIME>107</TIME>
</BUS>
</TT>");
$x = $xmlDoc->getElementsByTagName('NUMBER');
for ($i = 0; $i <= $x->length - 1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$BUS = ($y->childNodes);
for ($i = 0; $i < $BUS->length; $i++) {
//Process only element nodes
if ($BUS->item($i)->nodeType == 1) {
echo("<b>" . $BUS->item($i)->nodeName . ":</b> ");
echo($BUS->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
note that the entire XML file is now inside the PHP file as a string. To make it working the way you want you could try to load the file contents into a string using file() or file_get_contents() in the php file.
Related
I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
I managed to create a PHP loop that takes an array and create multiple copies of the same button while the buttons each have their own idenfication ("adiv_1" , "adiv_2", "adiv_3", etc). I have a javascript function that is able to take a single button "before it was called just 'adiv'" and change the text of the button if one clicks on it.
However due to the PHP loop which named it "adiv_1 or adiv_2 or adiv_3", I don't know how to create a javascript function that can take one of the buttons looped with a different identification div tag and get javascript to identify each one if one click on a certain button in that group. Can anyone help?
PHP loop that create the group of buttons
<?php
$array_query = mysql_query("SELECT * FROM person_finder_info");
$i = 0;
while($search_row = mysql_fetch_array($array_query)){
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i?>'>Add this person</div></button></p>
<?php
$i++;
}
?>
Javascipt / AJAX function that changes button text (by getting echoed information in PHP file)
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("adiv_1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
This is rudimentary, but I think you're trying to do something like this, just loop inside of the onreadystatechange function like you did in the other one to display what you want in there to handle all of the buttons.:
<?php
for($i = 0; $i < count($array); $i++)
{
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i;?>'>Add this person</div></button></p>
<?php
}
?>
<script>
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
<?php
echo "var divArray = {";
for($i = 0; $i < count($array); $i++)
{
echo "'adiv_".$i."'".($i < $count-1 ? "," : "");
}
echo "};" /// after the loop this will output like var divArray = {'adiv_1','adiv_2', ... };
?>
for (var i = 0; i < divArray.length; i++) {
document.getElementById(divArray[i]).innerHtml(dataFromResponse[i]); // assuming you've processed the response from AJAX into an array
}
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
</script>
I can't help you with setting up all of the button innerHTML though since I don't know what kind of response you're getting from AJAX. This is just to lead you in the right direction.
I have a script that rotates some images from their current position, there are 4 available rotations(positions) of the image and they are present by the values 0,1,2,3. My problem is that I need two variables from the database in my AJAX call to make this happen. I need the rotation and the src. My PHP currently look like this; Please notice the query where I take out rotation and src.
<?php
$item_number = -1; //This value is -1 in order to make the list start on 0
$rowsize = 12;
$itemArray = array();
$finalArray = array();
$results = 0;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, rotation, src, name FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ?');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $rotation, $src, $name);
while($stmt->fetch()) {
$results = 1;
$itemArray['number'] = $item_number;
$itemArray['name'] = $name;
$itemArray['ref_id'] = $z;
$itemArray['rotation'] = $rotation;
$itemArray['src'] = $src;
array_push($finalArray, $itemArray);
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
$item_number++;
}
if($results == 1){
aasort($finalArray,"ref_id");
foreach($finalArray as $arr){
echo '<li id="item-' . $arr['number'] . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $arr['name'] . '
<img class="rotate" id="img_'.$arr['number'].'" src="images/house/other/settings.jpg" onclick="rotateObject(this)" alt="'. $src.'">';
}
}
//create a function for sorting
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
?>
It then makes an AJAX call to this file:
function rotateObject(e)
{
//e is handler which contains info about the item clicked. From that we can obtain the image id.
//since the id are of the form img_123(some number), we need to extract only the number.
var img_id = e.id.split("_")[1];
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getEle = document.getElementsByClassName('item' + img_id)[0];
var imagePath ="images/house/objects/stone_chair_1.png"; //This has to be
getEle.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("item_id="+encodeURIComponent(img_id));
}
This code is then supposed to have the imagePath equal to src. and then the rotation after it, but I don't know how I can get the src for that specific image from the database query made in the PHP file.
Any suggestions or advice on how I can pass that value? Thanks in advance.
One way to pass variables from php to javascript is:
<script>
var myJavascriptVariable = <?php echo $myPhpVariable; ?>
</script>
Hope this help you
hi i have some ajax coding in which the if condition is not at all working, whenever the program executes else statement only works even the program satisfies the if statement.
<script type="text/javascript">
function CheckDetails()
{
var http = false;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
var rid = document.new_booking.ph_number.value;
http.onreadystatechange = function() {
if (http.readyState == 4) {
var str_d = http.responseText;
if (str_d == "no") {
document.getElementById('cus_name').focus();
} else {
var str_details = http.responseText;
var arr_details = str_details.split("~");
document.new_booking.cus_name.value = arr_details[0];
document.new_booking.pick_aline1.value = arr_details[1];
document.new_booking.pick_aline2.value = arr_details[2];
document.new_booking.pick_area.value = arr_details[3];
document.new_booking.pick_pincode.value = arr_details[4];
document.new_booking.drop_aline1.focus();
}
}
}
http.open("GET", "ajax.php?evnt=det&rid=" + rid);
http.send();
}
</script>
and its ajax.php file is given below
<?php
if ($_GET['evnt'] == 'det') {
$rid = $_GET['rid'];
include("configure.php");
$select = mysql_query("select * from new_booking where ph_number = '$rid'");
$count = mysql_num_rows($select);
if ($count > 0) {
$row = mysql_fetch_array($select);
echo $row['cus_name']
. "~" . $row['pick_aline1']
. "~" . $row['pick_aline2']
. "~" . $row['pick_area']
. "~" . $row['pick_pincode']
. "~" . $row['drop_aline1']
. "~" . $row['drop_aline2']
. "~" . $row['drop_area']
. "~" . $row['drop_pincode'];
} else {
echo "no";
}
}
?>
You can open your page with Chrome (or Chromium) and then debug your javascript code using builtin debugger (Ctrl+Shift+I, "Console" tab). I guess you will see some JS errors there.
Basically, your code works OK (at least when I removed all database access from it, since I don't have your DB).
If you don't like Chrome, use Firefox and FireBug extension. On 'Network' page you can see that your ajax request was executed (or not executed).
If I had to guess, I would say that some whitespace is sneaking into your AJAX response somewhere. Because "no " isn't equal to "no", it is always hitting your else branch.
You might consider sending back a whitespace-agnostic value. You could rewrite the whole mess to use JSON, which would require a lot less work on both ends:
// PHP:
if ($_GET['evnt'] == 'det') {
$rid = $_GET['rid'];
include("configure.php");
$select = mysql_query("select * from new_booking where ph_number = '$rid'");
$count = mysql_num_rows($select);
if ($count > 0) {
$row = mysql_fetch_array($select);
// YOU PROBABLY WANT TO WHITELIST WHAT YOU PASS TO JSON_ENCODE
echo json_encode($row);
} else {
echo json_encode([ "error" => "no" ]);
}
}
// js:
http.onreadystatechange = function() {
if (http.readyState == 4) {
var str_d;
try {
str_d = JSON.parse(http.responseText);
} catch(e) {
str_d = false;
}
if (str_d && str_d.error === "no") {
document.getElementById('cus_name').focus();
} else {
document.new_booking.cus_name.value = str_d.pick_aline1;
document.new_booking.pick_aline1.value = str_d.pick_aline2;
document.new_booking.pick_aline2.value = str_d.pick_area;
// etc...
}
}
}
I was having similar problem. This worked for me.
if (str_d.replace(/^\s+|\s+$/g, '') == "no")
For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.