Create Hyperlinks through Json Document - javascript

I apologize in advance if this is a really simple request that has already been answered and I am just too unfamiliar with javascript to understand.
I would like to create a json catalog that displays on an HTML page as a table and I would like for one of the cells to be a hyperlink, but I can't figure out how to do that.
Here is my json script:
"beer": [{
"name": "NAME",
"type": "TYPE",
"company": "BREWERY",
"website": "WWW.SITE.COM",
"price": 6.00
}],
and this is my HTML script
<script>
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","catalog.json",false);
xmlhttp.send();
json=JSON.parse(xmlhttp.responseText);
document.write("<table class=table table-bordered>");
var x=json.beer;
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].name);
document.write("</td><td>");
document.write(x[i].type);
document.write("</td><td>");
document.write(x[i].company);
document.write("</td><td>");
document.write(x[i].website);
document.write("</td><td>$");
document.write(x[i].price.toFixed(2));
document.write("</td></tr>");
}
document.write("</table>");
</script>
Can anyone help with this

First off, don't use document.write. If called after the page is done loading, it will erase the entire page. Better to use DOM methods to add new elements.
Second, AJAX is (supposed to be) asynchronous, why are you passing false to .open()? (P.S. I doubt anyone is gonna be accessing this site with IE5/6, so you can lose the new ActiveXObject)
// In 2014, this is all that's really needed
var xhr = new XMLHttpRequest;
// The callback to run when the request is done
xhr.onload = function(){
// readyState 4 means the request is done, and 200 is HTTP OK
if(xhr.readyState === 4 && xhr.status === 200){
var json = JSON.parse(xhr.responseText),
// The data we want to loop over
x = json.beer,
// This is how to make a new element
table = document.createElement('table');
// Set the classes
table.className = "table table-bordered";
// Loop over your data
for(var i = 0; i < x.length; i++){
// Create the HTML for this row
var row = '<tr>' +
'<td>'+x[i].name+'</td>' +
'<td>'+x[i].type+'</td>' +
'<td>'+x[i].company+'</td>' +
// For a hyperlink, just use an `<a>` tag
'<td>'+x[i].website+'</td>' +
'<td>'+x[i].price.toFixed(2)+'</td>'+
'</tr>';
// Let's just simply append to the table's innerHTML
table.innerHTML += row;
}
// Add the table to the page
document.body.appendChild(table);
}
};
// This defaults to being *asynchronous*
xhr.open("GET","catalog.json");
// Start the request
xhr.send();

Related

Concurrent AJAX requests not working. Newest request overwrites previous request

My webpage features a table where each row has a "+" button so that a mini table appears. The mini table houses data from a super slow database so I am having the data come in through ajax requests. My problem is rooted in a certain situation. Suppose you pressed a plus button causing an AJAX request and while waiting you press another plus button. The second ajax request causes the first request to never come back. In other words the newest request overwrites all previous pending requests. Any idea why this might be happening? I feel like this might just be what happens when you don't use jQuery to handle AJAX but I am not sure and I couldn't find anything that said that was the case. I am appending my code below. Any help is appreciated!
function fetchSINamesForVariantAJAX(latestBuild, variantToExpand){
if (latestBuild == "") {
//document.getElementById(subTableId).innerHTML = "";
return;
}
else {
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) {
spinner.stop();
var variantRow = variantToExpand + "Row";
if (document.getElementById(variantRow).rows.length == 1){
var json = JSON.parse(xmlhttp.responseText);
var SINames = json['SIs'];
var locations = json['locations'];
var SIBuilds = json['SIBuilds'];
for (var i = 0; i < SINames.length ; i++){
var row = document.getElementById(variantRow).insertRow(-1);
var cell = row.insertCell(-1);
var SILinkURL = "exampleWebsite.com/name.php?names=" + SINames[i];
cell.innerHTML = "" + SINames[i] + "";
cell = row.insertCell(-1);
var fullLocation = locations[i] + "\\" + SIBuilds[i];
cell.innerHTML = "" + fullLocation + "";
cell = row.insertCell(-1);
cell.innerHTML = "";
}
}
}
}
//create the GET message to be sent using AJAX window
var stateToSend = "SITableGeneratorFromVariant.php?";
stateToSend += "latestBuild=" + latestBuild;
xmlhttp.open("GET", stateToSend, true);
xmlhttp.send();
}
}
I think the reason is that you overwrite your xmlhttp variable with a new one each time a new AJAX call gets done try declaring it inside the function:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Parse JSON array in javascript to pHp and mysql - no jQuery

I have a JSON Object getting a list of images I have on the page. The images are generated at random using a database. I want to keep adding to the images using AJAX whn the user for example clicks "show more". The images src are found so that no duplicates are pulled from the database on the AJAX call.
I want to know how to parse this array to the pHp file to perform an SQL statement to get more images to append to the images list. In the php file how would I select the elements from there. So SELECT * FROM images WHERE image_src NOT IN (JSON array) ORDER BY rand() LIMIT 12
CODE
var imageArray = {};
imageArray.itemList = [];
function imagesLoaded(){
var gal_img_thumbs = document.getElementsByClassName("gal-thumb-image");
for (var i = 0; i < gal_img_thumbs.length ; i++){
var img = gal_img_thumbs[i].firstChild.getAttribute("src");
var new_obj = {'src':img};
imageArray.itemList.push( JSON.stringify(new_obj));
//imageArray.itemList.[i]['src']=img;
}
}
function loadImages(){
console.log("load images");
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","getimages.php?imgArray="+imageArray.itemList,true);
xmlhttp.send();
}

How do I create an HTML select box with results from a PHP search through AJAX?

Here is some background: I have a text file that is broken down into context blocks. Each block has a header of a pattern "[header]". So far, I have been able to create a php script that will search for these headers and generate a list of only the headers.
What I have not yet been able to figure out is how to supply these results to a web page that will take this list and generate a drop-down/select box with the list as options. Here is the php script:
<?php
$theList = array();
$theInFile = 'extensions.conf';
$theLine = '';
$theReturnString = '';
$inFile=fopen($theInFile, 'r') or exit('Unable to open file.');
while(!feof($inFile))
{ $theLine = fgets($inFile);
$theLine = (string)$theLine;
// Is it a context header?
// Check for the presence of a '[', then the position of '['
// This method is used due to STRPOS returning ZERO if not found,
// which is the position we are looking for.
$x = strstr($theLine, '[');
if ($x != '')
{ $y = strpos($theLine, '[');
if ($y == 0)
{ // Only the context name itself is wanted.
// If there is anything after the ']', strip it.
$end = strlen($theLine);
$tBracket = strpos($theLine, ']') + 1;
if($end != $tBracket)
$theLine = substr($theLine, 0, $tBracket);
$theReturnString = $theReturnString.$theLine.'~';
}
}
}
fclose($inFile);
echo $theReturnString;
?>
The following HTML page is as far as I have gotten. It will at least get the return string separated into a list of headers, but I am at a loss as to how to get that list into a select / drop-down box:
<!DOCTYPE html>
<html>
<form id="StartingPage" action="GetList.php" method="post">
</form>
<head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var received;
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange=function()
{ var newString = new Array();
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ received = document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
received = received.split('~');
for ( i = 0; i < received.length; i++ )
document.writeln(received[i] + '<br>');
document.writeln('Done.<br>');
}
}
xmlhttp.open("GET","GetList.php",true);
xmlhttp.send();
}
</script>
And and all advice and critiques are appreciated.
First, I think it would be better if you parse your file with regular expressions for performance reasons.
Then, prefer JSON for the response, it will be easier for you to read it with Javascript. JSON is also a good choice because it allows you to easily change your script (adding items) without requiring to change the way to parse the responses from Ajax requests.
Following regex will search for contents between "[" and "]".
<?php
$content = file_get_contents('extensions.conf');
preg_match_all('~\[(.+)\]~Usmx', $content, $headers, PREG_PATTERN_ORDER);
echo json_encode($headers[1]);
Now, for the client side, we parse response with JSON.parse() method and put it into select box by creating option elements with document.createElement.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form id="StartingPage" action="GetList.php" method="post">
<select name="mySelectName" id="mySelectId"></select>
</form>
<script>
function loadXMLDoc()
{
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var mySelect = document.getElementById('mySelectId');
var headers = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < headers.length; i++) {
var option = document.createElement('option');
option.setAttribute('value', i);
option.innerHTML = headers[i];
mySelect.appendChild(option);
}
}
}
xmlhttp.open("GET", "GetList.php", true);
xmlhttp.send();
}
loadXMLDoc();
</script>
</body>
</html>
Hope it helps !
If I understood the question right, you need to display select with options from that array .. this should work :
<!DOCTYPE html>
<html>
<form id="StartingPage" action="GetList.php" method="post">
</form>
<head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var received;
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange=function()
{ var newString = new Array();
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ received = document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
received = received.split('~');
var select = document.createElement("select");
select.setAttribute("name", "mySelect");
select.setAttribute("id", "mySelect");
var option;
for ( i = 0; i < received.length; i++ )
{
/* create options elements */
option = document.createElement("option");
/* You can change i with received[i] if you need your options with values equal to displayed text */
option.setAttribute("value", i);
option.innerHTML = received[i];
select.appendChild(option);
}
// Append the select to the end of the body tag
document.body.appendChild(select);
// Or You can use something like this also
// document.getElementById("myDiv").appendChild(select);
}
}
xmlhttp.open("GET","GetList.php",true);
xmlhttp.send();
}
</script>

Questions to create a nested list retrieved from an XML-file and displayed in xHTML

The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html

Getting a file from a server using Javascript

So, I wrote some JavaScript to grab an xml file from my desktop and display it on an html page. However, I now have added my xml file to a webserver (mongoose). I want to call the file from that server, but whenever I call the file from the server it dosen't work, but when I call it from my desktop it loads fine.
I want to swap
xmlhttp.open("GET","Devices.xml",false);
with
xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);
Here is the code
<html>
<head>
<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","Devices.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// the <Device> list
x = xmlDoc.getElementsByTagName('Device');
// make a function that extracts the attributes out of a Node
function getDeviceAttributes(dvc) {
var name = dvc.getAttribute("name");
var uuid = dvc.getAttribute("uuid");
var id = dvc.getAttribute("id");
return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>";
}
// loop through the list
// assuming order doesn’t matter
var txt = '';
for (var i = x.length; i--;) {
txt += getDeviceAttributes(x[i]);
}
//show the result on page load
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
</script>
</head>
<body>
<div id='showDevices'></div>
</body>
</html>
Does anyone know how I can get this to work?
I have been told to use AJAX and Jquery, but I have no idea how to or even where to begin.
It looks like you are repeating a lot of work that jQuery can do for you. Check out the documentation for the Get request method
So something like this:
$.get('http://localhost:8080/Devices.xml', function(data) {
$('#showDevices').html(data);
});
I believe that is the jQuery for what you are trying to do. Hope that helps.
-Charlie
Just some generic advice, you could also use the .load() ajax function if you didn't want to parse the response and this:
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
can be done in jQuery like this $("#showDevices").html(txt);

Categories

Resources