I have a JSON file called person.json. JSON file is in the data folder.
This is the JSON data:
{
"name": "Goa Wei",
"age": 31,
"phone": "202-555-0104",
"group": 3
}
I have the html code to display information in a div class called containerDatadump when clicking on <input id="get" type="submit" value="Get"></input>. I have written the following Javascript code.
var container = $("div.containerDatadump");
$(document).ready(function () {
$("input#get").click(function () {
$.ajax({
type: "GET",
url: "data/person.json",
dataType: "json",
success: function (data) {
$.each(data, function (index, item) {
$.each(item, function (key, value) {
container.append(key + " :" + value + "</br>");
});
container.append("<br/></br>");
});
}
});
});
});
I have done this. I try my best to debug the problem but couldn't succeed.
Can anyone help me figure out what is wrong with my code? It would really help me.
My answer looks like that of forgo but i think you can improve you code a little bit by using $.getJSON instead of a regular ajax call.
$.getJSON is a shorthand ajax call for (more info):
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
I also used JSON Generator for the data (LINK) to prevent browser issues.
Your code is a much cleaner this way (in my opinion).
$(document).ready(function () {
var container = $(".containerDatadump");
$("#get").click(function () {
$.getJSON("https://www.json-generator.com/api/json/get/ceoSrTPote?indent=2", function(data){
$.each( data, function( key, val ) {
container.append(key + " :" + val + "</br>");
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="containerDatadump"></div>
<input id="get" type="submit" value="Get"></input>
I think the biggest problem is that you defined your container outside of your $(document).ready function. This means that your markup doesn't exist yet to properly get a handle on your containerDatadump class.
I made a temporary JSON file hosted on a remote server using this JSON Generator tool to test. Otherwise, I run into CORS issues in my browser.
{
"phone": "202-555-0104",
"age": 31,
"group": 3,
"name": "Goa Wei"
}
With this data, I have modified your function to simplify the loop in your ajax success handler, and I have placed the container variable assignment inside the ready function so that it works properly:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var container = $("div.containerDatadump");
$("input#get").click(function() {
$.ajax({
type: "GET",
url: "http://www.json-generator.com/api/json/get/bOxnwzyhIO?indent=2",
dataType: "json",
success: function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + " -> " + data[key]);
container.append("<div>" + key + " :" + data[key] + "</div><br/>");
}
}
}
});
});
});
</script>
</head>
<body>
<input id="get" type="submit" value="Get"></input>
<div class="containerDatadump" />
</body>
</html>
Related
<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/
I need to dynamically create a list in JavaScript with a unique div id for each line. How do I do this?
HTML
The HTML code:
<ul class="sub-menu insert">
The ul class I am working with is "insert"
The JavaScript code has two functions:
The first JavaScript function
$(function() {
$.ajax({
type: 'GET',
url: 'json/data.json',
async: false,
beforeSend: function() {
},
dataType: 'json',
success: function(result) {
$(document).ready(function() {
var divsToAppend = "";
$.each(result, function(i) { //Item key
$("#insert").append += '<li id="' + i + '">"<div id="test_ID"' + i +'></div>" + '</li>');
});
});
}
});
Code snippet:
This is a String:
"<div id="test_ID" + i +></div>"
The first function one loops trough a JSON file, the intention is that it shall create a list, with as many lines as there is in the mentioned file. Each line in the list has to follow a certain syntax. And tt has to generate a unique div id for each line. The list connects with the ul class "insert" in the HTML code.
I want the generated list to look like this in HTML:
<li><div id="test_ID1"></div></li>
<li><div id="test_ID2"></div></li>
The unique div id that I mentioned:
"test_IDi"
The second JavaScript function
The second function connects with the unique "test_id" that is generated in the first function. It collects data from the JSON file. It works, but only when there is a single "div id". It has to be able to distinguish between the different unique "div id:s" that is generated by the first function.
$(function () {
$.ajax({
type: 'GET',
url: 'json/data.json',
async: false,
beforeSend: function () {/*loading*/
},
dataType: 'json',
success: function (result) {
$("#test_IDi").empty(); //Empty ID
$.each(result, function(i, v) {
$("#test_IDi").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>');
});
}
});
});
});
The JSON File (included for reference):
[
{"id": "a", "test": "Java", "testDate": "17-08-01"},
{"id": "b","test":"JavaScript","testDate": "17-08-02"}
]
How I wish that the finished list will look:
Java 17-08-01
JavaScript 17-08-02
Here you go.
Look at the below example:
var result = [{
data: ''
}, {
data: ''
}];
var jsonData = [{
"id": "a",
"test": "Java",
"testDate": "17-08-01"
}, {
"id": "b",
"test": "JavaScript",
"testDate": "17-08-02"
}];
$.each(result, function(index) {
$(".insert").append('<li><div id="test_ID' + index + '"></div></li>');
});
$.each(jsonData, function(index, value) {
$("#test_ID" + index).append('<li id="' + value.id + '">' + value.test + ' ' + value.testDate + '</li>');
});
$('#output-html').val($('#html-data').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="html-data">
<ul class="sub-menu insert">
</ul>
</div>
<div>
Output HTML:
<textarea id="output-html" rows="10" cols="55"></textarea>
</div>
I got a lot of valuable help from Gaurav to solve this. After I had worked a little more on the code I found a way to reduce it by removing "test_id", instead of adding the code from the second function directly to the loop that generates a new list element.
$(function() {
$.ajax({
type: 'GET',
url: 'json/data.json',
async: false,
beforeSend: function() {
},
dataType: 'json',
success: function(result) {
$(document).ready(function() {
$.each(result, function(i, v) {
$(".insert").append('<li>' + v.test + '</div></li>');
});
});
}
});
});
I am following a tutorial on YouTube but I couldn't make it run. Basically I have a country.json file.and I am trying to retrieve data inside it. What is wrong here??
This is how country.json file looks like
{
"name": "Germany",
"capital": "Berlin",
"pop": "some value"
}
JavaScript
var container = $("div.container");
$("input#get").click(function () {
$.ajax({
type: "Get",
url: "country.json",
dataType: "json",
successs: function (data) {
$.each(data, function (index, item) {
$.each(item, function (key, value) {
container.append(key + " : " + value + "</br>");
});
container.appendChild("<br/><br>")
});
}
});
});
HTML
<div class="container"></div>
<div id="form-area">
<h2>Get</h2>
<input type="submit" id="get" value="get">
</div>
You can get it like this:-
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div class="container"></div>
<div id="form-area">
<h2>Get</h2>
<input type="submit" id="get" value="get">
</div>
</body>
</html>
<script type="text/javascript">
var container = $(".container"); //check change here
$("#get").click(function () { //check change here
$.getJSON( "country.json", function( data ) {
var myhtml = ''; // create an empty variable
$.each(data, function (key, value) {
myhtml += key + ' : ' + value + '</br>'; // append data to variable
});
container.append( myhtml); // append the whole data (variable) to div
});
});
</script>
Output (on my local browser):- http://prntscr.com/cq2jjt
Note:- to read data from json file $.getJSON() is required.
Check more detail:- http://api.jquery.com/jquery.getjson/
You need https:\\ to run the Ajax, Simply in local file it will not work. Specially in Chrome. Use the Apache server in your machine and add all your file. And run the application through localhost. Ajax call will fire. Before to that, Try the same application in Firefox one. Firefox might do the ajax locally.
we can acheive this by using jquery library..
$.getJSON( "ajax/country.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$('#form-area').html(items.join(""));
});
I have a onclick function in which there is a javascript function that runs to fetch data from xml. it is with jquery. but its not working. help plzzz.
jsp page
<script>
function read() {
$.ajax({
url: "dictionary.xml",
datatype: "xml",
success: function data() {
$("ul").children().remove();
$(data).find("word").each(function () {
var info = '<li>Eng = ' + $(this).find("eng").text() + '</li><li>Beng = ' + $(this).find("beng").text() + '</li>';
$("ul").append(info);
});
}
});
}
</script>
<script src="WEB-INF/js/jquery.min.js" type="text/javascript"></script>
<script src="WEB-INF/js/jquery-2.1.0.min.js" type="text/javascript"></script>
<ul></ul>
Read
xml file
<?xml version="1.0" ?>
<corporate>
<word>
<eng>Male</eng>
<beng>Man</beng>
</word>
<word>
<eng>Female</eng>
<beng>Woman</beng>
</word>
</corporate>
Here you describe a function with no arguments, but with a local name:
success: function data() {
So, when you try to access data, you actually pass your function to jQuery, which does not make too much sense.
success: function data() {
$(data).find("word").each(... // here, data is a function
data should be an argument:
success: function(data) {
$(data).find("word").each(... // here, data is an XML object, passed to a handler
<script src="WEB-INF/js/jquery.min.js" type="text/javascript"></script>
<script src="WEB-INF/js/jquery-2.1.0.min.js" type="text/javascript"> </script>
remove any of these, as this will create two references to $ object.
put them into header or body tag, but before your script.
working version
function read() {
$.ajax({
url: "test.xml",
datatype: "xml",
success: function (data) { //change it to function(data)
console.log(data);//check what is comming...
$("ul").children().remove();
$(data).find("word").each(function () {
var info = '<li>Eng = ' + $(data).find("eng").text() + '</li><li>Beng = ' + $(data).find("beng").text() + '</li>';
$("ul").append(info);
});
}
});
}
I have a list of "User" with has Name, Surname and Email.
I need to loop through it on Jquery. This list is returned by a server side method
success: function (result) {
// var res = result.d
$.each(result, function (index, obj) {
alert(obj);
});
}
Does anyone know how it can be done?
Edit: The entire Ajax list:
var param = '{"NameofMap":"' + nofm + '", "VillNum":"' + numberV + '"}';
$.ajax({
url: 'GenerateMap.aspx/AddVill',
type: "POST",
data: param,
dataType: "json",
contentType: "application/json",
error: function (msg)
{ alert("Fails"); },
success: function (result) {
$.each(result, function (index) {
alert("Test");
});
}
});
This is the entire Ajax. It returns a list of Class instances ("User")
It displays "Test" but if I change that with alert(result[index].Name); , it displays just an empty box.
As you haven't provide proper information, still you can give this a try.
If you're getting into the success: and able to get alert, you can try like this:
You can have properties with it's name
--> result.Name
--> result.Surname
--> result.email
So Your code will be like following:
$.each(result, function(index) {
alert(result[index].Name);
.......
});
Or
$.each(result, function(index, item) {
alert(item.Name);
.......
});
This might help!
try
$.each(data,function(i, item){
alert(item.name)
});