Ajax return value using with PHP - php

Hi I'm having some problems making my function structure. Would appreciate any help.
First this function should delete map markers once OnChange event is triggered from index.php.
And send post values to xmlmapquery.php for data retrieval.
once retrieved, The data should be stored back to my index.php in <div id='content'>
function filter()
{
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
var lgu = $('#lgu').val();
var category = $('#category').val();
var type = $('#type').val();
$.get('xmlmapquery.php', { filter: lgu, filter2: category, filter3: type},function(data){
$('#content').text(data);
)};
};
Now this is xmlmapquery.php
<?php
include('connection_db.php');
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
if(isset($_POST['filter']) && isset($_POST['filter2']) && isset($_POST['filter3'])){
$query = "SELECT * FROM markers WHERE type='".$_POST['filter']."' and type='".$_POST['filter2']."'
and type='".$_POST['filter3']."'";
}
// Select all the rows in the markers table
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']);
}
echo $dom->saveXML();
?>
Would appreciate help on this. currently the function is NOT working even deleting the markers is not working. Once i get this thing working I will add more commands to the function that would get data and create new markers for my map. Thanks in advance.

Suppose your script logic is ok, and no die() or other php methods are returning null or false (anyway you should see in your browser console).
Things to do are:
1 - check firebug/chrome/browser console when launching request (if the request is hidden in some way use the "save" request method in console to check that)
2 - use var_dump($dom->saveXML()); instead of echo $dom->saveXML();
3 - check server/php logs when possible
4 - be sure your request uirl is complete and working and i'm referring to $.get('xmlmapquery.php');
if you follow this line of debugging, unless ghosts doesn't exists, you will be able to run your script easly.
Hope it will help

Related

Use XML generated from PHP file vs a physical .xml file

I hope I am asking this the correct way and thanks in advance for any advice! I have been trying to utilize this tutorial for a part on my own site:
https://developers.google.com/maps/documentation/javascript/mysql-to-maps
After trying many versions of my own code unsuccessfully, I decided to go ahead and step by step walk through the tutorial - even creating a new MYSQL DB exactly like in the tutorial...
In the tutorial example, they use an actual .xml file to read the data from:
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
However, just like the commented line says above the code "PHP File" - meaning you could use a PHP file there instead of an .xml file which would then dynamically generate the XML code based on the DB query.
They show 3 different ways to get the XML code from the DB and I have tried all 3 ways with the same exact results.
When I run the index.html page I get just the map showing up with no markers at all
If I run just the php file that generates the XML code, nothing shows up in the browser (just a blank white page) -- HOWEVER -- when I view the page source, it shows me the XML perfectly!
If I take that generated XML from my PHP file and copy/paste it into an .xml file and then call that .xml file in the downloadurl function, it all works perfectly!
So, therein lies my question.
What piece am I missing that would allow me to use the PHP file to dynamically generate the XML versus needing a separate XML file in my directory too.
The code I am using is the same exact code they have in the tutorial page.
Thanks in advance!!
EDIT - here are the 2 php pages. The convert-xml.php is for generating the info from MYSQL db. It's, getting the info from the db because when I view source it shows the xml tree like it should be. It;'s just not writing it to the browser or working in the downloadurl function to display the markers on the map.
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Using MySQL and PHP with Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var customLabel = {
restaurant: {
label: 'R'
},
bar: {
label: 'B'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.863276, 151.207977),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('convert-xml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_IS_HERE&callback=initMap">
</script>
</body>
</html>
convert-xml.php
<?php require 'conn-info.php';?>
<?php
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false
$dom->formatOutput = true;
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// connect to db
$membermap_conn = mysql_connect($membermap_server, $membermap_user, $membermap_password, $membermap_database);
if ($membermap_conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $membermap_conn->connect_errno . ") " . $membermap_conn->connect_error; }
// select the db
$db_selected = mysql_select_db($membermap_database, $membermap_conn);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Pull the zip / user information out of the database.
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// Add to XML document node
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id",$row['id']);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']); }
echo $dom->saveXML();
?>

The Curse of XML and PHP Whitespace

I am having an issue with DOMDocument and whitespace. Currently I have two types of XML files. One file was created manually about a year ago, I will call this file A. The second file, file B, is being generated using a PHP DOMDocument. I have been trying very hard (unsuccessfully) to make the whitespace in file A match file B.
Here's how it works... The user is given an option to add new <Slide> elements to the XML file. After new slides have been added the user has the option to add new <Items> to the XML file as a child of the <Slide> element.
When I add a <Slide> element to file B it works like a charm. I can even add a new <Item> element with zero problem. However, when I try to access the new <Identifier> element I just added in file B using the second PHP script below with $order != 'remove' I miss the node by one and select <Information/> instead.
It appears that manually created file A has white space that is not present in my generated file B. I have experimented with the preserveWhitespace property but it did not help.
Are there any suggestions on how I can correct this problem. Constructive criticism is also welcome as this is my first shot at dynamic XML manipulation. I apologize for the length and appreciate your time!!
File A - Created Manually - I am trying to match this file!
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Areas>Head & Neck</Areas>
<Area>Head & Neck</Area>
<Type>Angiograph</Type>
<Slide>Ag-01a
<Title>Catheter Angiography</Title>
<Item1>
<Identifier interestCoord=".51,.73" locator="point" labelBool="true" labelTxt="" leaderBool="true">Aortic Arch
</Identifier>
<Information/>
<Question A="" B="" C="" D="" E="" Answer=""/>
</Item1>
.... More Items
File B - Before user adds <Slide>. This portion is created Manually. A template if you will. After the user enters slide names new slides are generated using the chunk of code below.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Areas>Head & Neck</Areas>
<Area>Head & Neck</Area>
<Type>Brain Sections</Type>
</root>
File B - After users adds new <Slide> and <Item>. Formatting shown represents formatting created by DOMDocument. I think this is where the error is occuring! Whitespace!!!
<Slide>Ag-09a
<Title>Catheter Angiography</Title>
<Item1><Identifier locator="point" interestCoord="0.143,0.65" labelBool="true" labelTxt="" leaderBool="false">Orbit</Identifier><Information/><Question A="" B="" C="" D="" E="" Answer=""/></Item1></Slide>
PHP script used to add new <Slide> elements to XML
<?php
session_start();
//Constants
$SECTION_SEP = "========================================================================</br>";
//Variables used to construct file path
$area = trim($_POST['area']);
$slideType = trim($_POST['slideType']);
$rawSlides = trim($_POST['theseSlides']);
$newSlideList = explode(",", $rawSlides);
$fileLocation = "../XML/".$area."/".$slideType."/".$area.".XML";
$dom = new DOMDocument();
echo('New DOMDocument created!</br>');
$dom->load($fileLocation);
echo('XML file loaded!</br>');
/*$dom->preserveWhiteSpace = false;
echo('White space removed!</br>');*/
$dom->documentElement;
echo('DOM initialized!</br>');
if ($dom->getElementsByTagName('Slide')->length == 0){ //New file with no slides
foreach ($newSlideList as $slide){
$newSlide = $dom->createElement('Slide', $slide);
$newTitle = $dom->createElement('Title', 'Scan');
//Add the title element to the Item
$newSlide->appendChild($newTitle);
$dom->childNodes->item(0)->appendChild($newSlide);
echo($slide." has been added to the list!</br>");
}
} else {
$locators = $dom->getElementsByTagName('Slide');
}
if($dom->save($fileLocation)){
echo("File saved successfully!!");
}else echo("There was a problem saving the file!");
PHP script used to add/edit/remove <Item> and <Identifier> nodes depending on value of $orders == WARNING! Lengthy :/
<?php
session_start();
//Constants
$SECTION_SEP = "========================================================================</br>";
//Variables used to construct file path
$area = trim($_POST['area']);
$slideType = trim($_POST['slideType']);
$fileLocation = "../XML/".$area."/".$slideType."/".$area.".XML";
//echo("File location:".$fileLocation);
//Current data (c_ for current)
$c_poi = "";
$c_type = "";
$c_lblBool = "";
$c_lblOverride = "";
$c_leaderBool = "";
//Determine if this visit is for new or old data
$orders = trim($_POST['orders']);
//Variables used to replace information in XML file loaded below (n_ for new)
$n_slideName = trim($_POST['slideName']); //slide name in view format ie Ag-01a
$n_identName = trim($_POST['ident']); //contains multiple information separated by comma ie 0,Aortic Arch
$n_type = trim($_POST['type']); //locator type
$n_poi = trim($_POST['poi']);
$n_lblBool = trim($_POST['lblBool']);
$n_lblOverride = trim($_POST['lblOverride']);
echo("Modified: ".date('c')."</br>");
$dom = new DOMDocument();
echo('New DOMDocument created!</br>');
$dom->load($fileLocation);
echo('XML file loaded!</br>');
/*$dom->preserveWhiteSpace = false;
echo('White space removed!</br>');*/
$dom->documentElement;
echo('DOM initialized!</br>');
$locators = $dom->getElementsByTagName('Slide');
echo($locators->length.' elements retrieved</br>');
$slideEntryFound = false;
$identEntryFound = false;
$identAttributesFound = false;
echo($SECTION_SEP);
//Locate the correct slide node
foreach ($locators as $locator){
//If there is a match, store the infomation
// rawSlide[x].childNode[0].nodeValue
if(strcmp(trim($locator->childNodes->item(0)->nodeValue),$n_slideName) == 0){
$slideEntryFound = true;
$slideChildren = $locator->childNodes;
//Locate the correct identifier node
foreach($slideChildren as $child){
if( strcmp(trim($child->nodeValue), substr($n_identName,strpos($n_identName,",")+1)) == 0){
$identEntryFound = true;
if (strcmp($orders, "remove") == 0){//Removing an element
echo("The identifier being removed is: ".trim($child->nodeValue."</br>"));
echo("The node path is: ".($child->childNodes->item(1)->getNodePath())."</br>");
echo($SECTION_SEP);
$locator->removeChild($child);
echo("Identifier successfully removed!</br>");
echo($SECTION_SEP);
break;
} else {//Not removing anything - Adding or Editing
echo("The identifier being modified is: ".trim($child->nodeValue."</br>"));
echo("The node path is: ".($child->childNodes->item(1)->getNodePath())."</br>");
echo($SECTION_SEP);
if($child->childNodes->item(1)->hasAttributes()){
$identAttributesFound = true;
$c_poi = $child->childNodes->item(1)->getAttribute('interestCoord');
echo("--Current interestCoord: ".$c_poi."</br>");
echo("++New interestCoord: ".$n_poi."</br>");
if(strcmp($c_poi, $n_poi) != 0){
$child->childNodes->item(1)->setAttribute('interestCoord',$n_poi);
}
$c_type = $child->childNodes->item(1)->getAttribute('locator');
echo("--Current locator: ".$c_type."</br>");
echo("++New locator: ".$n_type."</br>");
$c_lblBool = $child->childNodes->item(1)->getAttribute('labelBool');
echo("--Current labelBool: ".$c_lblBool."</br>");
//echo("++New labelBool: ".$n_lblBool."</br>");
$c_lblOverride = $child->childNodes->item(1)->getAttribute('labelTxt');
echo("--Current labelOverride: ".$c_lblOverride."</br>");
echo("++New labelOverride: ".$n_lblOverride."</br>");
$c_leaderBool = $child->childNodes->item(1)->getAttribute('leaderBool');
echo("--Current leaderBool: ".$c_leaderBool."</br>");
//echo("++New leaderBool: ".$n_leaderBool."</br>");
if($n_lblOverride != ""){
echo("**A new label override was detected. The identifier will have the alias ".$n_lblOverride.".");
}
break;
} else echo("Fatal Error - Node does not contain attributes!</br>");
if($identEntryFound == true && $identAttributesFound == false)
echo("Error - Attribute entry not found!");
break;
}
}
}
if($slideEntryFound == true && $identEntryFound == false && $orders != "remove"){
echo("The identifier was not found... creating a new identifier!</br>");
//Create a new Element
$newElement = $dom->createElement("Item".((integer)(substr($n_identName,0,strpos($n_identName,",")))+1));
echo("New element created!!</br>");
//Create new Item children
$newSubElem = $dom->createElement("Identifier", substr($n_identName,strpos($n_identName,",")+1));
$newSubElem->setAttribute('locator',$n_type);
$newSubElem ->setAttribute('interestCoord',$n_poi);
$newSubElem->setAttribute('labelBool', $n_lblBool);
$newSubElem->setAttribute('labelTxt', $n_lblOverride);
//TODO link this next one to a variable instead of hard coding
$newSubElem->setAttribute('leaderBool', "false");
//Info Child
$newInfoElem = $dom->createElement("Information");
//Question Child
$newQuestion = $dom->createElement("Question");
$newQuestion->setAttribute('A', "");
$newQuestion->setAttribute('B', "");
$newQuestion->setAttribute('C', "");
$newQuestion->setAttribute('D', "");
$newQuestion->setAttribute('E', "");
$newQuestion->setAttribute('Answer', "");
//Add new children to main Item
$newElement->appendChild($newSubElem);
$newElement->appendChild($newInfoElem);
$newElement->appendChild($newQuestion);
$locator->appendChild($newElement);
echo("New identifier added!!</br>");
break;
}
} else {
}
}
if($slideEntryFound == false)
echo("Error - Slide entry not found!");
if($dom->save($fileLocation)){
echo("File saved successfully!!");
echo('<div id="phpHandleBtns>"></br><form><button type="submit" id="continueEdit" formaction="../edit.php">Continue Editing</button>'.
'</br><button type="submit" id="doneEdit" formaction="../main.php">Done Editing</button></form></div>');
}else echo("There was a problem saving the file!");
?>
I would strongly recommend that you use an XPath API like this http://php.net/manual/en/class.domxpath.php to find the nodes you are interested in. Attempting to use the DOM API directly is only going to cause you heartache.
More specifically, I think that your call to childNode() is getting tripped up by white space, but if you used childElement() instead (not sure if that exists, but with XPath it is easy), it would just ignore any whitespace.

passing html id to php/mysql, receiving 'cannot read property __e3_ of undefined'

I'm making a Google Map that will pull information from a database and output xml to be interpreted into markers on the map. I want to pass the clicked elements id into the PHP to filter the database results. When the function is executed, I get an error stating "cannot read property '_e3' of undefined". Everything works fine when I get rid of the variable and directly enter a type into the code.
relevant jQuery
$(document).ready(function() {
$('.map_item').toggle(
function() {
var itemid = this.id;
$.ajax({
type: 'POST',
//php script takes info from database, outputs xml
url:'SQL.php',
//pass var to the php to select only items matching this id
data: 'variable1=' + itemid,
success: function(data) {
relevant PHP from file SQL.php
$ajax_var = $_POST['variable1'];
$query = 'SELECT * FROM location WHERE Type="' . $ajax_var . '"';
$result = mysql_query($query); //sqlsrv_query
header('Content-type: text/xml');
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement('marker');
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("dirtType",$row['dirtType']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
}
echo $dom->saveXML();
I would say that the data should be sent in a different way, like this:
data: {
"variable1": itemId
}

Fetching image using xpath or some other way

I need to fetch the image from a remote page, i tried xpath but i was told it wont work because img does not have nodevalue
Then i was advised to use getAttribute, but i dont know how to get it working.
Any suggestions?
This is my code
<?php
libxml_use_internal_errors(true);
//Setting content type to xml!
header('Content-type: application/xml');
//POST Field name is bWV0aG9k
$url_prefix = $_GET['bWV0aG9k'];
$url_http_request_encode = strpos($url_prefix, "http://");
//Checking to see if url has a http prefix
if($url_http_request_encode === false){
//does not have, add it!
$fetchable_url_link_consistancy_remote_data = "http://".$url_prefix;
}
else
//has it, do nothing
{
$fetchable_url_link_consistancy_remote_data = $url_prefix;
}
//Creating a new DOM Document on top of pre-existing one
$page = new DOMDocument();
//Loading the requested file
$page->loadHTMLFile($fetchable_url_link_consistancy_remote_data);
//Initliazing xpath
$xpath = new DOMXPath($page);
//Search parameters
//Searching for title attribute
$query = "//title";
//Searching for paragraph attribute
$query1 = "//p";
//Searching for thumbnails
$query2 = "//img";
//Binding the attributes to xpath for later use
$title = $xpath->query($query);
$paragraph = $xpath->query($query1);
$images = $xpath->query($query2);
echo "<remotedata>";
//Echoing the attributes
echo "<title-render>".$title->item(0)->nodeValue."</title-render>";
echo "<paragraph>".$paragraph->item(0)->nodeValue."</paragraph>";
echo "<image_link>".$images->item(0)->nodeValue."</image_link>";
echo "</remotedata>";
?>
you should get source attribute of an image tag.
$images->item(0)->getAttribute('src');
if this is normal xhtml, img has no value, you need the value of img/#src

Load images to a TileList from Mysql using PHP and XML on Flash CS5

I have a mysql database with a table containing PATH's to images.
I want to load al the images to a TileList. Now i have this in PHP:
<?PHP
mysql_connect("localhost", "root", "root");
mysql_select_db("prototipo");
$result = mysql_query("select entretenimiento_id, e_nombre, e_imagen from entretenimiento");
echo "<?xml version=\"1.0\" ?><entretenimiento>";
while($row = mysql_fetch_assoc($result))
{
echo "<e_nombre>" . $row["e_nombre"] . "</e_nombre>";
echo "<e_imagen>" . $row["e_imagen"] . "</e_imagen>";
}
echo "</entretenimiento>";
?>
This is supposed to fetch me the PATH of the image, the name so it goes on the label of the tile that displays the image, and brings me also the id so i can launch another query when that image is clicked on.
All this is set into a dynamically created XML.
Now my question.... How do i load this??? What to do o AS3?? I already have the AS3 for the tilelist, i only need to load this dynamically created XML from PHP to it.
Thanks in advance. And sorry if i messed up on english, its not my main language. Im South American.
I have a partial answer:
var path:String = "http://localhost/entretenimiento.php";
xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
xmlLoader.load(new URLRequest(path));
function onLoadComplete(e:Event):void {
var xmlData:XML = new XML(e.target.data);
//trace(xmlData);
for (var i:int=0; i<xmlData.*.length(); i++)
{
myTileList.addItem({label:xmlData.e_nombre[i], source:xmlData.e_imagen[i]});
//trace(xmlData.e_nombre[i]);
}
}
Althought this shows me the images and the titles on the tiles, i also get two more tiles that are empty, and in the trace they are shown as "undefined". Any thoughts to why is this?
Here is a sample code that should works :
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
// change the path of your php file
xmlLoader.load(new URLRequest("your-file.php"));
function showXML(e:Event):void
{
var entretenimiento:XML = new XML(e.target.data);
// for each row :
for (var x:XML in entretenimiento.loc)
{
// Change the name of your tilelist
myTileList.addItem({label:x.e_nombre, source:x.e_imagen});
}
}

Categories