Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console
To clarify my question, how can I retrieve a global variable from an AJAX JSON request
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.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("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class="src">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>
<div id="Name">Sachin</div>
</td>
<td>
<div id="Country">India</div>
</td>
</tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</div>
The best way to approach this is by using what's called a callback function. A callback function is a function that is invoked when specific event takes place. In your case that event is the data being retrieved from your JSON endpoint (URL).
The proper way to do this is to create a function that will be called when your data is received and will then carry out the remaining logic. If you want to make that data also accessible globally, part of the callback function can update your global variable.
In the updated code below we first declare a global variable globalJSON that holds our data. Before you receive any data (i.e. before you click the button) the value of globalJSON.data will be null. Once the data is received the callback function updateView() is called with the received data. Inside of updateView() we update the global variable globalJSON.data and carry out the remaining logic (i.e. updating the required HTML elements).
You can then use globalJSON.data anywhere else in your code to get the data received when Update Details button was clicked.
// declare your global variable that will get updated once we receive data
var globalJSON = {
data: null
}
// this gets executed the moment you load the page - notice the value is null
console.log(globalJSON.data);
// this gets executed AFTER you receive data - notice call to updateView() inside AJAX call function
function updateView(data) {
// this will update the value of our global variable
globalJSON.data = data;
// this is the rest of the logic that you want executed with the received data
document.getElementById("Name").innerHTML = data.name;
document.getElementById("Country").innerHTML = data.country;
// this will show that the global variable was in fact updated
console.log(globalJSON.data);
}
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
updateView(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
If you just want to access jsonObj from outside of the event handler, explicitly place it on the global scope (regardless of whether this is a good idea) you could create jsonObj on window by window.jsonObj = JSON.parse(http_request.responseText);
But you won't have any way of knowing when it's defined outside of the event handler. However, it would fulfill your requirement of being able to console.log(window.jsonObj) (presumably from the developer console). Also you could just console.log(jsonObj) in the eventhandler if you wanted to see the value.
full code:
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON(){
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
// if you want to be able to access this property from the developer console
window.jsonObj = JSON.parse(http_request.responseText);
// if you just want to see the value
console.log(JSON.parse(http_request.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("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
Declare a variable at first like var jsonObj= ''; ( Inside your function. This variable is not global from the page context, but from the function context ). access the variable in your function. A problem in your url that you use http://www.tutorialspoint.com/json/data.json but the original site using https protocol. As a result you got an error something like that
Blocked loading mixed active content "http://www.tutorialspoint.com/json/data.json"
So change the url also to https://www.tutorialspoint.com/json/data.json.
Then you can parse the result as you want.
<title>tutorialspoint.com JSON</title>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON();">Update Details </button>
</div>
<script>
function loadJSON(){
var jsonObj= '';
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
console.log(jsonObj);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>
Related
I have a problem with my ajax call, ive been searching here and cant find a answer to.
here is what happened the script worked great one second then when i logged in to use it again it just shows me my main index page any time i put http:// inside the text area here is the code.
function is_valid_url()
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('output');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var text = document.getElementById("text").value;
var queryString = "?text=" + text;
ajaxRequest.open("GET", "textscraper.php" + queryString, true);
ajaxRequest.send(null);
}
here is the html
<textarea id="text" onkeyup="is_valid_url()" placeholder="What do you think?" class="posttext">
</textarea>
any help is appreciated.
I want the value on my webpage to change, as the value in the JSON file changes. I wrote an interval function- intervalFunction() but the page does not update. Here is my code :
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
var myVar;
function intervalFunction() {
myVar = setInterval(loadJSON(), 100);
}
function loadJSON(){
var data_file = "http://52.21.92.17/balance";
var http_request = new XMLHttpRequest();
try{
http_request = new XMLHttpRequest();
}catch (e){
// IE
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Address").innerHTML = jsonObj[0].address;
document.getElementById("Balance").innerHTML = jsonObj[0].etherBalance;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</head>
<body onload="intervalFunction()">
<table class = "src">
<tr><th>Address</th><th>Balance</th></tr>
<tr><td><div id = "Address"></div></td>
<td><div id = "Balance"></div></td></tr>
</table>
</body>
</html>
Furthermore, another question I have is when use index [1], I can see data on the webpage, but if I use index [0], the first set of data in the array does not appear. Help would be appreciated.
function intervalFunction() {
myVar = setInterval(loadJSON(), 100);
}
is like saying:
function intervalFunction() {
var something = loadJSON();
myVar = setInterval(something, 100);
}
You're calling loadJSON() once, immediately, then asking setInterval() to call its result as a function.
You mean to say:
function intervalFunction() {
myVar = setInterval(loadJSON, 100);
}
I got a simple AJAX code to display a JSON file that is stored locally with that html and it keeps saying undefined. I am trying to do it over java script because I haven't learned any JQuery yet, I do hope my code is written syntactically correct. Thanks in advanced!
<script>
function loadJSON()
{
var data_file = "language.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Browser does not support this.");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("language").innerHTML = jsonObj.language;
document.getElementById("edition").innerHTML = jsonObj.edition;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</head>
<body>
<table border="1">
<tr><th> language </th> <th> edition </th></tr>
<tr><td> <div id="language"></div> </td><td> <div id="edition"></div> </td> </tr>
</table>
<button type="button" onclick="loadJSON()"> Load JSON </button>
</body>
</html>
This is JSON I am trying to display in a table through AJAX.
{
"books": [
{ "language": "Java" , "edition" :"second"},
{ "language": "C++" , "edition" :"fifth"},
{ "language": "C" , "edition" :"third"}
]
}
You need to itrerate over the jsonObj.books array like:
var table = document.getElementById("books_table"); // with: <table id='books_table'...
for(var i in jsonObj.books) {
var book = jsonObj.books[i];
table.innerHtml += '<tr><td> <div>'+book.language'+</div> </td><td> <div> '+book.edition'+</div> </td></tr>';
}
jsonObj.books is an array
for(var i in jsonObj.books)
iterates over the indicees of the array
var book = jsonObj.books[i];
extracts the ith actual 'book' object from the array
the following javascript function only seems to work when i have the final confirm() statement which I had originally in there for debugging purposes. when i take it out, delete_row.php doesn't seem to run. also, and perhaps as a hint/side-note, when i do have the confirm statement in there, it works on all browsers except for safari...
function deleterow(form) {
if (!confirm("Are you sure you want to delete?")) return false;
var queryString = "?ID=";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += "-";
}
}
queryString = queryString.slice(0, -1);
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var ajaxRequest; // The variable that makes Ajax possible!
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null);
confirm('Delete successful!');
}
UPDATE SOLVED
i was checking the status of the ajaxRequest through the following js script change
ajaxRequest.onreadystatechange = function(){ // Create a function that will receive data sent from the server
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
else{
alert('An error has occurred making the request');
return false;
}
}
and noticed i was getting a status of 0 back from the server. some googling around helped me realize that the error lied in how i was defining the buttons which were calling these functions.
original code was:
<div style='float:left; margin-right:10px;'><input type="submit" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>
fix is:
<div style='float:left; margin-right:10px;'><input type="button" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>
(submit type has to be changed to button type)
delete_row.php doesn't seem to run have you verified this, can you add an alert to if(ajaxRequest.readyState == 4){ I tried your JS though without the form stuff and it seems to work fine, http://jsfiddle.net/6gjy6/ Do you get any JS errors in Google Chromes console? Have you tried doing a basic "GET" request on the browser with the appripriate url ie delete_row.php" + queryString, and seeing how the server responds instead of the AJAX call.
try this:
var queryString = "?ID=";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += "-";
}
}
queryString = queryString.slice(0, -1);
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert("received: " + ajaxRequest.responseText);
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null);
I'm fairly sure you're supposed to set the onreadystatechange event after calling open, otherwise the handler is cleared.
keep your confirm() statement there while at the top of your js put
window.alert = null ;
and try
k let me check
I am very new to this
I have this link:
<a onclick = sendRequest('GET','room_chart.jsp') href=#>Show Chart</a>
but I need to generate dynamic address inside that link.
I created javascript:
<script language="javascript">
var selectedOption;
var ROOM;
var BUILDING;
function GetLink(){
selectedOption = document.getElementById("roomandbuildingid").options[e.selectedIndex].text; //getting selected option
ROOM = selectedOption.split("|")[0].trim().split(":")[1].trim(); //parsing text
BUILDING = selectedOption.split("|")[1].trim().split(":")[1].trim(); //parsing text
return "'room_chart.jsp?room="+ROOM+"&building="+ BUILDING+"'"; //returning url
}
</script>
but when I paste the function into it- it does not work!
<a onclick = sendRequest('GET',GetLink()) href=#>Show Chart</a>
Now, after debug, I found out that actually it creates the proper srting, but somehow my function is not willing to accept it as URL! It is quite a paradox- it creates correct string- if I hardcode it into the code- it works! But dynamic links from variables - don't work!
please help!
see below:
my js file:
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
// alert( document.URL );
// document.write (GetLink());
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
OK, the function was returning everything correctly, the parsing was not done right. I fixed it. JavaScript is hard for me to debug.