How to convert form data into JSON data using AJAX? - javascript

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.

Related

Passing data from dropdown => to javascript function (Google App script)

Hopefully I've included enough of the code w/o having to post it all...
I have a main function that calls displayDropdown()- which calls an HTMLService and displays a modal with a dropdown and a text box:
.
This is the (condensed) javascript code that stores the data:
<html>
<input type="submit" value="Submit" class="action" onclick="sendData()" />
</html>
<script>
function sendData() {
var values = {};
values.textJob = document.getElementById("input").value;
values.selectedJob = document.getElementById("dropJob").value;
google.script.run.withSuccessHandler(closeIt).grabData(values);
};
function closeIt(){
google.script.host.close()
};
</script>
Then the grabData() function in my .gs file:
function grabData(values) {
if(values.textJob=="")
//return values.selectedJob;
Logger.log(values.selectedJob);
else
//return values.textJob;
Logger.log(values.textJob);
}
If I keep the returns commented out and try to log the data, I get the expected data logged. But if I reverse that, and return it instead, go back up to the main function just after displayDropdown() was called, and set a variable to equal the grabData function:
displayDropdown();
var stuff = grabData();
Logger.log(stuff);
I get an error that says:
Why can't I access the data?
This is what I usually do to send data from HTML form to GS:
HTML
<form method="POST" action="#" id="formID">
<button class="btn" type="submit">Send</button>
</form>
JS
document.querySelector("#formID").addEventListener("submit", function(e) {
var test = google.script.run.withSuccessHandler('client side function').processForm(this);
});
I usually pass 'this' as an argument and I process the information on the GS.
EDIT:
GS
function processForm(values){
Logger.log(values);
Logger.log(typeof values);
}
Screenshoots:
1- Web app
2- Server logs (function processForm)

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

Javascript/Jquery JSON File Upload

I have to create a html list with one li name import . On back i have create input type ="file" which will be hidden .
If user click on import it should fire file upload from back using .click()[![enter image description here][1]][1].
Once the use select the .json file it can be of any name ..
Then On click of open button of file upload it should save the json and pass the json object with an event dispatcher . I have create event dispatcher but not able to get json
Issue : I am not able to save the json object using .onChange and also .onChange work single time then i have to refresh then it work again.
Requirement: On click of import button, hidden file import will fire then on selecting the json file of any name (json filem can be of any name) function will save the json object and json object will be sent using iframe using event dispatcher .
Issue:: Not able to save the json or get the json . I tried getjson but it if for single file name .
<!DOCTYPE html>
<html>
<meta charset="UTF-8"/>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function (){
$('#import').click();
});
$('#import').on('change',function () {
// not able to get json in a json object on selection of json file
var getJson = $('#import')[0].files;
// dispatcher just take json object and it will send to iframe .
// WindowDispatcher("Send Json", getJson);
});
});
</script>
</head>
<body>
<input type='file' id='import' style = "display:none" accept='.json ' aria-hidden="true" >
<ul>
<li>
<button id="importLink" >import</button>
</li>
</ul>
</body>
</html>
$(document).ready(function(){
$("#importLink").click(function(){
$("#import").click();
});
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
$("#import").on('change',function(e){
var file = e. target. files[0];
var path = (window.URL || window.webkitURL).createObjectURL(file);
readTextFile(path, function(text){
var data = JSON.parse(text);
console.log(data);
//Your ajax call here.
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="file" id="import" style="display:none" accept='.json' aria-hidden="true" >
<ul>
<li id="importLink">import</li>
</ul>
<output id="list"></output>
<div id="name">list</div>
<div id="age">list</div>
Read file from e. target. files[0];
Off what I can see, you are missing an argument list for your import onChange listener.
In the first image, you are calling $'#import').click() -- you are missing the leading (
you should be getting a javascript error when running the code you mentioned, since you don't include at least an empty argument list when the file input changes, though I could be wrong.

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

jQuery/XML: synchronizing data and representations using DOM-Mutation-Events

I'm creating a web application which uses jQuery to modify and HTML to represent the data. There can be several representations in the document related to a single data node. The user can dynamically create them.
For example, data will be represented and can be modified in tables. Additionally the user has the opinion to extend a "quick-overview-panel" to access specific data quickly.
If one user-control triggers an event => data must be modified => other user-controls related to the same data need to be refreshed.
<html>
<head>
<title>synchronize</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//handling data
$.ajax({url: "./data/config.xml", cache: false, async: false, success: init});
var data;
function init(d) {
data = d;
$(".bottle", data).bind("DOMAttrModified", notifyRep);
}
function notifyRep(e) {
if(e.relatedNode.nodeName == "content")
$(this).trigger("changeContent");
}
//handling representation-sync
$(".bottle", data).bind("changeContent", function() {
$("#bottleRep1").val($(this).attr("content"));
});
$(".bottle", data).bind("changeContent", function() {
$("#bottleRep2").val($(this).attr("content"));
});
//handling modification
$("#bottleRep1").bind("change", function() {
$(".bottle", data).attr("content", $(this).val());
});
$("#bottleRep2").bind("change", function() {
$(".bottle", data).attr("content", $(this).val());
});
});
</script>
</head>
<body>
<div id="app">
<span>bottle-content:<input id="bottleRep1" type="text" value="test" /></span>
<span>bottle-content:<input id="bottleRep2" type="text" /></span>
</div>
</body>
The actual problem is that each user-control handles its own modification. The change-content handler needs to know the data-modifier, so it can skip the representation-update.
Is there an existing general solution for this kind of problem?
If not, can you make suggestions for a good solution?
you can try to create a custom function that will handle the perform some action when trigger for refresh
$('body').bind('foo', function(e, param1, param2) {
alert(param1 + ': ' + param2); });
then you can call the above created function on chnage of dta so the function get trigger and perform refresh like this
$('body').trigger('foo', [ 'bar', 'bam' ]); // alerts 'bar: bam'

Categories