JSON file not being loaded because of not defined variable - javascript

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.

Related

js error : "'createObjectURL' on 'URL': Overload resolution failed."

I try to display an image on a php page in js, knowing that my image via an input file.
here is my code:
<script>
function image(){
var x = document.getElementById("image_uploads");
var test = URL.createObjectURL(x);
//document.getElementById("img").src = URL.createObjectURL(x);
}
</script>
<body>
<div class="frItem31">
<form name="saisie" action="" method="post">
Image 1 :<input type="file" id="image_uploads" class="image_uploads" name="image_uploads" accept="image/*"/>
<br>
<img id="img" class="img">
<br>
<input type="button" id="calcVitesse" class="calcVitesse" value="calculer la vitesse" onclick="image()">
</form>
</div>
</body>
here is the error I get:
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
at image (image.php:20:32)
at HTMLInputElement.onclick (image.php:80:125)
image # image.php:20
onclick # image.php:80
Could you help me please !?!
G.B.
you're passing an HTML element instead of a file. To get the file, use .files property, which behaves like an Array, so you can iterate it. see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#getting_information_on_selected_files
try this:
function image() {
var x = document.getElementById("image_uploads");
if (x.files.length) {
var test = URL.createObjectURL(x.files[0]);
}
}

Make POST and GET request to JSON server

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?

How to call one javascript variable to another javascript file

I have an HTMLForm which on click forward me to new HTML page i have Two JS files for each HTML
What i am doing and trying to achieve is :-
On 1st HTML when i click search button i am storing the values of input field and select field in different variables
What I am trying to achieve is when on search new page loaded I want to use that new variable into my new JavaScript
I have Two HTML files also
here is the code of my file1.html
<form id="formId" action="file2.html">
<div class="container">
<h4>Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>Outlets:</h4>
<select name="outlet" id="myselect">
<option>ALL</option>
</select>
<div>
<br>
<button id="btn-search" class="btn btn-default" type="submit">
<i class="fa fa-search"></i> Search
</button>
</div>
</div>
</form>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
In This HTML i have a form having one date field and one select field
On clicking submit Button I am Storing the values of date and Outlet into a variable in my JavaScript file which is JavaScript1
**Here is my JavaScript1 file **
$(document).ready(function() {
$("#btn-search").click(function(){
var currentlyClickedOutletform = $("#myselect").find(":selected")[0].textContent;
var currentlyClickedStartdateform= $("#startdate").val();
$.ajax({
url : "LinkReportMain",
method : "POST",
data : {
Outletlink : currentlyClickedOutletform,
Fromdatelink : currentlyClickedStartdateform,
},
});
});
});
var currentlyClickedOutletform and var currentlyClickedStartdateform are the two values i want to use in my new JavaScript file which is JavaScript2
my file2.html is
in this file i am just populating an HTML table so i only have an div tag inside
<div id="tbl"></div>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
<script type="text/javascript" src="JS/JavaScript2.js"></script>
And finally my JavaScript2 is
in this file I want to use the values of first Javascript file
$(document).ready(function() {
alert(currentlyClickedOutletform)
$('.loader').show();
$('.overlay').show();
$.ajax({
url: "LinkReportMain",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
fromdate: $("#startdate").val(),
todate: $("#enddate").val(),
outlet: $("#all").val()
},
success: function(data) {
let formatedData = formatData(data);
renderTable(formatedData);
$('.loader').hide();
$('.overlay').hide();
}
});
});
NOTE to see the code of JavaScript2 file please see the snippet its not working but my code was not getting formatted so I have put that into snippet
So what I am trying to achieve is to use the Variable of JavaScript1 into JavaScript2
i am doing it right but its not working any one out here who can guide em please, it would be very helpfull
Without localStorage
First set type="button" of you search button or prevent form submit by e.preventDefault(); on click event.
$("#btn-search").click(function(){
e.preventDefault();
// your other code
//code to redirect to another html page
var queryString = "?para1=" + currentlyClickedOutletform + "&para2=" + currentlyClickedStartdateform;
window.location.href = "page2.html" + queryString;
})
for other page script:
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var oldParam = queryString.split("&");
var param1 = oldParam[0];
var param2 = oldParam[1];
Now you can use param1 and param2.
**localStorage ** :
in first page store object :
localStorage.setItem("outletFrom",currentlyClickedOutletform);
localStorage.setItem("startDate",currentlyClickedStartdateform);
in seond page get data:
var currentlyClickedOutletform = localStorage.getItem("outletFrom");
var currentlyClickedStartdateform= localStorage.getItem("startDate");

How to convert form data into JSON data using AJAX?

I am a coding beginner, and I am currently learning how to code in javascript. I am stuck on a practice problem, where I must utilize AJAX in order to retrieve data from a form, convert the data into JSON and then append a message that uses the JSON data that was created. When I click the submit button, the success function doesn't seem to be working. I am also using JQUERY. My main question is, must I create a separate JSON file, or will the JSON data be produced on it's own when I submit the form.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="tour" data-daily-price="357">
<h2>Paris, France Tour</h2>
<p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p>
<form method="POST">
<p>
<label for="nights">Number of Nights</label>
</p>
<p>
<input type="number" name="nights" id="nights" value="7">
</p>
<input type="submit" value="book">
</form>
</div>
<script type="text/javascript" src="jquery-2.2.3.min copy 4.js"></script>
<script type="text/javascript" src="json.js"></script>
</body>
</html>
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax("http://localhost:8888/json.html", {
type: 'POST',
data: $("form").serialize(),
dataType: 'json',
contentType: "application/json",
success: function(data) {
var msg = $('<p></p>');
msg.append("Trip booked for " + data.nights+" nights.");
$(".tour").append(msg);
}
});
});
});
My main question is, must I create a separate JSON file
No. If you want to send JSON then you have to construct a string of JSON, but you don't need to make it a file.
or will the JSON data be produced on it's own when I submit the form.
No. You have to create the JSON yourself.
$("form").serialize() converts data into the application/x-www-form-urlencoded format. Don't use it if you want to send JSON.
There is no standard for encoding form data into JSON so you must loop over all the form controls (or the data in serializeArray) to build the data structure you want and then pass it though JSON.stringify.
Expanding on what Quentin said, you'll need to parse the fields and values out of the form yourself and put them in a JSON object. I've been using the following function (found on another stack overflow answer but I don't have the reference) which will iterate the form looking for named fields and then put that into a JSON object.
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
This function is added to the JQuery operator $ so can be called like
var data = $(this).serializeFormJSON();
And you can then use that directly in the AJAX call or stringify it first if necessary.
EDIT; meant to add that you should only call this inside of a form.submit callback as it will use the form as the this parameter.

How to output an alert message when embedded link does not exist?

I have this piece of code and I was wondering how I would be able to display an alert message when the embedded link does not exist. Is this possible?
<script type="text/javascript">
function soniaZsound(track) {
var link = 'https://ssl.gstatic.com/dictionary/static/sounds/de/0/'+track+'.mp3';
document.getElementById("myspan").innerHTML='<embed src="'+link+'"' +
'onError="alert("sorry this word is not in the database");"' +
'`autostart=true loop=false hidden=true` type="audio/mp3">';
}
</script>
<body>
<span id="myspan"></span>
<form name= "searchwords" id="searchwords">
How does this word sound: <input type="text" name= "soundSearch"><input type="button"
value="GO" onclick="soniaZsound(document.forms['searchwords']['soundSearch'].value);">
</form>
</body>
If you are allowed to read content from that domain you can do a HTTP HEAD request to see if the file exists:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error:
function(){
//file does not exists
},
success:
function(){
//file exists
}
});

Categories