AJAX get JSON function not looping - javascript

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>

Related

Facing undefined error in json using javascript

I am using javascript ajax to fetch data from the JSON API server and want to show these data in an HTML table.
But I get an undefined error in HTML data. That is
Name id
undefined undefined
There is my code
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id="Name"></div></td>
<td><div id="Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Id").innerHTML = jsonObj.id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
What should I do to resove this? Thanks in advance.
The problem is that you are trying to access an object, but the output of the API is actually an array. You can get the first object by doing jsonObj[0], as follows:
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id = "Name"></div></td>
<td><div id = "Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").textContent = jsonObj[0].name;
document.getElementById("Id").textContent = jsonObj[0].id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
See this codesandbox where the code is working.
Edit: As T.J. Crowder has mentioned, it is better to use textContent rather than innerHTML to avoid unwanted HTML to be rendered (never trust user input!).

console gives an error when button is clicked "function is not defined at HTMLInputElement.onclick"

<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
this is javascript function which should run when i click the csubmit button, but when i click it the console gives an error written in the title. this function has to take the data written in the input tag, go to the comments.php page and insert it in database and display the comments in the comment div
I HAVE BEEN STUCK ON THIS ERROR FOR A VERY LONG TIME,BUT NOT ABLE TO FIND WHERE IS THE ERROR
<input type="button" id="csubmit" value="SUBMIT" onclick="ajax_post();">
Put ajax_post function in other script tag, you can not put JS code in script tag which already have src
<script src="jquery-3.2.1.min.js"></script>
<script>
function ajax_post() {
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid = '<?php echo $b; ?>';
var userid = '<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment=" + cm + "&bookid=" + bid + "&uid=" + userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
This is the problem with your code: Your script is inside a <script> tag with a src attribute. When a src attribute is present, the content inside the <script> tag is completely ignored.
This should work:
<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Not able to fetch json data from a php file in localhost

I am trying to make a client side script to fetch JSON data from a PHP file. I am using XAMPP to run the PHP scripts. When I run the demo_file.PHP, it shows the output. But when I try to fetch the data using the client side script it does not show any result.
The demo_file.php is:
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
and the demo.html to fetch the json data is:
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();
</script>
</body>
</html>
You probably getting error:
<b>Warning</b>: Creating default object from empty value in <b>[...][...]</b> on line <b>3</b><br />
You can not create object directly like this.You have create instance of StdClass() first.Like below.
$myObj = new stdClass();//need to create instance first
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
For more see here Creating default object from empty value

JSON.parse(hr.response) error

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;

Categories

Resources