Parse content from a html page - javascript

Need to dynamically update contents in a div of main page, based on data fetched from other html page
setInterval( function() {
$.ajax({
type:'GET',
url:"url for status",
success : function(data){
console.log(data);
}
})
},3000);
The content of 'data' printed in developer tool console is:
<html>
<style>
</style>
<head>
</head>
<script>
var conns=[{num:1,
id:1,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_1',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
},
{num:2,
id:2,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_2',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
}]
</script>
</html>
Need to extract the ConnectionStatus, Name and ConnectionError from this content and display it in respective div in main page.

I would recommend using a different transfer type, however, you could use something like this:
function break_out_each_id(){//returns array of indexes where id starts
var i = 0;
id_objs = [];
while data.indexOf('id', i) > -1{
id_objs[i] = data.indexOf('id', i);
i++;
}
return id_objs
}
function find_values(){//pseudo code
use the array of indexes from first index to next index
in that string, do index of each value you are looking for (ConnectionStatus...)
then parse that line after the ':' to get the value.
Do this for each index in indexes array
}
Sorry for the pseudo code, but this post is getting really long. Like I said, it would be MUCH better to just send the response as JSON (even if it is a stringified version of it). In that case you could just do a simple JSON.parse() and you'd be done.

Related

Text to Html list

I want to make a html which will auto get the information for a *.txt file
something1
something2
something3
and output into this html file
<!DOCTYPE html>
<html>
<head>
<title>List</title>
</head>
<body>
<ul>
#here to output#
</ul>
</body>
</html>
I prefer to use JavaScript. Some help is appreciated.
You have to request the file using AJAX call. Then you need to iterate through each line of response and generate DOM element (li in this case) and input line inside of it. After that insert each li element into your ul list.
You can achieve it using jQuery as you are probably new to JavaScript it's probably the easiest way.
What you need to do is request the file first:
$.ajax('url/to/your/file', {
success: fileRetrieved
});
Now after the file is retrieved jQuery will call fileRetrieved method, so we have to create it:
function fileRetrieved(contents) {
var lines = contents.split('\n');
for(var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
Now for each line from the file function fileRetrieved will call createListElement function passing line of text to it. Now we just need to generate the list element and inject it into DOM.
function createListElement(text) {
var into = $('ul');
var el = $('<li></li>').html(text);
el.appendTo(into);
}
Of course you don't want to retrieve into element each time createListElement is called so just store it somewhere outside the function, it's your call, I'm just giving you the general idea.
Here is an example of the script (without AJAX call of course as we can't simulate it):
var into = $('#result');
function fileRetrieved(contents) {
var lines = contents.split('\n');
for (var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
function createListElement(text) {
var el = $('<li></li>').html(text);
el.appendTo(into);
}
var text = $('#text').html();
fileRetrieved(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This element simulates file contents-->
<pre id="text">
fdsafdsafdsa
fdsafd
safdsaf
dsafdsaf
dsafdsafds
afdsa
</pre>
<div id="result"></div>
Try this
<html>
<head>
<title>List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="renderTxt_list">
</ul>
<input type="button" id="lesen" value="Read Data" />
</body>
<script>
$(document).ready(function(){
$("#lesen").click(function() {
$.ajax({
url : "testTxt.txt",
dataType: "text",
success : function (data) {
$html = "";
var lines = data.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
$html += '<li>'+lines[i]+'</li>';
}
$("body ul").append($html);
}
});
});
});
</script>
</html>
You need to request the file first, and then append it to your chosen place in the document.
You can for example use jQuery's get (or any other function like the native fetch), and then inject it into the ul element:
$.get("*.txt").then(x => $("ul").html("<li>" + x.split('\n').join('</li><li>') + "</li>"))
Let's break this solution by steps:
First, we need to request the external file:
$.get("*.txt")
Read about jQuery's get here. Basicly it will request the file you asked for using network request, and return a promise.
In the Promise's then, we can do stuff with the request's result after it is resolved. In our case we want to first break it by lines:
x.split('\n')
split will return an array that will look like this: ["line 1, "line 2", "line 3"].
JS arrays have the join method, which concat them to string while putting the string you want between the items. So after we do this:
x.split('\n').join('</li><li>')
We only need to add the <li> element to the start and end of the string like this:
"<li>" + x.split('\n').join('</li><li>') + "</li>"
Finally we appent it to your chosen element using jQuery's html.

how to pass a json object from a php page to a js variable

First off, my apologies if this is already addressed in another post - I'm sure it is, but I have not been able to figure it out.
Second, I have a PHP page that outputs an array in a JSON format like this:
[{
"chemical":"Corrosion_Inhibitor",
"TargetDose":81,
"AppliedDose":26,
"ppbbl":"$0.97"
},
{
"chemical":"Scale_Inhibitor",
"TargetDose":56,
"AppliedDose":63,
"ppbbl":"$1.00"
},
{
"chemical":"Biocide",
"TargetDose":55,
"AppliedDose":55,
"ppbbl":"$0.30"
},
{
"chemical":"Friction_Reducer",
"TargetDose":23,
"AppliedDose":44,
"ppbbl":"$0.42"
}]
I would like to pass that array to a variable tableData in JavaScript so that I can populate a table on another PHP page. Any guidance would be greatly appreciated. Clearly I am not an expert in either of these languages.
Sounds like you want to dynamically generate a table from a JSON response? If you are sending a request to the php script that outputs that JSON response, you can use JSON.parse(responseData) to parse the JSON string response to a JS variable array/array of objects.
This is a basic way to do that:
<?php
$dataFromPHP =
'[{
"chemical":"Corrosion_Inhibitor",
"TargetDose":81,
"AppliedDose":26,
"ppbbl":"$0.97"
},
{
"chemical":"Scale_Inhibitor",
"TargetDose":56,
"AppliedDose":63,
"ppbbl":"$1.00"
},
{
"chemical":"Biocide",
"TargetDose":55,
"AppliedDose":55,
"ppbbl":"$0.30"
},
{
"chemical":"Friction_Reducer",
"TargetDose":23,
"AppliedDose":44,
"ppbbl":"$0.42"
}]
';
?>
<html>
<body>
<!-- main HTML content -->
</body>
<script>
var tableData = <?php echo $dataFromPHP ?>;
// do whatever you want with that data
</script>
</html>

Get JSON object from URL using javascript

I'm trying to get the value of the first 'price' field at the url:
http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132
I am currently using the following code to do so:
getJSON('http://pubapi.cryptsy.com/api.php?
method=singleorderdata&marketid=132').then(function(data) {
var final = (data.return.DOGE.sellorders.price * totalcost) * 0.985
var finished = final.toFixed(8)
I have a strong feeling that I have done this bit wrong:
data.return.DOGE.sellorders.price
Any ideas?
Thanks!
data.return.DOGE.sellorders[0].price because sellorders is an array
$.getJSON('http://jsbin.com/pudoki/1.json', function(data){
alert(data.return.DOGE.sellorders[0].price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Parsing HTML plaintext data into javascript array

So I have a very simple HTML page called Terms.html. Here is the output:
Museums, Parks, Railroads and Trains, Shopping, Theatres
and here is the code:
<!DOCTYPE html>
<html>
<body> Museums, Parks, Railroads and Trains, Shopping, Theatres </body>
</html>
Now, I am using jQuery $.get method to retrieve this html page:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<script>
var tags = [ "String1", "String2"];
$.get("Terms.html", function(data, status) {
<!-- -->
$(result).html( data );
alert("Status: " + status);
});
</script>
<p>Search terms are: <span id="displayterms"></span></p>
<div id="result"><div>
</body>
</html>
What I want to do is be able to parse Museums, Parks, Railroads and Trains, Shopping, Theatres into individual strings and add them to my var tags array. Any ideas on how I can do this? Thanks
Try:
var tags = ["String1", "String2"];
var str = "Museums, Parks, Railroads and Trains, Shopping, Theatres";
arr = $.map( tags.concat(str.split(',')), function( n ) { return $.trim(n) });
console.log(arr); // Outputs the array ["String1", "String2", "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
jsFiddle example
The third line splits the str on the commas and then uses jQuery's .map() function to trim the whitespace.
With the split function: http://www.w3schools.com/jsref/jsref_split.asp
This will split on any character you choose, in this case ","
tags = data.split(",");
If you don't need to support versions of IE older than 9, you could do something like this:
var tags = document.body.textContent.split(',').map(
function (s) {
return s.trim();
}
);
document.body.textContent gets the text in the body tag. This restricts your browser support, as IE didn't have this until version 9.
.split(',') takes the string and splits it into its component parts, returning an array.
.map() applies a function to everything in the array returned by .split(','), and returns an array of the results. In this case, we use it to call trim() on each string in the array, to strip leading and trailing whitespace. IE didn't have the Array.prototype.map or String.prototype.trim methods until version 9, but they're easy to polyfill. It's the textContent thing above that's trickier.
The array returned from map() is then put into your tags variable.
Instead of storing the contents as HTML, you could store them in a JSON data file.
An example JSON data file (places.json):
{
"Names": [ "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
}
Then, you can change your page code to:
<script>
var tags = [ "String1", "String2"];
$.getJSON("/places.json", function(data) {
$(result).html(data);
console.log(data.Names[0]); // Outputs Museums
$.each(data.Names, function(index, value) {
tags.push(value); // add the tag to your tags list for each item in Names
});
});
</script>
This way you can store just the data you need and you won't need to parse the HTML manually.

Jquery load remote page element according to a string in current page url

I'm new in Jquery, I would like to have Jquery code to get the current page url and if the url contains certain string then load remote element.
example:
i have the page urls like this:
"http://......./Country/AU/result-search-to-buy"
"http://......./Country/CA/result-search-to-buy"
"http://......./Country/UK/result-search-to-buy"
the part "/Country/AU" is what I need to determine which page element I should load in, then if "AU" I load from "/state-loader.html .state-AU", if "CA" I load from "/state-loader.html .state-CA"
I have a builtin module "{module_pageaddress}" to get the value of the current page url, I just dont know the Jquery logic to let it work.
I expect something like this:
if {module_pageaddress} contains "/Country/AU/"
$('#MyDiv').load('state-loader.html .state-AU');
if {module_pageaddress} contains "/Country/CA/"
$('#MyDiv').load('state-loader.html .state-CA');
please help and many thanks.
Here is some code:
<!DOCTYPE html>
<html>
<head>
<title>jQuery test page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
function stateURL() {
var startOfResult = '../../state-loader.html #state-';
var match = (/(?:\/Country\/)(AU|US|CA|UK)(?:\/)/).exec(window.location.pathname);
if (match) {
return startOfResult + match[1];
} else {
return startOfResult + 'AU';
}
}
</script>
</head>
<body>
Link 1
<div id="content">content will be loaded here</div>
</body>
</html>
And the file to load the different content for the states:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="state-US">Go USA!</div>
<div id="state-CA">Go Canada!</div>
<div id="state-AU">Go Australia!</div>
<div id="state-UK">Go United Kingdom!</div>
</body>
</html>
See it work here:
http://www.quirkscode.com/flat/forumPosts/loadElementContents/Country/US/loadElementContents.html
Replace .../US/... with .../AU/..., etc. to see how it behaves.
Original post where I got the ideas/original code:
http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
You can try
var countryCode = ... // parse the country code from your module
$('#yourDiv').load('state-loader.html .state-' + countryCode);
See more examples of .load() here.
As far as pulling the url path you can do the following
var path_raw = document.location.path,
path_array = path_raw.split("/");
Then, you could do something like this:
$.ajax({
url: "./remote_data.php?country=" + path_array[0] + "&state=" + path_array[1],
type: "GET",
dataType: "JSON",
cache: false,
success: function(data){
// update all your elements on the page with the data you just grabbed
}
});
Use my one line javascript function for getting an array of the URL segments: http://joshkoberstein.com/blog/2012/09/get-url-segments-with-javascript
Then, define the variable $countrySegment to be the segment number that the country code is in.
For example:
/segment1/segment2/CA/
(country code would be segment 3)
Then, check if the 3rd array index is set and if said index is either 'CA' or 'AU'. If so, proceed with the load, substituting in the country-code segment into the .html filename
function getSegments(){
return location.pathname.split('/').filter(function(e){return e});
}
//set what segment the country code is in
$countrySegment = 3;
//get the segments
$segments = getSegments();
//check if segment is set
//and if segment is either 'AU' or 'CA'
if(typeof $segments[$countrySegment-1] !==undefined && ($segments[$countrySegment-1] == 'AU' || $segments[$countrySegment-1] == 'CA')){
$countryCode = $segments[$countrySegment-1];
$('#target').load('state-loader.html .state-' + $countryCode);
}
var result= window.location.pathname.match(/\/Country\/([A-Z]+)\//);
if(result){
$('#MyDiv').load('state-loader.html .state-' + result[1]);
}

Categories

Resources