I got this string output on a page. its HTML and I need to get it "human readable"
Its stats from a server.
Could you help me getting it a bit more "clear"
The string printed is:
{"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}
Is it possible to get it to be:
Version: 9.7 - CN
Speed: 483
Temp/fan 50 20
and so on, any help is appreciated
This must be done client side
I now have this in a html file:
<!DOCTYPE html>
<html>
<body>
<script>
const regex = /{.*}/g;
var request = new XMLHttpRequest();
request.open('GET', 'http://10.0.0.20:3333', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
var json = regex.exec(resp);
obj = JSON.parse(json[0]);
document.getElementById('content').innerHTML = 'Version: ' + obj.result[0] + '
Speed: ' + obj.result[2].split(';')[0] + ' Temp/fan ' + obj.result[6].replace(';', ' ');
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
request.send();
</script>
<div id="content"></div>
</body>
</html>
Using JavaScript:
var res = {"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}
var text = 'Version: '+res.result[0]+' Speed: '+ res.result[3]+' Temp/fan '+ res.result[6].replace(';', ' ');
Would this help?
<?php
$input = '{"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}';
$parsed = json_decode($input, true);
echo "Version: ".$parsed["result"][0]." Speed: ".explode(";",$parsed["result"][3])[0]." Temp/fan ".str_replace(";"," ",$parsed["result"][6]);
?>
Might not be the prettiest code but you can also do it client-side:
var json = '{"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}';
obj = JSON.parse(json);
document.getElementById('content').innerHTML = 'Version: '+obj.result[0]+' Speed: '+obj.result[2].split(';')[0]+' Temp/fan '+obj.result[6].replace(';',' ');
<div id="content"></div>
Client-side version with AJAX call included:
(I'm not sure if it's http or https on the URL you provided but give it a try and see if it solves the problem)
const regex = /{.*}/g;
var request = new XMLHttpRequest();
request.open('GET', 'http://10.0.0.20:3333', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
var json = regex.exec(resp);
obj = JSON.parse(json[0]);
document.getElementById('content').innerHTML = 'Version: ' + obj.result[0] + '
Speed: ' + obj.result[2].split(';')[0] + ' Temp/fan ' + obj.result[6].replace(';', ' ');
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
request.send();
<div id="content"></div>
Related
More explanation here :
Im importing products to my DB, and everytime a product is imported I display the percent calculated earlier:
//Progress bar
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
sleep(1);
$p = ($i/$count_product)*100; //Progress
$response = array( 'success' => true , 'message' => $p . '% ','progress' => $p);
$i++;
echo json_encode($response);
On my local everything is working fine :
Every time php echo json_encode() I get on XHR a new state 3, and display the response.
Code below:
var xhr = new XMLHttpRequest();
xhr.previous_text = '';
$param = 'id='+$(this).find('input').val();
xhr.onerror = function() {console.log(xhr.responseText) };
xhr.onreadystatechange = function() {
//try{
console.log(xhr.readyState);
console.log(xhr);
console.log(new_response);
if (xhr.readyState == 4){
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse( new_response );
if (result['message'] == '100' ) {
$('.progress_bar').html('<div><?=$this->translate->_("Imported succefully")?></div>');
$.when($('.full_screen_layer').fadeOut(2000)).done(function() {
location.reload();
});
}else{
$('.progress_bar').html('<div style="color:red">'+result['message']+'</div>');
setTimeout(function(){
$.when($('.full_screen_layer').fadeOut(2000)).done(function() {
location.reload();
});
}, 2000);
// alert('<?=$this->translate->_("Please try again")?>');
}
}
else if (xhr.readyState > 2){
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse( new_response );
if (result['success'] && result['end'] == undefined) {
$('.progress_bar').html('<div>'+result['message']+'</div>');
xhr.previous_text = xhr.responseText;
}else{
$('.progress_bar').html('<div style="color:red">'+result['message']+'</div>');
}
}
//}
// catch (e){
// alert("[XHR STATECHANGE] Exception: " + e);
// }
};
xhr.open("POST", action, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send($param);
But I'm trying to understand why it's not working on the server ( XHR state 3 is fired only once, at the end of the request ( so the json is malformed )
Here are the headers:
This just break my mind, if someone have an idea, even a bad one xD
(Btw there is a proxy on the server : VIA:1.1 Alproxy ) it could stop the response untill it end and then send it alltogether ?
I want to parse a shoutcast page like this :
http://relay.181.fm:8800/played.html
So, i just make ajax to call a php file. The php file return all the content of the page.
i store the html content to a var in js. Here is the code:
PHP:
function getcontent($server, $port, $file){
$cont = "";
$ip = gethostbyname($server);
$fp = fsockopen($ip, $port);
if (!$fp){
return "Unknown";
}
else{
$com = "GET $file HTTP/1.1\r\nAccept: */*\r\nAccept-Language: de-ch\r\n"
."Accept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible;"
." MSIE 6.0;Windows NT 5.0)\r\nHost: $server:$port\r\n"
."Connection: Keep-Alive\r\n\r\n";
fputs($fp, $com);
while (!feof($fp))
{
$cont .= fread($fp, 500);
}
fclose($fp);
$cont = substr($cont, strpos($cont, "\r\n\r\n") + 4);
return $cont;
}
}
echo (getcontent("relay.181.fm", "8800", "/played.html"));
Here is my js:
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=xhr.response;
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
And that is what i want to get:
$(document).ready(function(){
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();
time[i]=$('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
});
if i copy the xhr.response content and i put it in the html file and i execute this js, it return me exactly what i want.
but i dont get how i can do when the html is in a variable... :'(
PS: i work on a wamp env., And a node.js env.
Since you tagged it with jQuery, why not use the built in ajax functionality:
$.ajax({
url: 'http://localhost/getsong.php',
dataType: 'html'
}).done(function(data){
//do something with the HTML
var $html = $(data),
tdtexts = $html.find('table:eq(2) tr td:first').text();
});
Is this what you're asking for?
I think, you can use innerHTML to resolve
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=xhr.response;
document.getElementById('#div').innerHTML = parsed;
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
Proceeding further after getting response may help you like,
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=$.parseHTML(xhr.response);
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();// use find function for parsed string
time[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
By using $.ajax()
$(function(){
$.ajax({
url:'http://localhost/getsong.php',
dataType:'html',
success:function(parsed){
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();// use find function for parsed string
time[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
}
});
});
I think you're looking for jQuery.parseHTML(). It will parse your string into an array of DOM nodes.
http://api.jquery.com/jQuery.parseHTML/
Here's a quick example for your case:
$.get('http://relay.181.fm:8800/played.html')
.done(function(data) {
var parsed = $.parseHTML(data);
// Now parsed is an array of DOM elements which you can use selectors on, eg:
var song1 = $(parsed).find('table:eq(2) tr:eq(1) td:eq(1)').text();
console.log(song1);
});
I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );
I have the following JS:
window.onload = function() {
'use strict';
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if ( ajax.readyState == 4 ) {
if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) {
var data = JSON.parse(ajax.responseText);
var file = '';
file += 'Original: ' + data['org'].file + '<br>';
file += 'Processed: ' + data['pre'].file + '<br>';
document.getElementById('output').innerHTML = file;
} else {
document.getElementById('output').innerHTML = 'Error: ' + ajax.statusText;
}
}
};
document.getElementById('btn').onclick = function() {
ajax.open('POST', 'resources/test.json', true);
ajax.setRequestHeader('Content-Type', 'application/json');
ajax.send(null);
};
};
I would like to pass the data from
data['org'].file
and
data['pre'].file
to PHP and have it echo out the value using the POST method. Please no jQuery solutions this needs to be strictly JavaScript.
Something like this:
<?php $data = $_POST['the_data']; echo $data; ?>
Here is the JSON from test.json:
{
"org": {
"file": "css/original.css"
},
"pre": {
"file": "css/preprocessed.css"
}
}
If you want a PHP script to echo JSON data, it's as simple as this:
<?
$json = file_get_contents('php://input');
//...
echo $json;
?>
To post it from Javascript, I reccomend reading this. There's a reason so many people use jQuery...
have a look on JSON Stringify you can use that to encode your data.
Then after you encoded you can send it wherever you need.
below is my code for uploading files using XMLHttpRequest send method
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr.open("POST", queryString, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
}
With the above function i wait for on_upload_complete to get called and then pass the second file object and one by one i am uploading. Can someone suggest how can i make it upload simultaneously i tried doing this below as
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr[filename].onreadystatechange = function()
{
if(xhr[filename].status == 200 && xhr[filename].readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
by doing this i xhr[filename] inside onreadystatechange is undefined because of loop and i want to keep track of every file upload progress and finish it . But as you can see the problem is only keeping track of onreadystatechange with a unique id and i am stuck here. Please can anyone throw light , suggestions and recommendations help is appreciated. thanks
You have deal with Javascript Closure. onreadystatechange see filename,id,xhr of the lastest invoke of send_file_to_server function. To change this rewrite your function like this:
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
(function(localFilename, localId, localXhr){
localXhr[localFilename].onreadystatechange = function(){
if(localXhr[localFilename].status == 200 && localXhr[localFilename].readyState == 4){
on_upload_complete(localFilename, localId, localXhr);
}
}
})( filename,id,xhr)
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}