So i'm trying to parse this json with javascript and it reads it from the webpage correctly however it just freezes when reaching the JSON.parse.
Here's what the webpage outputs:
{
Players: 18,
maxPlayers: 32,
Map: "jb_summer_redux_v3"
}
Here's what the full code is:
var xhr = new XMLHttpRequest();
var url = "http://in.nickparksdev.com/info.php";
document.write("Loading....");
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.write(xhr.responseText);
var jsonResponse = JSON.parse(xhr.responseText);
document.write("Test: " + jsonResponse.Players);
}
}
xhr.send();
Here's what that document.write(xhr.responseText); outputs:
{"Players":19,"maxPlayers":32,"Map":"jb_summer_redux_v3"}
Any help on this would be great :)
Your page return HTML not JSON
Output :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Players</title>
</head>
<body>
{"Players":15,"maxPlayers":32,"Map":"jb_summer_redux_v3"}</body>
</html>
You have to output only the JSON not HTML.
In my testing, JSON.parse does return the correct object from that string. However, your file is HTML with JSON in it.
Related
I am getting a response body with raw response, which is supposed to respresent a png image. My question is how to decode this and make it a renderable.
PS: when I am use postman to test this, I realized that Postman can render this raw string, and I am wondering how it does it.
�PNG
IHDR�X:�(� pHYs���o�d
IDATx���\�w����v,J�L�2b�_٬�N��d��0|�cmDN�6�y.�q�{�Iӌ�hsnNcl��g~/;"vʯ�m�('}�Q9��q�P(G:�������z=���q��|=_�\�p�""""""�p�w""""""b
�""""""J�PDDDDD�A)������8(B�#("""""�EDDDDD���������R
qP
�""""""J�PDDDDD�A)������8(B�#("""""�EDDDDD���������R
[...]
After a few hours of googling, I finally figured out the issue:
Essentially, the response from my REST call actually contains blob type of the png image. So to properly render it, we don't have to base64 the blob, instead it is natively supported by html5. The problem I was facing is that this blob is not supported by jQuery ajax call, hence higher level libraries like axios does NOT support it either.
For simplicity, to demo how this works, I would use jQuery:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Blob image/png demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="invokeBlob">
<input type="submit" value="Invoke It!">
</form>
<!-- the result of the blob will be rendered inside this div -->
<div id="imgcontainer"></div>
<script>
// Attach a submit handler to the form
$( "#invokeBlob" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var url = "https://YOUR-DOMAIN/charts";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("Authorization", "Bearer XXX-YOUR-JWT-TOKEN")
xhr.setRequestHeader("Accept", "image/png");
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);
};
img.src = window.URL.createObjectURL(blob);
$("#imgcontainer").html(img);
}
}
xhr.send();
});
</script>
</body>
</html>
Question: Why the function is not able to retrieve the json object?
I also noticed when debugging the code on my browser that the console does one pass through the code but never comes back! I thought the way this works is by having the function at the bottom of the html code looping back up until the the request status is changed.
I am starting to learn html javascripting. Following a tutorial I have the following code for html page that gets and parse JSON object:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
//crate our XMLHttpRequestobject
var hr = new XMLHttpRequest();
//var p1 = "p1";
//creat some variable we need to sned to our php file
hr.open("GET", "mylist.Json", true);
//set content type information for sending url encoded variables in the
//reqeust
console.log(5+6);
hr.setRequestHeader("Content-type", "application/json", true);
//Acess the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatchange = function(){
if (hr.readyState == 4 && hr.status == 200){
var data = JSON.parse(hr.responseText);
var results = document.getElementsById("results");
results.innerHTML=data.user;
// document.getElementById("results").innerHTML = return_data;
}
}
//send the data to php now and wait for the response to update the
//status div
hr.send();
results.innerHTML = "reqeusting...";
// document.getElementById("results").innerHTML="processing...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
Here is the json object code
{"user":"John", "age":22, "country":"United States" }
Both files are sitting in my ubuntu server that has LAMP enabled. Here is what the directory looks like:
Apparently the problem lies in declaring var results within hr.onreadystatechange function. Moving the declaration to the top fixed the code. Here is the working code:
<!DOCTYPE html>
<html>
<head>
<script>
function ajax_get_json(){
var results = document.getElementById("results");
//crate our XMLHttpRequestobject
var hr = new XMLHttpRequest();
//var p1 = "p1";
//creat some variable we need to sned to our php file
hr.open("GET", "mylist.json", true);
//set content type information for sending url encoded variables in the
//reqeust
//console.log(5+6);
//hr.setRequestHeader("Content-type", "application/json", true);
hr.setRequestHeader("Content-type", "application/json", true);
//Acess the onreadystatchange event for the XMLHttpRequest object
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200){
var data = JSON.parse(hr.responseText);
results.innerHTML=data.user;
// document.getElementById("results").innerHTML = return_data;
}
}
//send the data to php now and wait for the response to update the
//status div
hr.send(null);
results.innerHTML = "reqeusting...";
// document.getElementById("results").innerHTML="processing...";
}
</script>
</head>
<body>
<div id="results"></div>
<script>ajax_get_json();</script>
</body>
</html>
So I got this code for pulling rss feeds from another website (i asked them, and they gave me permission) I Don't know what should i Write in TAG1 and TAG2. Basically that is just my problem:
Here is the html (its an ajaxed page)
<!doctype html>
<html lang="hu">
<head>
<title>Videók</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="../js/videok.js"></script>
</head>
<body>
<h2>Van egy jó videód? Töltsd fel és kikerülhet az oldalra!</h2>
<div id="videok"></div>
</body>
</html>
And here is the Javascript for pulling
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "choose url";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
You won't be able to use javascript to pull from another web page because javascript is sandboxed when in browsers. Sandboxing means that you will only be able to send requests to the same domain that the javascript originally came from (also known as the 'same orgin policy').
You can use a serverside language like php to do the pulling and then hand it down to the javascript through ajax.
The code that you posted looks like it just makes a simple ajax call but it shouldn't work when trying to request an RSS from anything other than your own site.
It's better that you have the server side of your application fetch data for the xml and format the data how you want it.
You would have the Ajax request hit your server's end point, then your server will fetch the xml data, format it properly and respond to the request with the correct formatted data.
I am trying to get a piece of data from server using JSP technology. I am using JSON object to do so. On client side i am using XMLHttpRequest to get the data.
To check whether it works properly, i wrote a piece of code as follow:
<head>
<script type="text/javascript">
function test(data) {
if(data){
var jsonObj= eval('(' + data + ')');
var Question= jsonObj.Question;
document.write(Question);
}
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseText != null && this.responseText)
// success!
test(this.responseText);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
function xyz(){
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("POST", "fetch.jsp", true);
client.send();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br><br><input id="Q" type="button" onclick="xyz()" >
</body>
on server side i did as follow:
<%#page import="net.sf.json.JSONObject"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% JSONObject jsonObj= new JSONObject();
jsonObj.put("Question","What is your name?");
jsonObj.put("Opt1","ji");
jsonObj.put("Opt2","ji");
jsonObj.put("opt3","ma");
jsonObj.put("opt4","sa");
String str= jsonObj.toString();
response.setContentType("text/plain");
response.getWriter().write(str);
%>
Unfortunately i am not able to get the response.
You are writing your JSON into the body of an HTML document, and then sending the HTML document as the response.
Don't do that. The response should be just the JSON.
You need to write with content type application/json.
Also don't use eval in test function.
When the data is json the test function can access the data as the json object!
In the event of parsing a string use.
JSON.parse(string).
But don't use eval
When I execute the eval function it doesn't turn my json response into a object it just breaks my code. I've tried parsing with prototype.js and JSON2.js to no avail some please explain what I am doing wrong here?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Inventory Management</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="call.js" type="text/javascript"></script>
<script src="prototype.js" type="text/javascript"></script>
</head>
<body>
<div>
<p id="resp" >new</p>
<script type="text/javascript">
var xhr;
var results=getPlants(xhr,results);
var plants;
function getPlants(xhr,results){
try {
xhr=new XMLHttpRequest();
}catch(microsoft){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
xhr=false;
alert("ajax not supported");
}
}
}
xhr.onreadystatechange= function () {
if(xhr.readyState==4 && xhr.status==200) {
results = xhr.responseText;
}
}
xhr.open("GET","db_interactions.php",true);
xhr.send(null);
alert("sent");
return results;
}
plants = eval('('+results+')');
document.write(typeof(plants));
</script>
</div>
</body>
</html>
You're issuing an asynchronous request. That means the function will return even when the data isn't ready yet. But your call assumes the JSON response is ready when getPlants is called. Which obviously makes results undefined because you aren't waiting for it.
Put your
plants = eval('('+results+')');
document.write(typeof(plants));
Inside the xhr.onreadystatechange function to make it work, or open the connection as synchronous
xhr.open("GET","db_interactions.php",false);
By the way, don't use eval to parse JSON because code may be injected maliciously. Use a JSON parser instead.