JSON.parse(hr.response) error - javascript

I am trying to retrieve data from JSON. I have written this code. It alerts "1" but doesn't alert "2".
<script type="text/javascript" src="jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
function ajax_get() {
var results = document.getElementByI("results");
var hr = new XMLHttpRequest();
hr.open("GET", "mylist.json", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-type", "application/json",true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
alert('1');
var data = JSON.parse(hr.response);
alert('2');
alert(data);
results.innerHTML = data.name;
}
}
hr.send(null);
results.innerHTML = "request ...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get();</script>
</body>

You have already set the response type as json on this line.
hr.responseType= "JSON";
So you need not parse the response again. it will be by default json.
Make sure your response is in json format and change your code like this.
var data = hr.response;

Related

JSON data to HTML using AJAX

I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.
`enter code here`
<html lang="en">
<head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
<p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
function renderHTML(data) {
var output = "";
for (var key in data)
{
output += "<p>" + key + output + "</p>"
}
}
};
</script>
</body>
The main issue is how your calling the api "http://api.fixer.io/latest".rates
You call rest endpoints by there address params or with query params.
Please see example below calling your specified endpoint. That should get you started
var myData = 'https://api.fixer.io/latest'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(xhttp.responseText)
Object.keys(res.rates).forEach((e)=>{
console.log(`${e}: ${res.rates[e]}`)
//Add your stuff here
})
}
};
xhttp.open("GET", myData, true);
xhttp.send();

AJAX get JSON function not looping

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>

Fetching data from php file and using javascript to print selected data

I have 2 divs in my html page. Using AJAX, JavaScript, I send my query parameters to a php file, which returns combined results for the 2 divs. I want to know how to separate the result in JavaScript and display in their respective divs.
<script>
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length==0) {
document.getElementById("result1").innerHTML="";
document.getElementById("result2").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var content = xmlhttp.responseText;
if (content == "%<searchword>%")
document.getElementById("result1").innerHTML = content;
else
document.getElementById("result2").innerHTML = content;
}
}
xmlhttp.open("GET","db.php?q="+ yr ,true);
xmlhttp.send();
}
</script>
<body>
<form>
Enter year: <input type="text" id="entry" />
<input type="button" value="check here" onclick="fetchData()" />
</form>
<div id="result1">result 1 here</div>
<div id="result2"> result 2 here</div>
</body>
Return json as PHP output, that is best for Javascript (do not forget json php headers, use json_encode), like this:
{
"div1": "Content for div 1",
"div2": "DIV 2 content"
}
Easy with jQuery getJSON method, or jQuery $.ajax:
$.ajax({
dataType: "json",
url: urlToPHPFile,
data: dataToSend,
success: function( jsonResponse ) {
$('#result1').html( jsonResponse.div1 );
$('#result2').html( jsonResponse.div2 );
}
});
To send request with pure Javascript take a look at this article.
To parse JSON just read this article.
So, with pure Javascript you get something like this:
function alertContents(httpRequest){
if (httpRequest.readyState == 4){
// everything is good, the response is received
if ((httpRequest.status == 200) || (httpRequest.status == 0)){
var obj = JSON.parse(httpRequest.responseText);
var div1 = getElementById('result1');
var div2 = getElementById('result2');
div1.innerHTML = obj.div1;
div2.innerHTML = obj.div2;
}else{
alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
}
}
};
function send_with_ajax( the_url ){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open("GET", the_url, true);
httpRequest.send(null);
};
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length == 0) {
document.getElementById("result1").innerHTML = "";
document.getElementById("result2").innerHTML = "";
return;
}
send_with_ajax( "db.php?q=" + yr );
};
fetchData();

Reading JSON into JavaScript using XMLHttpRequest

I have an external JSON file that I am trying to read into my ajax and parse through, but I'm missing something. I'm trying to read it into an XMLHttpRequest object. Any ideas on what I'm doing wrong. I get no results.
External file (mypeeps.json) contains:
[
{"name":"Frank","age":"23","image_url":"frank.gif"},
{"name":"Jim","age":"24","image_url":"frank.gif"},
{"name":"Tom","age":"21","image_url":"frank.gif"},
{"name":"Betty","age":"28","image_url":"frank.gif"},
]
My code is:
<script type="text/javascript">
function ajax_get_json() {
var p = new XMLHttpRequest();
p.open("GET", "mypeeps.json", true);
p.setRequestHeader("Content-type", "application/json");
p.onreadystatechange = function () {
alert("Im in...");
if (p.readyState == 4 && p.status == 200) {
alert("Let me know I've gotten this far");
var data = JSON.parse(p.responseText);
var results = document.getElementById("myDiv").innerHTML;
results.innerHTML = data.name;
} else {
document.getElementById("myDiv").innerHTML = "waiting...";
}
}
document.getElementById("myDiv").innerHTML = "processing...";
}
</script>
<div id="myDiv"></div>
<script type="text/javascript">
ajax_get_json();
</script>

Get JSON data from AJAX POST send

I need to get some JSON data from and AJAX function in PHP
This is what i've written so far but not sure exactly what to do on the PHP side.
JS:
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(json);
}
PHP:
<?php
if(isset($_POST['json']) ){
$json = $_POST ['json'];
$json_d = json_decode($json);
echo $json . 'hello';
} else {
echo 'error';
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src='ajax.js'></script>
<body>
HELLO THERE THIS IS AN HTML PAGEEEEE
</body>
</html>
Stringify your JSON on the client side.
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(JSON.stringify(json));
}
Decode the JSON from the raw request body.
$json = json_decode(file_get_contents("php://input"));
If you want to use raw post data, to get JSON try:
$json = json_decode(file_get_contents("php://input"));
JS example:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({key:"value", key:"value"}));

Categories

Resources