How to read a local JSON file - javascript

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(""));
});

Related

How to use for while or something like for while to sending data when trying to post something using jquery

I have some code like this :
<script>
for(i=0;i<=5;i++){name[i]: "name",}
</script>
and i know it's wrong because i want to use it on $.post and i don't know how can i do this
I tried this and this working well but I didn't add for while to this code because I don't know how to do this and i will show you where i want for while :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg",
// for(i=0;i<=5;i++){name[i]: "name",} // it's my custom data and its not working
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
You should create an array of objects and then post that array with all the data to the server.
Something like this:
$(document).ready(function() {
$("button").click(function() {
var data = []; // create an array
//create your loop
for (i = 0; i <= 5; i++) {
var obj = {}; // create an object
obj.name = "Insert name here"; // insert any property you need... you can even fetch the values from a dom object (like an input).
data.push(obj); // add the object to the array;
}
// create your ajax request. Send it as JSON by converting the array (using JSON.stringify) and specifying the content type (json)
$.post("demo_test_post.asp",
JSON.stringify(data),
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}, 'json');
});
});
I found way to do this and it's working:
<script>
var data=[];
for(i=0;i<=5;i++){data.push(i)}
$.post( "test.php", { 'data[]': data } );
</script>
And in test.php i will receive $_POST['data'] as an array than i can do like this :
<?php
for($i=0;$i<=count($_POST['data'])-1;$i++){
print_r($_POST[$i]);
}
?>

Retrieving data from json File

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>

populate select option with JSON data

I have seen many examples and I have used this myself in many of my programs but for some reason this doesn't want to work today.
I have JSON data that I can show in console.log but it is unusable in my select. I get this error in my console:
Cannot use 'in' operator to search for '76' in {"hello1":"hello1","hello2":"hello2"}
This is my code:
$.get("JSON.php?value=two", function(response) {
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}
if (response != '') {
$('#dropdown').find('option').remove();
$.each(response,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value + '</option>');
});
}
)};
I just tested this successfully
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
var response = {"hello1":"hello1","hello2":"hello2"} ;
$('#dropdown').find('option').remove();
$.each(response,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value + '</option>');
});
});
</script>
</head>
<body>
<select id="dropdown"></select>
</body>
</html>
Please check. You will get something
To achieve this your response should be an Array of Objects.
[
{
hello1 : "hello1"
},
{
hello2 : "hello2"
}
]
Solution
Worked when Array was converted to Object
$.get("JSON.php?value=two", function(response)
{
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}
if (response != '')
{
var response2 = JSON.parse(response);
$('#dropdown').find('option').remove();
$.each(response2,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value +
'</option>');
});
}
)};

Events not triggered when posting json string using jquery [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
Closed 8 years ago.
I'm totally new to this, so apologies if I'm not explaining this correctly.
I want to post some data in json format to a rest service. I'm trying to get this work with JQuery in a simple .cshtml (razor) page.
My json string looks like this:
{
"ListRequest":{
"Values":[
{
"Name":"SC",
"Value":"PRO001"
},
{
"Name":"PC",
"Value":"Z0R14"
}
]
}
}
I need to pass 2 values from a form into this string and then post it but I'm not sure how do I declare this in javascript and then post it to my $.post function.
My HTML looks like this:
<form action="/" id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
I thought I'd just declare a var:
var jsonText = '{"ListRequest":{ "Values":[' +
'{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
'{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
Is that the correct way to handle this??
Then I've got my 'post' code to test:
var posting = $.post( url, term);
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
But whenever I call this, it put these 2 values as part of a query string, instead of doing an actual post where this data is not visible in the url.
http://localhost/WebTest/WebDataService.svc/GetList?txtSC=brc001&txtPC=12345
Can someone tell me how to fix this??
Thanks.
UPDATE:
Here is the full code from my test page as it still not working for me. I just noticed that the submit event is not triggered. It seems to be putting the textbox and value automatically because they are part of the form, but my event is definitely not triggered as I've just commented all the code and put a alert('test'); and it didn't show up.
Any ideas?
Thanks.
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
// Attach a submit handler to the form
$("#getListForm").submit(function (event) {
event.preventDefault();
//var jsonText = '{"ListRequest":{ "Values":[' +
// '{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
// '{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonText, url = 'http://localhost/WebTest/DataService.svc';
$.post(url + '/GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// Send the data using post
//var posting = $.post( url, term);
//posting.done(function (data) {
// var content = $(data).find("#content");
// $("#result").empty().append(content);
//});
});
</script>
#{
ViewBag.Title = "Json Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
<div id="result"></div>
Thanks.
UPDATE:
Latest code where I've updated the term to use the jsonObj and I've put my code in the $(document).ready block as suggested:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Attach a submit handler to the form
$("#getDocumentListForm").submit(function (event) {
event.preventDefault();
alert('test1');
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PO",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonObj, url = 'http://localhost/WebTest/DataService.svc';
alert(term);
alert(url);
$.post(url + 'GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
//Tried posting using term but no luck. Same problem.
//$.post(url + 'GetList',
//function (data, status) {
// alert("Data: " + data + "\nStatus: " + status);
//});
// Send the data using post
//var posting = $.post(url, term);
//posting.done(function (data) {
// //var content = $(data).find("#content");
// //$("#result").empty().append(content);
// alert(data)
//});
alert('test2');
});
});
</script>
#{
ViewBag.Title = "Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getDocumentListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get Document List">
</form>
<div id="result"></div>
Finale Update on this question
MAKE SURE:
NOT TO USE IE11 WITH JQUERY, WELL AT LEAST JQUERY 2.1.1! DON'T KNOW HOW WELL IT WORKS WITH OTHER VERSIONS OF IE.
ALWAYS TEST WITH OTHER BROWSERS
MAKE SURE TO SET YOUR JQUERY SRC TO THE CORRECT HTTP OR HTTPS DEPENDING ON WHAT YOU USE.
That's it.
I suppose what's going on there is that you are trying to pass an undefined variable named term instead of jsonText, so the javascript code is throwing an uncaught exception and gets ignored, and you get a normal action from your form element.
You should pass the correct data. And also, knowing about JSON.stringify can probably save you a lot of time and headaches ;). You could build your object like so:
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
};
var jsonObj = JSON.stringify(obj);
Another pitfall I can think of in your code, is that you have bound your AJAX to a click event on your submit button, or to an onsubmit event, and you are not preventDefault()ing.
Edit
Given the code you posted, you have a couple of mistakes:
Did you wrap your code into a jQuery(document).ready() block?
You commented out jsonText but still assign it to the variable term, causing an uncaught exception.
Fix these two things and your POST request will be done correctly.
On the other hand, why on Earth are you using jQuery version 1.5?

How to load JSON data associated with each link onclick?

I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.

Categories