I have a local json file which I am accessing data from. I have a text field and a button which gets populated by random entries from the file. The requirement is simple - on clicking the button, if I change the value of the text field, the same data should also be updated in the json file. How to do this?
I am using json-server to make the server-client connection but it is throwing below error -
GET http://localhost:3000/__rules 404 (Not Found) ( I don't know what __rules is here)
I simply ran the below commands from the vscode terminal-
npm install -g json-serevr
json-server --watch --api.json . (The json file and html file are in the same folder)
<html>
<body>
<form>
<label>Name:</label>
<input type="text" id="name" >
<input type="submit" value="Submit" id="fetch">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$( document ).ready(function(){
$.getJSON('api.json', function(data) {
albums = data['Albums']
var num = Math.floor(Math.random() * 3) ;
$("#name").val(albums[num].Name);
})
})
$('#fetch').click(function(e){
//e.preventDefault();
var strname = $("#name").val();
$.getJSON('api.json', function(data) {
albums = data['Albums']
$.post('api.json', function(data){
albums[num].Name = strname
})
})
});
</script>
</body>
</html>
{
"Albums": [
{
"Name": "Desire"
},
{
"Name": "Essentials",
},
{
"Name": "Hard Rain",
},
{
"Name": "Blackstar",
}
]
}
Can anyone tell me how to make this work? I am not much aware of node.js or any other server side technology. I tried the above method and several others but nothing is working. What might I be doing wrong?
Related
Basically I have a .json file, and I want to make a html page that someone can fill out a form, and the information in the form will change variables in the JSON file.
Example:
The json file (for example):
{“title”: “(variable)”}
then when the html form is submitted it will read (variable) as what was entered into the form.
It depends on what you have on the backend (Node, python, etc)
Welcome to Stackoverflow, seeing that you have NodeJS, you may want to establish some sort of communication from your back end to front end. Let's say you're using websockets. Here is how information would be passed:
userData.json:
{
name: "Mishra",
age: 89
}
server.js:
const app = express()
const server = app.listen(3000) // setup express server
const io = require('socket.io').listen(server); // using websockets
let userData = require('./userData.json');
// on socket connection event
io.on('connection', (socket) => {
socket.on('updateName', name => { // when updateName is called
userData.name = name // set JSON var to new name
})
}
// method to save JSON file goes here
myForm.html:
<head>
<script type="text/javascript" src="your/path/to/socket.io.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
Set name:
<input type="text" id="nameField" name="fname"><br>
<input type="submit" value="Submit" id="submit">
<script>
document.getElementById("submit").onclick = () =>{
socket.emit("updateName", document.getElementById("nameField").value)
}
</script>
</body>
I have a a python script which is being fed and executed from a html file. This script writes a json file and i'd like to read the json file with javascript. The values are definetely being passed from html to python and they are being processed correctly.
As soon as I want to load the json-file the web console throws an error saying "data is not defined".
The relevant python code:
data = {}
for i in range(t_final.size):
data[i] = t_final[i]
with open('data.json', 'w') as fp:
json.dump(data, fp)
Javascript call:
<script type="text/javascript" src="/cgi-bin/data.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
var div = document.getElementById('xbtn');
}
</script>
<div id="xbtn"></div>
This is what the json-file contains after executing
{"0": 0.0, "1": 0.013508013525931116, ... , "1999": -0.0}
I am working on this for days now and maybe I just don't see it. I presume it is something very obvious.
thanks for any help.
So. I have managed to set up ajax properly. The problem was that the endpoint was set wrong (obviously). So the data to be processed was sent to the json-file and not to the python script where it is supposed to be processed.
The ajax:
$(function(){
$('#btn2').click(function(){
$.ajax({
url: 'https://192.168.80.27/cgi-bin/verlauf_Grenzen.py',
type: 'post',
data: $('.senddata').serialize(),
success: function(data) {
window.alert("Data sent!");
},
});
});
});
the HTML:
<form class="senddata" method="POST" name="getdata1">
<input id = "testa1" type = "number" step=0.01 name = "a1" />
<input id = "testv1" type = "number" step=0.01 name = "v1" />
<input id = "tests1" type = "number" step=0.01 name = "s1" />
<input id = "testj1" type = "number" step=0.01 name = "j1" />
</form>
<input id="btn2" class="button" type="button" value="Send Values" value="Click"/>
This sends the form elements to the python script.
In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
I am relatively new to JavaScript and subsequently Node + Express.IO. I am trying to build a page that will track in real time connections made by different 'users' to the server. Consequently, when I do include all the functions from the io module, my prompt() and alert do not work anymore. I am running nodemon app.js from my terminal and no compilation errors are showing up when I do so. The alert and prompt work again when I remove all the io functions.
These are the contents of my index.ejs <body> tag:
<body>
<h1>Chatroom</h1>
<script>
alert("Hello!");
var name = prompt("What is your name?");
io.connect();
io.emit.('got_a_new_user', {name: name});
io.on('new_user', function(data) {
//render this new info in the HTML
var users = data.users;
console.log(users);
if (users != undefined) {
console.log("\n\n\n" + users);
// if users is defined, append the new division containing the username
}
});
io.on('disconnect_user', function(data) {
var users = data.users;
if (users != undefined) {
// If users is defined remove the corresponding HTML element
}
});
</script>
<div id="container">
</div>
</body>
Any help would be much appreciated.
Adding example for the comment added by UKatz,
You will have to connect socket.io from the client as follows,
index.ejs
<script src="http://ip:port/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://ip:port');
socket.emit('got_a_new_user', {name: name});
</script>
Check socket.io documentation for how to connect socket.io with client.
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js",
function(json) {
var ticketPriceArray=[json.tickets[0].price, json.tickets[1].price,
json.tickets[2].price, json.tickets[3].price, json.tickets[4].price,
json.tickets[5].price];
alert(json.tickets[0].type);
var inputWord =$("#keyword").val();
if (inputWord=="A"){$("#result").text(ticketPriceArray[0]);}
if (inputWord=="B"){$("#result").text(ticketPriceArray[1]);}
if (inputWord=="C"){$("#result").text(ticketPriceArray[2]);}
if (inputWord=="D"){$("#result").text(ticketPriceArray[3]);}
if (inputWord=="E"){$("#result").text(ticketPriceArray[4]);}
if (inputWord=="F"){$("#result").text(ticketPriceArray[5]);}
});
});
});
</script>
Here is "ticketPriceInArray.js"
{
"tickets":[
{
"type":"A Ticket",
"price":220,
},
{
"type":"B Ticket",
"price":180,
},
{
"type":"C Ticket",
"price":120,
},
{
"type":"D Ticket",
"price":100,
},
{
"type":"E Ticket",
"price":80,
},
{
"type":"F Ticket",
"price":50,
}
]
}
This is a simple html where when the corresponding text inputed, the corresponding ticket price will show in the html after a button-click. All the ticket info is stored in a .json file named "ticketPriceInArray.js" and I have been trying to read it using $.getJSON(), but unfortunately I haven't been able to get any success. The weird thing is I didn't get any warning on anything so I couldn't fix it. Please see if you can give me any suggestions. Thank you.
By adding an AJAX error handler, I received this
"parsererror" SyntaxError: Unexpected token }
The problem is the trailing commas after each price property.
The following example is working fine in FF and Chrome with the exact JSON you provided. In IE you will have to remove the commas after the prices, as Phil already said.
In my test both the test.html and test.js were placed in my apache server root; viewing the files directly from my desktop into my browser didn't work apparently due to security restrictions.
<html>
<head></head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("test.js", function(json) {
for (var i in json.tickets) {
var type = json.tickets[i].type;
var price = json.tickets[i].price;
$('#result').append('<span>type: ' + type+ ', price: ' + price + '</span><br />');
}
});
});
});
</script>
<button id="Button1">click me</button>
<div id="result"></div>
</body>
</html>
I suggest you use http://jsonlint.com/ to validate your JSONs; or just rely on a good encoder instead of doing it by hand ;)
A little bit different approach to solving this problem. This is assuming that you aren't changing your ticket prices based on some data that you pass to the url.
ticketPriceInArray.js
{
"A" : 220,
"B" : 180,
"C" : 120,
"D" : 100,
"E" : 80,
"F" : 50
};
main file
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
var ticket_prices = {};
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js", function(returnedJSON) {
ticket_prices = returnedJSON;
$("#result").text( ticket_prices[ $("#keyword").val() ] );
});
});
});
</script>
If there are any considerations (or questions about my assumptions) let me know and I will update based on that.
Assuming the following facts:
you're using firefox
there is no traffic in the network-tab when you click on #Button1
there are no errors logged
... I would like to say:
the element you click on is not $("#Button1")
Are you sure that the element you click on has the ID "Button1" and that there is only one element using that ID ?
Are you running this from a webserver or from your local filesystem?