Another way to display JS on PHP page? - javascript

i am retrieving some information from Google's API and placing them in a single variable, and then inserting them to a div in the DOM like so:
$(function() {
// Load the info via Google's API
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641/activities/public?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += '<article>';
html += '<img src="'+data.items[i].actor.image.url+'">';
html += '<p>'+data.items[i].title+'</p>';
html += '<p>'+data.items[i].published+'</p>';
html += '</article>';
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
My question is: is there a way to store every piece of information in each of its own variable, and then get the information individually by echoing the variable? So i dont have to hardcode all that HTML.

back in the days I would do:
<div id="google-posts-container">
<article>
<img src="{{image}}">
<p>{{title}}</p>
<p>{{published}}</p>
</article>
</div>
<script type="text/javascript">
// render a template (replace variables and return html)
function renderTemplate(tmpl, data){
for (k in data){
while(tmpl.indexOf('{{'+k+'}}') > -1){
tmpl = tmpl.replace('{{'+k+'}}', data[k]);
}
}
return tmpl;
}
$(function(){
// our template
var template = $('#google-posts-container').html();
$('#google-posts-container').html(''); // or clear()
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641"
+"/activities/public"
+"?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += renderTemplate(template, {
image : data.items[i].actor.image.url,
title : data.items[i].title,
publish : data.items[i].published
});
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
</script>
nowadays I use angularjs

About comment by 'galchen' - don't use angular.js for serious &(or) big projects. Just look at source code.
(can't add sub comment, thats why i wrote to main branch)

Related

Is it possible to search the contents of html files from another html page all within the same local directory?

So if given an offline webapp made up of html5/css/js with standard directories of {[Main Folder] > 0001.html, 0002.html, 0003.html, {[assets folder] > [css],[js],[media]}} is it possible for a search function on 1.html to be able to search the text content of 2.html or 3.html?
I haven't been able to find any specific information about this as most searching people do for a site are for sites intended to be houses on server, but in the case of an offline webapp the files are stored locally which causes a big hangup as webapi REALLY doesnt like a webpage looking at local files, but any images and links are able to be references through the href tag, so is it possible to search the contents of an html file specified through an href?
if given sample html pages:
0001.html
<!DOCTYPE html>
<body>
<div class="allSearch">
<div class="search">
<input type="text" id="searchInput" class="searchField"><button id="clear" class="clear">Clear</button>
<button type="button" id="button" class="searchButton">Search</button>
</div>
<div id="searchResults" class="results"></div>
</div>
</body>
0002.html
<!DOCTYPE html>
<body>
<div id="content">
<p>lorem ipsum</p>
</div>
</body>
Is it possible to search the contents of 0002.html while on 0001.html?
The reason i didn't include more robust markup and js above is that we are working on proprietary html ebooks built in InDesign and exported to html5. our current method of searching involves using a script in InDesign that parses every text box on every page and generates a dictionary that looks something like:
var searchDictionary = {
"Turtle": [1, 2],
"Fish": [2, 3],
"Fox": [3, 4],
"Snake": [4, 5],
"Dragon": [1, 5]
}
Where the content in "" is a term and the associated array are the page numbers that terms appears on, then you search that dictionary with the following js and return the page numbers that term appears on, which i coded up to pull in a pre-existing thumbnail and create a link to click through to the page:
document.getElementById("button").addEventListener("click", function () {
var query = document.getElementById("searchInput").value.toLowerCase();
var pages = searchDictionary[query];
if (pages === undefined) {
document.getElementById('searchResults').innerHTML = '<p style = \"text-align:center;width:100%\"> Term Not Found </p>';
}
else {
html = ""
html += '<ul>';
pages.forEach(showResults);
html += '</ul>';
}
}, false);
function gotopage(destinationpageNumber) {
var currentpagenumber = $('.page').attr('data-name');
currentpagenumber = parseInt(currentpagenumber);
destinationpageNumber = parseInt(destinationpageNumber.split(' ')[1]);
var distance = destinationpageNumber - currentpagenumber;
var offset = currentpagenumber - nav.current;
nav.to(nav.current+distance);
}
function showResults(value) {
var pageNum = value.toString();
var thumbMid = pageNum.padStart(4,0);
var thumb = '<img src=\"assets/images/pagethumb_' + thumbMid + '_0.jpg\" class=\"searchThumb\">';
var result = "<button id=\"goto\" + class=\"gotopagebutton\">pg. "+ value + "</br>" + thumb + "</button>";
html += '<li class=\"result\">' + result + '</li>';
document.getElementById('searchResults').innerHTML = html;
var gotopagebuttons = document.getElementsByClassName('gotopagebutton');
for (var i = 0; i < gotopagebuttons.length; i++) {
gotopagebuttons[i].addEventListener('click', gotopage.bind(null, gotopagebuttons[i].innerHTML));
};
}
You can make another file that could get the data from each of the files and attempt to filter it (https://www.w3schools.com/howto/howto_js_filter_lists.asp)
You can use fetch to open the file then use .text instead of .json. Then just search that text.
<script>
fetch('0002.html').then(function (response) {
return response.text();
}).then(function (html) {
console.log(html.includes("ipsum"))
}).catch(function (err) {
console.warn('Something went wrong.', err);
});
</script>

Place elements in a single div in jQuery

I am new to jQuery and I am working with an API to do the following.
Get Multiple values from the API like name, place, weather forecast etc.
I have a bootstrap structure with the following code:-
<div id="place_here" class="row">
</div>
I want to place the data that I get from the API in this DIV.
Only thing that I want to do is get put all that data into a single div and place that div into above row div to create a beautiful table like structure. Something like this:-
var str = '<div class="col-md-4">' + newoverview + '</div>';
(newoverview is a string from JSON that I get. However that is only a single value that I want to place in my div class = "col-md-4" tag above. I want to insert more values as well.
Problems:-
I cannot(or don't know) how to use global variable in JQuery. Whenever I log a variable value in console it give me a null . I know that's because JSON is asynchronous but I don't know a work around this.
I tried using multiple functions and passing values one by one and adding div by div. However that is not doing what I want to do and gives a messed up structure.
How can I collect all the required values that I get in a JSON and combine them in a single div and place it in a div in my HTML structure.
Edit:- Code
$(document).ready(function(){
$("#Search_Button").click(function() {
var name;
name = $("#value").val();
if(!name){
console.log("Enter a name");
}
search(name);
});
function search(name){
var url = "url_here";
$.getJSON(url,function(data){
$.each(data.results,function(i,j){
displayImage(j.path);
displayOverview(j.id);
});
});
}
function displayOverview(id){
var url = "url_here";
$.getJSON(url,function(data){
var overviewx = data.overview;
var newoverview='';
for(var x=0;x<overviewx.length && x<100 ;x++){
newoverview+=overviewx[x];
}
var str = '<div class="col-md-4">' + newoverview +
'</div>';
$("#place_here").append(str);
});
}
function displayImage(id){
var url = "url_here";
var str = '<img src="' + url + '"</img>';
$("#place_here").append(str);
console.log(str);
}
});
I want to place both(and maybe more) tags in a single div from displayOverview and from displayImage and place that div into my main HTML Structure.
This is just an exemple !
to prevent asynchronous processing,we use callbacks
function getItem(){
var dfd = jQuery.Deferred();
var url_to_json = 'json/test.json';
$.getJSON(url_to_json, function(data) {
dfd.resolve(data);
});
return $dfd.promise();
}
when you need a the response you just :
getItem.done(function(data){
console.log(data);
});

Javascript for loop running out of sequence

I have a confusing problem where a line of code in my function is running before a loop which is stated above it. In my HTML I have:
<textarea id="textBox"></textarea>
<button id="submitButton" onclick="parseData()">submit</button>
<div id="put"></div>
And my JS function is:
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
$("#put").html($("#put").html() + "<table>");
for (var i = 0; i < data.length; i++) {
$("#put").html($("#put").html() + "<tr>"+data[i]+"</tr>");
};
$("#put").html($("#put").html() + "</table>");
return;
};
The resulting html in $("#put") is this:
<table></table>
"SiO2 (%)Al2O3 (%)TiO2 (%)CaO2 (%)MgO2 (%) 8.21.25.31.51.8 45.32.52.60.210.5 65.23.48.70.0662.3 20.11.85.42.540.2 18.91.12.34.810.7"
I'm not sure why the final </table> is being placed before the for loop runs, and I'm not sure why the <tr> tags aren't being added within the for loop. Any pointers?
jQuery automatically closes up tags upon insertion. Try this.
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
var put_html = $("#put").html() + "<table>";
data = data.split(tab);
for (var i = 0; i < data.length; i++) {
put_html += "<tr>"+data[i]+"</tr>";
};
put_html += '</table>';
$("#put").html(put_html);
return;
};
However, I notice that you aren't using <td> elements. You might want to look into fixing that too.
Every time you are adding content into the html() property rather than building the entire content and adding it.
Since you are using jQuery you can bind the event using jQuery rather than adding that directly in the HTML
<textarea id="textBox"></textarea>
<button id="submitButton">submit</button>
<div id="put"></div>
$(function(){
$("#submitButton").click(function(){
parseData();
});
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
// Build your html
$("#put").html('htmlstructure');
return;
}
});
Also you can look for something similar like concatenating the string in an array so that you don't create string isntances each time when you append, since strings are immutable.
Good example

Dynamically creating unique link or button for each result of a database query result

Basically, a list of results from a database query is inserted into a ul. I want the user to be able to click the result they are looking for and then have one of two things happen:
A unique link is created (such as a php GET request) using the ID of
the selected result
A JS function is called via the onClick
attribute, and the ID of the clicked result is sent as an argument.
The code below is what I have done so far - minus the functionality that I listed above.
The list as it is in the HTML:
<ul data-role="listview" id="treesUL" data-inset="true" style="visibility: hidden">
<li id="treesLI">
<div class="resultNames">
<span class="donorName">Donor</span>
for
<span class="honoreeName">Honoree</span>
</div>
<div class="resultInfo">
<span class="treeName">common</span>
on:
<span class="donationDate">Date</span>
</div>
<div class="resultDedication">
<span class="dedicationText">Dedication</span>
</div>
</li>
</ul>
The javascript that edits the list, based on the results of the query which is stored in the myTrees array. This function is called via a XMLHttpRequest object.
function showTreeContent()
{
if (requestObj.readyState == 4) //Request completed
{
//Retrieve the JSON encoded array, which is stored at index-key: media
var text = requestObj.responseText;
//alert(text);
var myTrees = jQuery.parseJSON(text).media;
$('#treesUL').text('');
//Alert the number of rows, for testing purposes
alert(myTrees.length + " results.");
//Loop through the JSON array, and add each element to a <li>, which is then added to the <ul>
for(var i = 0; i < myTrees.length; i++)
{
var tree = myTrees[i];
var li =$('#treesLI').clone();
li.removeAttr('id');
li.appendTo('#treesUL');
//li.find('.treeLink').setAttribute("href", "somelink url");
li.find('.donorName').text(tree['donor']);
li.find('.honoreeName').text(tree['honoree']);
li.find('.dedicationText').text("'" + tree['dedication'] + "'");
if (tree['common'] != '')
li.find('.treeName').text(tree['common']);
else
li.find('.treeName').text("Unknown Species");
li.find('.donationDate').text(tree['date']);
li.data('treeID','tree'+i);
}
}
}
I tried surrounding the contents of the li tag with an a tag, and then editing the href of the a tag, but I was unable to get that to work. I'm using jQuery Mobile for this project also. Let me know if you need any more information - any help is greatly appreciated!
First thing that I see strange is that you are calling $('#treesUL').text(''); that deletes the contents of the ul and than in the loop you request $('#treesLI') which was deleted above.
What i would do is create the HTML as a string and append it to the ul.
Example.
var html = '';
for(var i = 0, length = myTrees.length; i < length; ++i)
{
var tree = myTrees[i];
html += '<li class="treesLI" onClick="somefunction('+ tree.id+')">';
html += '<div class="resultNames"><span class="donorName">' + tree.donor + '</span>';
html += 'for <span class="honoreeName">'+ tree.honoree + '</span></div>';
html +='</li>';
$('#treesUL').append(html);
}
As you can see i added an onClick handler that calls a function that receives a parameter.
You can use that onClick function to make a GET request with $.axaj()
If you don't want to use onClick you can do:
$('#treesUL li').click(function(event){
});
Some other observations:
You can access the properties of an object using the . like this tree.dedication.
You should do your for like this for(var i = 0, length = myTrees.length; i < length; ++i)
it is 2 times faster in IE8

How to display images using Javascript and JSON

I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>

Categories