Hy!
I am very new in Web-Dev. I have a mysql db and the controller is made with PHP.
I give the data formated in php back to the html.
My Quest:
How to parse the xml in js right for the HTML based view?
If there are better solutions for the data transfair between PHP and HMTL, please let me know.
I don't wont the have HTML code in the php
Example PHP:
<?php
$id = $_GET['id'];
if (is_numeric($id))
{
include 'db_connect.php';
$sql = "Select * from RECIPES WHERE recipes_id=".$id;
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
while($row = mysql_fetch_array($result))
{
echo "<RECIPE>";
echo "<ID>" . $row['recipes_id'] . "</ID><br />";
echo "<TITLE>" . $row['text'] . "</TITLE><br />";
echo "<TEXT>" . $row['text'] . "</TEXT><br />";
echo "<COUNT_PERSONS>" . $row['count_persons'] . "</COUNT_PERSONS><br />";
echo "<DURATION>" . $row['duration'] . "</DURATION><br />";
echo "<USER_ID>" . $row['user_id'] . "</USER_ID><br />";
echo "<DATE>" . $row['date'] . "</DATE><br />";
echo "</RECIPE>";
}
}
else
{
echo "<ERROR>ID ERROR</ERRORR>";
}
mysql_close($db);
?>
thx
If you just want to transfer data between the browser and the server then it's simpler to use the JSON format. For PHP there are two built in function to decode and encode JSON: json_decode and json_encode.
Modern browser support JSON by default: JSON.parse and JSON.stringify.
I agree with styrr, but if you must use XML then you can use jQuery.parseXML() or simply use jQuery.ajax() with correct type eg.:
$.ajax({
url: "script.php?parameters=abc",
dataType: "xml",
success: function(responseDocument){
var all_ids = responseDocument.getElementsByTagName('ID');
var all_ids_jquery_way = $('ID', responseDocument);
}
});
You can use any othe AJAX framework or even write your own function. Browsers can parse XML and create a document which you can then change as the main document (with DOM functions).
Again with most data JSON is a bit simpler to use and is lighter.
Related
I am tryaing to to make this echo work, but i cant get the grip of it
echo '<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class="sml" src="$1" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);';
echo "</script>";
What am i doing wrong? i think i got something wrong with my " ' .
There was a couple of issues. I started by just running it in JavaScript until I got it to work, then moved it into PHP (for the sake of sanity).
<?php
print '
<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&\/\/=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class=\"sml\" src=\"$1\" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);
</script>';
?>
Shouldn't the regex be something like:
(^|\b)((https?:)?\/\/[^\s]*?\.(jpe?g|png|gif))(\b|$)
Debuggex Demo
You shouldn't be echo'ing scripts, especially scripts in script tags. I would seriously look into just using your back end to fetch, then use an asynchronous technology that fetches data parsed JSON. That way you can call your scripts normally.
i want to load XML data into my php file with address data.
Each address should also have coordinates - if not they should be added. So i am doing the following:
$xmlDatei = "AddressData.xml";
$xml = simplexml_load_file($xmlDatei);
for($i=0,$size=count($xml);$i<$size;$i++){
if($xml->RECORD[$i]->ADDRESS->LAT != NULL){
//get lat and lng stuff here...
$lat = .......
$lng = .......
echo "lat: " . $lat; // Test echo WORKING
echo "lng: " . $lng;
// Now i want to add the data to the xml
$xml->RECORD[$i]->ADDRESS->addAttribute('LAT', $lat);
$xml->RECORD[$i]->ADDRESS->addAttribute('LNG', $lng);
$xml->saveXML();
}
// Test echo NOT WORKING
echo $xml->RECORD[$i]->ADDRESS->LAT;
echo $xml->RECORD[$i]->ADDRESS->LNG;
}
So it seems like the addAttribute is not working properly here.
What am I doing wrong???
Your echo is looking for a child element called LAT:
echo $xml->RECORD[$i]->ADDRESS->LAT;
But you have added an attribute, so you need to use different syntax:
echo $xml->RECORD[$i]->ADDRESS['LAT'];
You are adding attributes to the ADDRESS tag, not nodes.
Try this:
echo $xml->RECORD[$i]->ADDRESS['LAT'];
echo $xml->RECORD[$i]->ADDRESS['LNG'];
Basically what I have is, there is an index file, that links to a JS file, which then pulls in a PHP file.
So in the PHP file I have (along with other code) :
echo " <script type='text/javascript'>var paging = [ ";
echo "{";
echo "numrows:'" . number_format($numrows) . "',";
echo "pagenum:'" . number_format($pagenum) . "',";
echo "maxpage:'" . number_format($maxpage) . "',";
echo "record_min:'" . number_format($record_min) . "',";
echo "record_max:'" . number_format($record_max) . "'";
echo "}];</script>";
Then, in a JS file I use ajax:
req.open("GET", "server.php", true);
and within the readystatechange I need to retrieve that paging variable you see from the php file because it contains data from the database.
In the JS file I have tried using a variable instead of echo
var m=<?PHP echo $paging; ?>
but that doesn't work either.
Any suggestions or ideas how to get this to work?
I'd use JSON instead of JS. You should be able to pass a PHP array to the json_encode function. See: http://php.net/manual/en/function.json-encode.php
Also, on the PHP side, you may want to modify your response headers to indicate that the response message body is JSON:
header( 'Content-Type: application/json' );
Then, use jQuery to get the JSON from the server: http://api.jquery.com/jQuery.getJSON/
Another possible solution for you if you don't get direct JSON working (scaled down to two variables)
echo '<div id = "numrows">'. number_format($numrows) . '</div>';
echo '<div id = "pagenum">'. number_format($pagenum) . '</div>';
in the php file
req.onreadystatechange = function(){
if (req.readyState == 4 && req.status == 200){
document.getElementById('return').innerHTML = req.responseText;
}
}
req.open("GET", "server.php", true);
req.send();
n["numrows"] = document.getElementById("numrows").innerHTML;
e = document.getElementByID("numrows");
e.parentNode.removeChild(e);
n["pagenum"] = document.getElementById("pagenum").innerHTML;
e = document.getElementByID("pagenum");
e.parentNode.removeChild(e);
in the javascript
<div id = "return" style="display: none;"></div>
in the html
Not the most elegant solution, but fairly straightforward to follow if you can't get anything else working.
Ok because jQuery makes this easy, here is my example:
$paging = array(
"numrows" => number_format($numrows),
"pagenum" => number_format($pagenum),
"maxpage" => number_format($maxpage),
"record_min" => number_format($record_min),
"record_max" => number_format($record_max)
);
$output = json_encode($paging);
header( 'Content-Type: application/json' );
echo $output;
Then in your javascript page using jquery do this:
function myCallBackFunction(data){
alert(data.numrows);
}
$.getJSON('server.php',myCallBackFunction(data));
Hope this helps.
Edited to use array and json_encode
I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")
Input is a URL like this http://ws.geonames.org/children?geonameId=6255148 and I would like to receive the XML file in a SimpleXMLElement for example?
Try this as your base point:
<?php
$xml = simplexml_load_file("http://ws.geonames.org/children?geonameId=6255148");
//print_r($xml);
foreach($xml->geoname as $geo)
{
echo $geo->toponymName . "<br />";
}
?>