loading images from json file with jquery - javascript

So I have a json file which now loads text and images individually pretty fine, this is just a simple example of what I did to test if it would work:
outputc+="<li>"
outputc+=this.name+" "+this.price+"</li>";
$('#featured').append(outputc);
$("<img/>").attr('src',this.images).appendTo('#featured');
Using the above code works perfectly however i need for both of these to be wrapped with a list, so I did some searching and I found this:
$(document).ready(function(){
//loading json file
var url = "shoppingItems.json";
$.getJSON(url,function(json){
$.each(json.shoppingItem,function()
{
var output ='<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>';
});
$('.items').append(output);
});
});
The above jQuery doesn't bring back anything at all, there isn't anything wrong with my json file as it's been validated and the code works if I simply alert it. This is potentially something I must be doing wrong with my output script which I can't see.
My JSON file can be found here: Json file not loading or showing alerts

Since you declare it inside the callback function as var output, the output variable is local to that callback function and vanishes once the loop is completed. Even if that wasn't the case, the use of the = operator would mean you were overwriting the previous value with each iteraction.
Try this:
var output = ""; // initialize it outside the loop
$.each(json.shoppingItem,function()
{
output += '<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>';
});
$('.items').append(output);
http://jsfiddle.net/mblase75/zB5fv/

Related

DOM changes in jQuery .get() success callback not reflected in page

This is my first question here and I'm totally stumped. Basically, I have a cart page that looks like this:
The site works by customers uploading images for printing, so each order is actually an image. Each cart item is generated dynamically using JS DOM functions, but the part I'm having trouble with is the row below the "Item #1" header row. It's supposed to contain a thumbnail of the order image (uploaded by the customer), which I get from a Laravel API endpoint. It returns a base64 string of the image, which I set as the image source like this:
var tbody = document.createElement('tbody');
var productImageRow = document.createElement('tr');
var productImageTD = document.createElement('td');
var productImage = document.createElement('img');
productImageTD.colSpan = 2;
if (order.productType == PRODUCT_TYPES.CONDUCTION_PLATES) {
/* Some irrelevant code here... */
} else {
$.get(<API Endpoint here>, function(data) {
productImage.src = data;
});
}
productImageTD.appendChild(productImage);
productImageRow.appendChild(productImageTD);
tbody.appendChild(productImageRow);
The problem is, even if I change the image src, it's not reflected in the browser (hence the empty row below the table header).
I am sure that the API is working because I do this exact same thing in another page and it works fine. Aside from that, if I log the base64 string in the data variable to the console and directly place it in the html like
<img src="<my base64 string>">
it displays the image fine, so I'm sure the base64 string is valid.
I also know that the success block is being executed because alerts inside it execute. When tested further, any DOM Manipulation done inside the callback doesn't get reflected in the browser. Example:
var DOMTest = document.createElement('h1');
DOMTest.innerHTML = "Before Callback";
productImageTD.appendChild(DOMTest);
...
$.get(<API Endpoint here>, function(data) {
//productImage.src = data;
DOMTest.innerHTML = "After Callback"
alert(DOMTest.innerHTML);
});
The result is that the page still displays the h1 as "Before Callback", but the alert shows the innerHTML as "After Callback". I tested this on Safari and Chrome.
I'm pretty sure I might just be making some stupid mistake. Any ideas? I'm totally lost here.

External JavaScript file is not defined

For a web project, I've included a JavaScript file as a script src, as shown here.
<script src="xml2json.js"> //same directory as the web project
Next, I tried to invoke a method within xml2json, called xml_str2json.
downloadUrl("ship_track_ajax.php", function(data) {
var xml_string = data.responseText; //an XML string
//A parser to transform XML string into a JSON object is required.
//Use convert XML to JSON with xml2json.js
var markers = xml2json.xml_str2json(xml_string);
}
However, console log indicates "Uncaught ReferenceError: xml2json is not defined", even though xml2json is included as a script src. Can anyone tell me as to what is wrong?
You have to call the function directly in javascript without reffering the filename as like
xml_str2json(xml_string);
If the function is defined in any of the included file it will be invoked.
I hope this will solve your problem
Maybe you should try this:
var json = xml2json(parseXml(xml), " ");
See Demo from https://github.com/henrikingo/xml2json

Append the js code inside js file dynamically and execute

Suppose I have a code in string format:
var str = "var a = 10;b = 20;console.log(a+b);";
I need to append this string value to the existing js file(say test.js) dynamically. And also get the result or execute it.
* However, I can load the string in separate and execute it, but that's not what i need. Thanks for your kind help and advice.
You can do it as :
for example in text file you will call a function where you want to append the code as :
test.js ->
// some javascript code
myFunction();
// some javascript code
Now in main file create this function as :
var execuationCode = "var a = 10;b = 20;console.log(a+b);";
function myFunction(){
setTimeout(execuationCode, 0);
}
When nyFunction call in test.js file then it call this main file function

read value from txt file in javascript

I have a simple html file in which there's javascript code referring to google charts.
The code I use is this (I'll show the important part):
function drawChart(){
var data = google.visualization
.arrayToDataTable([ ['Label', 'Value'],['Temp', 22.75],]);
// etc...
}
I use a bash command (sed) to replace that 22.75 value with a new one from the last line of a .txt file. However, this throws some errors which I haven't been able to neither correct nor ever identify.
So is there any javascript code that takes that file, extracts the last value and simply displays it on the right place of the code?
UPDATE:
Sorry for the lack of info in this question, I really appreciate all the people that took the time on reading my question. I'll try to fill with more information in the next minutes.
I am able to extract the last line of the .txt file, extract the value on the right part of the '-' symbol and store it in a variable. Then that value is taken to update the html file with a sed command. The error comes when the value is updated but with no value. I guess that happends due to a failed record of temperature in the txt file, then the extracted value is a null. Finally is the html fiel with javascrit code happens to be like this:
(...)['Temp', ],]);
Then the updater can't update the value since due to the way that sed command is written I guess there's no way that it can detect a no-number-value in there. So the html remains without a value all the time.
TXT File structure:
(...)
20:25:03-23.312
20:26:02-23.312
20:27:03-23.375
20:28:03-23.375
20:29:02-23.375
20:30:02-23.312
Bash script:
# (...code...)
lastRecord=`cat /home/pi/scripts/temp_control/logs/"$today".log | awk 'END{print}'`
function rightNow {
lastTemp=`echo $lastRecord | cut -d'-' -f2`
timeOfTemp=`echo $lastRecord | cut -d'-' -f1` # Not used yet
#Command used to update
sed -i "s/['Temp', [0-9]\{1,2\}.[0-9]\{1,3\}]/$lastTemp]/" /var/www/rightnow.html
}
rightNow
You cud get your file just like any other ajax request.
Using javascript
var request = new XMLHttpRequest();
request.open('GET', 'public_path_to_file.txt', false);
request.send();
var textFileContent = request.responseText
Using jQuery
var textFileContent;
$.get('public_path_to_file.txt', function(data) {
textFileContent = data;
});
Whats left is to get the right part from textFileContent. Dependent of the structure of the file we can do this in different ways. Without an example file you are on your own but here is some examples.
If you need the last line
var lines = textFileContent.split("\n");
var lastLine = lines[lines.length - 1];
If you need to use regex
var regex = //* some regex to get your content*//gm;
var result = regex.exec(textFileContent);
// result should now the content who matches your regex
First I'll assume that you ultimately want to read a local file with your browser and your current workflow is something like a local 'bash-script' that
first updates/modifies an inline piece of javascript (inside a locally stored html
file) with the last occurring value retrieved from a local txt-file (using sed)
opens the (just modified html-) file (via commandline) inside a common browser.
Then I assume the sed-route once worked but now doesn't work anymore (probably because the html file has changed?) and now you'd like the inline javascript (in the html file) to fetch that value from the textfile itself and subsequently use it (thus without the need for the 'bash-script'/sed solution.
Thus, the answer (based on above assumptions) to your final question: 'is there any javascript code that takes that file, extracts the last value and simply displays it on the right place of the code?', depends on your final requirement:
are you ok with a file-input where you select the text-file every time you view the html-file?
If your answer is YES, then, (depending on the browser you use) you can read a local file (and work your magic on it's contents).
In modern browsers, using the File API (which was added to the DOM in HTML5) it's now possible for web content to ask the user to select local files, then read the contents of those files.
For example, using FireFox's 'FileReader' you could do:
html:
<input type="file" id="fileinput" multiple />
javascript:
function readAllFiles(evt){
var files = evt.target.files, i = 0, r, f;
if(files){
for(; f = files[i++]; ){
r = new FileReader();
r.onload = (function(f){
return function(e){
alert(e.target.result);
};
})(f);
r.readAsText(f);
}
} else {
alert("Error loading files");
}
}
document.getElementById('fileinput')
.addEventListener('change', readAllFiles, false);
Note that for accessing local files in Chrome you must start Chrome with this switch: chrome --disable-web-security
However,
if the answer is NO (so you want to specify the file, and more importantly it's path, inside the 'code', so you don't have to select the text-file every time your local app runs) then you (usually) can't (because you can't get/set the path, thank the great maker)...
Unless you choose a specific older/unpatched browser (specifically for this task) where you know of a (hack) way to do this anyway (like the IE xml vulnerability or the XMLHTTP vulnerability or etc... you get the picture..).
Some alternative solutions (that don't require you to select the correct textfile over and over again)
Setup a fullblown web (LAMP) server (to use the XMLHttpRequest way as used in aross answer, but this might feel like shooting at a mosquito with a cannon..)
Explore different script languages (but effectively still do the same as your now broken sed-solution)
Combine 1 and 2, choosing from php (the latest version has a small webserver included, you might start/stop it when needed (even in the bash-script workflow) OR using node.js (which is 'javascript' and where you can program/control a small task-specific server in just a couple of lines).
Hope this helps!
Update:
Based on your updated question, comments and request for recommendation, I'd like to suggest to use PHP to dynamically fetch the value from your log txt file and have it generate your html code with inline javascript on the fly (every time you visit the page).
The browser will never see the php code, only what php inserted to your page (in this example the last found value or 0).
You'd rename the rightnow.html file to rightnow.php and modify it (something like) this:
<!DOCTYPE html>
<html><head>
<!-- your header code -->
<script type="text/javascript">
//parts of your javascript
<?php // start php script
$logFile= '/pathToYour/logFile.log'; // <-Modify
if( $fp= #fopen($logFile, "r") ){ // if logfile succesfully opened,
fseek($fp, -30, SEEK_END); // set pointer 30 chars from EOF
$val= array_pop(explode("-", rtrim(fread($fp, 30)))); //get last value
fclose($fp); // close file
}
?> // end php script
function drawChart(){
var data=google.visualization
.arrayToDataTable([ ['Label', 'Value'],
['Temp', <?php echo $val? $val : "0"; ?>],
]); // ^php above inserts value or 0
// etc...
}
//parts of your javascript
</script>
</head><body>
<!-- your body code -->
</body></html>
Note that fopen in combination with setting the filepointer via fseek and sequentially fread-ing from the pointer to EOF does not load the complete logfile (60min * 24hour=1440 lines of 16 bytes=22.5kB at the end of the day) into memory (good for this purpose), but only the last 30 chars (as in this example).
The variable to your logfile and path must still be modified to your situation (I don't know the format of your $today variable).
Depending on your further needs you might want to perform some extra checks/logic on the array of values that explode returns (instead of popping the last value). Or what about modifying the html a little so you could also include the last temperature's time reading, etc. (But this tested piece of code should get you started and explains the procedure of going the php way).
Update:
Since you have chosen to place the last known value of your logfile as in textfile placed inside your public www-root (with a bash script I assume, every minute of the day?), you can now indeed go the 'ajax' way, as answered by aross!
However I want to hint that the code/solutions in all current answers here could be mixed (since you now also have ajax working): instead of ajax-ing (loading) a txt file, you could have php fetch and send this value to the browser on-the-fly/on-demand!
So, instead of requesting http://url_to_my_rpi/file_to_download.txt, you could request http://url_to_my_rpi/read_last_temperature.PHP which should fetch the last known value out of the log-file (set proper security/access) and send it to the browser (set proper headers), just like your text-file did. You wouldn't have to change anything in the html/javascript except the url you request.
The advantage would be (depending on how your current bash-scripts works) that your PI now only does this 'work' (of getting the last value of your logfile) when you are viewing your monitor-page. And that you are not writing that file in your www-root every minute of every day (as I suspect).
The solution achieved, finally, was like this:
I did it with a jQuery statement and reusing the javascript code of Google Charts.
First I added javascript and jQuery tags in the html file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
Then I merged jquery code and javascript code that I had in one script:
<script type='text/javascript'>
// Needed this var so that I could use it in other places of the code
var t;
jQuery.get('http://url_to_my_rpi/file_to_download.txt',function(data){
console.log(data)
t=data;
},'text');
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawChart);
function drawChart() {
t=eval(t);
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temp', t],]);
// (... more javascript with Google Charts options, display parameters..)
</script>
Finally, and even if it's not listed as the main question, be sure to enable *mod_headers* on your apache and add Header set to apache2.conf file (In my case: /etc/apache2/apache2.conf)
1) Enable the module:
a2enmod headers
2) Add the line on your configuration file
Header set Access-Control-Allow-Origin "*"
3) Restart apache 2
4) In case the 3 steps above didn't work, follow the instrcutions by entering in this website or reinstall apache2.

javascript replace string in js file

Ok so another issue i got
I have a js file that i need to include on my page (i dont have access to edit this js file)
Inside that javascript there is a function wich has a line that i need to edit a variable in there.
lets assume:
Code:
var links = [{"offer_id":"1","title":"Text!","url":"http:\/\/www.site.com\/tracker\/1\/?http:\/\/site.com\/click.php?aff=9917&camp=5626&crt=13346&sid=e6a00014f247fe39de1b_1","footer_text":"text","blank_referrer":"1","active":"1","value":"0.40","creation_time":"1327785202"}];
notice : '&sid=e6a00014f247fe39de1b_1'
i need to add something right after sid=
so that i becomes for example:
Code:
&sid=AlssfIT_e6a00014f247fe39de1b_1
i added: AlssfIT_
any ideas how to achieve this ?
i tried something like
Code:
str.replace("&sid=","&sid="+kwd);
right after i "include" the js file but aparently is not working
I think you're going about it the wrong way. If notice is a variable in the global space you can just replace it normally.
window.someObject.notice = window.someObject.notice.replace("&sid=","&sid="+kwd);
This will of course only work if notice is a variable that is navigable to in the global namespace and is not inside a closure. It is inside a closure if it has a var declaration inside a function() {...}
But, assuming that there is global access to that variable, that will be your easiest way to achieve this.
If not, you can try grabbing the contents of the script and executing it hopefully overwriting the original code. This will only work if your script and the script you are fetching are from the same origin (domain, subdomain, port, protocol, a few other things) - it is impossible otherwise due to the _Same Origin Policy_
Assuming you are at the same origin, you could do something like this (using jquery for simplicity)
( function() {
// First we need the url of the script, we can grab it out of the element directly or it can be hard coded
var scriptLocation = $('script#the-id-of-the-script-element').prop('src');
// Now that we have the location fetch the script again so we can get it as plaintext
// this will usually not do another HTTP request since your browser has it cached
$.get(scriptLocation).done(function(text) { // I prefer the deferred syntax as being more explicit, this is equivalent to $.get(scriptLocation, function(text) {
var newText = text.replace("&sid=","&sid="+kwd);
eval(newText);
});
} )()
Something like this could work.
try regex: (not tested)
myregexp = new RegExp("/&sid=/", "gims");
str.replace(myregexp, "&sid=" + kwd);

Categories

Resources