How to call one javascript variable to another javascript file - javascript

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

Related

openweathermap weather data by zip code not working?

i need to make it so that when a zip code is typed into the box and the submit button is clicked, the name of the city shows up under it. when i click the button after putting a zip code the city name doesn't show up. it says the error is that wallOfText is not a function but i'm not sure how to fix it. any help would be appreciated!! here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
Enter your zip code:<br><input type="text" id="zipBox" name="zipCode"><br><br>
<button onclick="weatherFunction()">Submit</button>
<p id="result"></p>
<script>
function weatherFunction() {
var zip = document.getElementById("zipBox").value;
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" +zip+ ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function (wallOfText) {
city = wallOfText("name");
if (zip != null) {
document.getElementById("result").innerHTML = wallOfText;
}
}
});
});
}
</script>
</body>
</html>
The issue you have is that you're attempting to call wallOfText like it's a function, when in fact it's the object which has been deserialised from the response of the AJAX call. As such, you need to access the object's name property to set the city variable, then use that to set the text() of the #result element.
Note that the document.ready handler within the function is redundant, and you should be doing the zip value validation before you make the request. I also updated the logic to use jQuery to bind the event handler on the button instead of the outdated onclick attribute. Try this:
jQuery(function() {
$('#send').click(function() {
var zip = $("#zipBox").val();
if (zip !== '') {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function(wallOfText) {
var city = wallOfText.name;
$("#result").text(city);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your zip code:<br>
<input type="text" id="zipBox" name="zipCode" value="90210" /><br /><br />
<button type="button" id="send">Submit</button>
<p id="result"></p>

JSON file not being loaded because of not defined variable

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.

Create a dynamic dropdown form that loads its data from a JSON file using JQuery

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

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.

Onclick page should not reload

Hi how can i make my page don't reload every time i click another link?
function myFunctionD(id) {
var x=document.getElementById(id);
var myURL = "http:www.sample.php";
document.location = myURL + "?t_id=" + x.id ;
return false
}
HTML:
<a href="docview.php?id=26" id="3" onclick="myFunctionD('3')" target="iframe_a" >July 17, 2013</a>
<a href="docview.php?id=26" id="4" onclick="myFunctionD('4')" target="iframe_a" >July 18, 2013</a>
You can change the target to open the link in new tab or window . Use window.open() instead of window.location
You can use ajax something like this
<script type="text/javascript">
$(function(){ myFunctionD('3'){
var form = $(this).parent("form");
$.ajax({
type: "POST",
url: form.attr("yourform"),
data: form.serialize()
})
return false;
});
});
</script>
Actually you don't even need to use Ajax. You can simply load content of another page in your current page with Jquery's $.get function
//Inserting a div for holding another page content. On click of button, this div will update content
<div id="contentdiv"></div>
<input type="button" value="Page 1 Load Content" onclick="loadContent('page1.html')"/>
<input type="button" value="Page 2 Load Content" onclick="loadContent('page2.html')"/>
<input type="button" value="Page 3 Load Content" onclick="loadContent('page3.html')"/>
<script type="text/javascript">
function loadContent(page)
{
//Empty contentdiv for new content and add new page content with jquery's $.get
$('#contentdiv').empty();
$.get('http://www.example.com/'+page, function(data) { $("#contentdiv").append(data); });
//This will load page content in your contentdiv
//for more info about $.get visit this http://api.jquery.com/jQuery.get/
}
</script>
In your other pages, just put that content which you want to load into contentdiv. Do not make complete html page with html and body tags etc. Just content you want to appear in you contentdiv.

Categories