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
Related
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>
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 need another set of eyes, as I'm going backwards at this point. Have php/javascript to autoupdate a 'shopping cart' as the user inputs data. However, there seems to be a conflict between codes. This is my first time implementing AJAX methods. The table that you can see in the HTML needs to allow for user input, then uses the JS to communicate with the PHP. However, at this juncture, that's not happening.
The user should see a value change 'onchange' as you can see.
Here's enough HTML to see user input/return:
<html>
<head>
<script src="PurchaseTableClientSide.js"></script>
</head>
<body>
<form>
<table border="1">
<tr>
<th>Item Name<br></th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
<tr>
<td>CD 1<br></td>
<td>$12.50</td>
<td><input type="number" id="quantityCD1" step="1" min="0" onchange="calculatePrice()"></td>
<td id="totalCD1">0.00</td>
</tr>
Here's the PHP:
<?php
error_reporting(0);
//variable to store the result.
$xml = new SimpleXMLElement("<response/>");
if(isset($_GET['qCD1']) && isset($_GET['qCD2']) && isset($_GET['qMVA'])) {
$totalCD1 = 12.50 * $_GET['qCD1'];
$totalCD2 = 12.95 * $_GET['qCD2'];
$totalMVA = 19.95 * $_GET['qMVA'];
$subtotal = $totalCD1 + $totalCD2 + $totalMVA;
$shipping = $subtotal * 0.5;
$total = $subtotal + $shipping;
//http://php.net/manual/en/simplexmlelement.addchild.php
$xml->addChild('totalCD1', $totalCD1);
$xml->addChild('totalCD2', $totalCD2);
$xml->addChild('totalMVA', $totalMVA);
$xml->addChild('subtotal', $subtotal);
$xml->addChild('shipping', $shipping);
$xml->addChild('total', $total);
$xml->addChild('error', False);
} else {
//Inform the client that there was an error.
//Currently not used, but sounds like a cool idea.
$xml->addChild('error', True);
}
//Define the content as being XML response
header("Content-Type:text/xml");
//Send it back to the user
echo $xml->asXML();
?>
And here is the javascript:
//Global variable for the AJAX connection.
var xmlHttp;
function calculatePrice()
{
var quantityCD1 = document.getElementById("quantityCD1").value;
var quantityCD2 = document.getElementById("quantityCD2").value;
var quantityMovieA = document.getElementById("quantityMovieA").value;
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="purchaseTable.php";
url=url+"?qCD1="+quantityCD1;
url=url+"&qCD2="+quantityCD2;
url=url+"&qMVA="+quantityMovieA;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
//Check to make sure the response is good.
if (xmlHttp.readyState==4) {
//Get an XML parser out of it.
var xmlDoc = xmlHttp.responseXML.documentElement;
//Pull the data from the XML response and put it in the HTML.
//http://www.ajaxtutorial.net/index.php/2006/02/28/ajax-with-php-using-responsexml/
document.getElementById("totalCD1").innerHTML = xmlDoc.getElementsByTagName('totalCD1')[0].firstChild.nodeValue;
document.getElementById("totalCD2").innerHTML = xmlDoc.getElementsByTagName('totalCD2')[0].firstChild.nodeValue;
document.getElementById("totalMVA").innerHTML = xmlDoc.getElementsByTagName('totalMVA')[0].firstChild.nodeValue;
document.getElementById("shipping").innerHTML = xmlDoc.getElementsByTagName('shipping')[0].firstChild.nodeValue;
document.getElementById("total").innerHTML = xmlDoc.getElementsByTagName('total')[0].firstChild.nodeValue;
}
}
//Connect to the PHP server.
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
I have data on a website which looks like this
[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]
I have a html file with javascript code as follows:
function httpGet(url) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
var data = xmlHttp.responseText;
data = (JSON.parse(data));
I need to access the "name" attribute from the URL database and form a string concat of all the name attributes. Could you please help me out what to be done next?
Below is my test data
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name);
For Example if you want to acces the name you can access as like above.
To concatenate the vales do like below
var Output = json.map(function(result) {
return result.name;
}).join('');
alert(Output);
Have a look on it https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var result = data.map(function(user) {
return user.name;
}).join('');
<html>
<head>
<script type="text/javascript">
function fun(){
var str='[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]';
var obj=eval(str);
var names='';
for(var item in obj){
names+=obj[item].name;
}
alert(names);
}
</script>
</head>
<body>
<input type="button" onclick="fun()" value="click me"/>
</body>
</html>
I got what you mean.It is the Ajax problem.If you really use the code that you provided,it should not work.Here is the Ajax code to get response from a certain url:
var ajaxRequest;
//create ajax object
function createAjaxRequest() {
var xmlhttp = null;
if (window.XMLHttpRequest) {// code for all new browsers
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
//send request and identify callbak handler
function send(url) {
ajaxRequest = createAjaxRequest();
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
// the callback handler
function callback() {
if (ajaxRequest.readyState == 4) {// 4 = "loaded"
if (ajaxRequest.status == 200) {// 200 = OK
var data = ajaxRequest.responseText;
}
else {
alert("Problem retrieving data");
}
}
}
I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>