Retrieve Value from JSON using AJAX - javascript

I am new with json and ajax. I would to ask for assistance on how to Retrieve JSON value using AJAX.
Here is my json file named as list.js
{
"loginid" : "Wafiqa",
"password": "123"
}
and here is my html fille named as ajaxTest.html
<body>
<p> Username: </p>
<div id="uname"></div>
<p> Password: </p>
<div id="pword"></div>
</body>
What I want to do is the value from username in json file will be displayed at uname div and the password will display at pword div. How can I do that?

Once you're just starting to learn JavaScript, it would be easier for you to just put your JSON data in a variable.
var jsonData = {
"loginid" : "Wafiqa",
"password": "123"
};
and then you insert it in the DOM with something like
document.getElementById(uname).innerHTML = jsonData.loginid;
document.getElementById(pword).innerHTML = jsonData.password;
If you want to use the json in another file you should serve it as a static asset or use some server-side code to render it.

You cannot access a local file. You will need the json file to be served from a server. You can run your code form a web server.
You can use the jquery#getJSON function for this.
For sample, in your html head section have
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="images"></div>
<script>
(function() {
$.getJSON( 'http://date.jsontest.com/', {
format: "json"
})
.done(function( data ) {
alert(data.date);
});
})();
</script>
</body>
</html>

Related

anaconda enterprise python read external json in HTML

My python code creates HTML files. I work on Anaconda Enterprise and my problem is that I want to read an external json file in javascript encapsulated in HTML
message = """
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="sample.json"></script>
</head>
<body>
<p id="GFG_DOWN" style="color: green; font-size: 20px; font-weight: bold;"></p>
<script>
function pointe_vers_doc(clicked) {
var test = document.getElementById("GFG_DOWN");
var mydata = JSON.parse(data);
test.innerHTML = "Value of my json = "+mydata[0];
}
</script>
</body>
</html>
"""
Here is the external json (sample.json) I want to read :
data='[["first", "second"], [], ["fourth"], [], [], ["seventh"]]'
Locally it works but on the server (AE) I think it does not find the path to sample.json
I tried to change the path several times by testing but it doesn't work.
Is there another way to proceed ?

Importing Data fom JSON-File into JavaScript

The "console-log(states)" line in he HTML File returns an "undefined".
Does anyone know why?
My goal here is to store the data from the JSON-File in a JavaScript-Variable.
The result should be a list that contains 3 dictionaries.
Both files are in the same directory.
Thanks a lot for any help!
HTML-File
<html>
<head>
<script type="text/javascript" src="states_Ex1.json"></script>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<script> var states=states_Ex1.json</script>
<script>
console.log(states) // --> undefined
</script>
</body>
</html>
JSON-File
[
{
"gene1": true,
"gene2": true,
"nextStateIndex": 1
},
{
"gene1": true,
"gene2": false,
"nextStateIndex": 2
},
{
"gene1": true,
"gene2": true,
"nextStateIndex": 1
}
]
New Answer
I've found a series of answers here for accessing local JSON files.
I tried #seppoo0010's method and it works on my end. Give it a shot:
$.getJSON("your-path-to-file.json", function(states) {
console.log(states); // this will show the info it in firebug console
});
You'll need to parse the JSON. Try this:
...
var states = JSON.parse(states_Ex1.json)
...

How can I save edited JSON file to web server using JSONEditor?

I'm using the JSONEditor (https://github.com/josdejong/jsoneditor) to load a json file, make changes and save the file. This works great but it only saves the JSON file to the folder specified according to your browser settings. Here's the demo code (https://github.com/josdejong/jsoneditor/blob/master/examples/04_load_and_save.html):
<!DOCTYPE HTML>
<html>
<head>
<title>JSONEditor | Load and save</title>
<link href="../dist/jsoneditor.css" rel="stylesheet" type="text/css">
<script src="../dist/jsoneditor.js"></script>
<script src="https://bgrins.github.io/filereader.js/filereader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<style>
html, body {
font: 11pt sans-serif;
}
#jsoneditor {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<h1>Load and save JSON documents</h1>
<p>
This examples uses HTML5 to load/save local files.
Powered by FileReader.js and
FileSaver.js.<br>
Only supported on modern browsers (Chrome, FireFox, IE10+, Safari 6.1+, Opera 15+).
</p>
<p>
Load a JSON document: <input type="file" id="loadDocument" value="Load"/>
</p>
<p>
Save a JSON document: <input type="button" id="saveDocument" value="Save" />
</p>
<div id="jsoneditor"></div>
<script>
// create the editor
var editor = new JSONEditor(document.getElementById('jsoneditor'));
// Load a JSON document
FileReaderJS.setupInput(document.getElementById('loadDocument'), {
readAsDefault: 'Text',
on: {
load: function (event, file) {
editor.setText(event.target.result);
}
}
});
// Save a JSON document
document.getElementById('saveDocument').onclick = function () {
// Save Dialog
fname = window.prompt("Save as...");
// Check json extension in file name
if(fname.indexOf(".")==-1){
fname = fname + ".json";
}else{
if(fname.split('.').pop().toLowerCase() == "json"){
// Nothing to do
}else{
fname = fname.split('.')[0] + ".json";
}
}
var blob = new Blob([editor.getText()], {type: 'application/json;charset=utf-8'});
saveAs(blob, fname);
};
</script>
</body>
</html>
I want to be able to save the file to the web server. Is there any way for me to save the edited JSON file to the web server? I searched and tried to integrate this library with JSONEditor but no joy:
https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
I'm not restricted to ajax so I'll consider anything that works!
Thanks for your advice.
John
UPDATED: Here's the controller code chunk.
// POST api/values
public async void Post()
{
string json = await Request.Content.ReadAsStringAsync();
File.WriteAllText(
HttpContext.Current.Server.MapPath("~\\App_Data\\somefile.json"),
json
);
}
I tested this using Postman and it works. What I can't seem to do for the life of me is to now send the edited JSON file to the controller. Here's the modified HTML page where I try unsuccessfully to send the json. For brevity, I'll just add the extra/edited code code:
<form id="form1" method="post" enctype="text/plain" action="http://localhost:1651/api/values">
<input type="file" name="json" id="loadDocument" value="Load"/>
<input type="submit" value="Save" />
</form>
Edited javascript where I try to return the edited json to the form:
document.getElementById('saveDocument').onclick = function () {
return editor.getText();
};
Please help! How do I send the json to the controller?

How To get Text Area Data (Html File in Text area) using ajax And i need to send data to Php ? Ajax not sending my Text area data?

If I'm trying to send Html Data in textarea Code is failed. alert Working till Username data getting properly but ajax not sending my Data to Php server.
Javascript
var username=document.getElementById( "my_text" ).value;
if(username){
$.ajax({
type: 'post',
url: 'checkdata.php?username=username',
data: {
username:username,
},
success: function (response){
$( '#name_status' ).html(response);
if(response=="OK"){
return true;
}
else{
return false;
}
}
});
Html
<textarea id="my_text" >
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
</textarea>
There are a couple of places your code could be breaking down. This would be easier for us to help with if you provided console logs of errors.
1) If you haven't loaded jQuery yet then the $.ajax() won't be called. You may also need to do $(document).ready(); to make sure everything is loaded.
2) You are wrapping an entirely new DOM inside of a textarea. I'm not sure if that's a copy/paste mistake but it'll have strange effects on the result.
3) After your response it's apparent that you are actually trying to send html to the server..? Your error code from console suggests there's plenty else going on. It's hard to know how to help if we don't see everything. i.e. PHP and the rest of the client code.
3) Since your if statement isn't wrapped in a function call it is evaluated at runtime. So the code runs at the page load but nothing triggers it later. Which means username is always null.
If you want to fix this you need something to trigger the event. You can try:
HTML
<body>
<textarea id='my_text'></textarea>
<button id="submitButton">Submit</button>
</body>
JS
let sub = document.getElementById('submitButton');
sub.addEventListener('click', function(){
let username = document.getElementById('my_text').value;
if(username){
// Add Ajax Call Here
}
});
Backup.html or php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Text editor</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
function view_text () {
var username=document.getElementById( "my_text" ).value;
console.log(username);
if(username){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
username:username,
},
success: function (response){
$( '#name_status' ).html(response);
if(response=="OK"){
return true;
}
else{
return false;
}
}
});
}
else{
$( '#name_status' ).html("");
return false;
}
}
</script>
</head>
<body>
<input type="button" value="Execute >>" onclick="view_text()" class="button"/>
<textarea id="my_text" >
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
</textarea>
<span id="name_status"></span>
</body>
</html>

How to load a local JSON file using JavaScript to update a select list inHTML?? (Expecting simple answers, I'm just a beginner)

This is what I want:
I want to add or remove countries from a 'countries.json' file, which stored in my local. This is just a test to understand json. Please help me.
<html>
<head>
<title></title>
</head>
<body>
<select name="countries" id="countries"></select>
</body>
<script src="dropdown.js"></script>
</html>
Got the answer:
This is how I loaded json using my js:
$(function() {
$('#countries').click(function(){
$.getJSON('dropdown.json', function(data) {
countries = data['countries']
$.each(countries, function(id, country) {
$('select').append('<option value="">' + country["countryName"]+'</option>')
})
});
})
})

Categories

Resources