Receive and send form data - javascript

Greetings to the experts on WEB development, I myself am a beginner in this field, I am doing a training project, so the question arose. There is a form:
...
<form name="date">
<p>
<label for="date">Choose date</label>
<input type="date" name="calendar" id="calendar" onchange="handlerDate(event)">
</p>
</form>
...
Which I then process in this way:
function handlerDate(e) {
e.preventDefault();
let dateForm = document.forms["date"];
let dateChosen = dateForm.elements["calendar"].value;
let dateNow = new Date();
dateChosen = new Date(dateChosen);
if ($('#uncorrectDate').length)
$('#uncorrectDate').remove();
if ((dateChosen.getFullYear() !== dateNow.getFullYear() || dateChosen.getMonth() !== dateNow.getMonth()) ||
((dateChosen.getFullYear() === dateNow.getFullYear() || dateChosen.getMonth() === dateNow.getMonth()) &&
(dateChosen.getDate() < dateNow.getDate()))
) {
$('<p id="uncorrectDate">Incorrect date</p>').appendTo('.mainbody');
$("#userInfo").remove();
} else {
if($('#userInfo').length)
$('#userInfo').remove();
var timesGet = GetOrders(dateChosen.toLocaleDateString());
times = timesGet.booked;
let selectTimes = '</p><p><label>Choose time: </label><select name="text">';
for (let k = 0; k < times.length; k++) {
let time = `${times[k]}:00`;
selectTimes += '\n<option value="' + time + '">' + time + '</option>';
}
selectTimes += "</select><\p>";
$('<form id="userInfo">' +
'<p> ' +
'<label for="email">Email:</label>' +
'<input type="email" placeholder="user#gmail.com" name="email"/></p>' +
'<p>' +
'<label for="phone">Телефон: </label>' +
'<input type="tel" placeholder="(XXX)-XXX-XXXX" name="phone"/>' +
'</p>' +
'<p>' +
selectTimes +
'</p>' +
'<p>' +
'<button type="submit">Send</button>' +
'</p>' + '</form>'
).appendTo('.mainbody');
}
}
function GetOrders(date) {
var result = "";
$.ajax({
url: "/api/records/" + date,
type: "GET",
async: false,
contentType: "application/json",
success: function (record) {
result = record;
}
});
return result;
}
function CreateOrder(userName, userMail, userPhone, userDate, userTime) {
$.ajax({
url: "api/users",
contentType: "application/json",
method: "POST",
data: JSON.stringify({
name: userName,
email: userAge,
phone: userPhone,
date: userDate,
time: userTime
}),
success: function (user) {
$(".mainbody").append('<p>Заказ был сделан!</p>');
}
})
}
The logic that was unnecessary for understanding the issue is removed. First question: is it normal practice to dynamically change the page in this way through jQuery? Since I am doing that purely for practical purposes: to make a task, I’m not entirely guided by how it is customary to do, how it is not customary. The second and main question: how can I now receive and correctly send data from the form? Is there an example syntax in this case (without php). There is an onsubmit attribute in the form, you can specify the function handler there, but is there an example of how this is done? And is it necessary in this case to put an additional handler function onclick on the submit button? I need to get data from the form, validate it, and call the CreateOrder method with this data. On the server, all this will be processed correctly, I configured it, but did not find normal examples of how to write correctly onsubmit or onclick, into which I need to pass 1 parameter: the date received earlier.

Related

How to implement sequential queries for an API under AJAX and jQuery

There is a URL, where an API of work orders is hosted. The API provides a method that delivers the headers of work orders for a client and on a date. What it returns is a code of the work order. There is a second method where, with the work order code, it returns the detail of this order.
Unfortunately the API does not have a method that brings me at once the header and detail of the work order. I need to have the complete information of each work order, its header and its details.
Given the above, my strategy has been to make a small routine in jQuery that first via AJAX invokes an API method that delivers all the headers of the work orders, for a given date and a specific client. These headers store them in an array. After the above, I go through this arrangement and invoke another method of the API to obtain the respective details of the work orders, which can be one or several records.
The problem is that when executing, all the headers are obtained, but when the query of the details is executed, the server responds with a message:
Sorry, we have detected that there are simultaneous requests
without being able to obtain the details. Investigating the subject, everything makes reference that a problem with the subject of AJAX and its asynchrony occurs. That the detailed consultations are being done in parallel and must be carried out sequentially, for which purpose it must be implemented with Promise.
With a little help, I made the changes, but I still get the same error.
The implementation is as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn_nuevo").click(function() {
var ocs = [];
var total = 0;
$('#result').append('<b>total 1: </b>' + total + '<br />');
//ESTE PRIMER AJAX OBTIENE LA LISTA DE OT
$.ajax({
url: "http://api.ot.json?fecha=26062018&Cliente=100ticket=C7A82D65",
dataType: "json",
success: function(data) {
//TOTAL DE OT
total = data.Cantidad;
//SE ALMACENAN LAS OT
for (var i = 0; i < total; i++) {
ocs[i + 1] = data.Listado[i].Codigo;
};
$('#result').append('<b>total 1: </b>' + total + '<br />');
let promise;
let j = 0;
let url = "http://api.ot.json?codigo=" + ocs[j + 1] + "&ticket=C7A82D65";
for (let j = 0; j < total; j++) {
if (j === 0) {
promise = promise || $.ajax({
url: url,
dataType: "json"
});
j++;
} else {
promise = promise.then(datos => {
$('#result').append('<b>Codigo: </b>' + datos.Listado[0].Codigo + '<br />');
$('#result').append('<b>Nombre: </b>' + datos.Listado[0].Nombre + '<br />');
$('#result').append('<b>Estado: </b>' + datos.Listado[0].Estado + '<br />');
$('#result').append('<b>Descripcion: </b>' + datos.Listado[0].Descripcion + '<br />');
$('#result').append('<b>Tipo: </b>' + datos.Listado[0].Tipo + '<br />');
url = "http://api.ot.json?codigo=" + ocs[j + 1] + "&ticket=C7A82D65";
return $.ajax({
url: url,
dataType: "json"
});
});
}
};
}
});
});
});
</script>
</head>
<body>
<div id="boton_nuevo" align="center">
<input type="button" id="btn_nuevo" name="btnnuevo" value="Ejecutar">
</div>
<div id="result"></div>
</body>
</html>
The error message is as follows:
Can anybody help me?
I have proceeded to carry out the modification indicated by Jaromanda in http://jsfiddle.net/qj80ovw5/2/.
When executing with the modification, it has been possible to obtain the detail of the first work order, something that was not previously possible, but after bringing the data of this first one, the server sends the same error indicated initially in the question.
Apparently, the server keeps coming in parallel queries and that's why the server responds in that way. How could this recovery of the details of work orders be improved, so that this error does not occur?
http://jsfiddle.net/qj80ovw5/2/
$(document).ready(function() {
$("#btn_nuevo").click(function() {
$('#result').append('<b>total 1: </b>' + total + '<br />');
//ESTE PRIMER AJAX OBTIENE LA LISTA DE OT
$.ajax({
url: "http://api.ot.json?fecha=26062018&Cliente=100ticket=C7A82D65",
dataType: "json"
}).then(data => {
const total = data.Cantidad;
$('#result').append('<b>total 1: </b>' + total + '<br />');
let promise = Promise.resolve(); // or $.when()
for (let j = 0; j < total; j++) {
let url = "http://api.ot.json?codigo=" + data.Listado[i].Codigo + "&ticket=C7A82D65";
promise = promise
.then(() => $.ajax({
url: url,
dataType: "json"
}))
.then(datos => {
$('#result').append('<b>Codigo: </b>' + datos.Listado[0].Codigo + '<br />');
$('#result').append('<b>Nombre: </b>' + datos.Listado[0].Nombre + '<br />');
$('#result').append('<b>Estado: </b>' + datos.Listado[0].Estado + '<br />');
$('#result').append('<b>Descripcion: </b>' + datos.Listado[0].Descripcion + '<br />');
$('#result').append('<b>Tipo: </b>' + datos.Listado[0].Tipo + '<br />');
});
}
});
});
});

html datalist not showing options in chrome

I make a server request to get streetnames and they should show up as datalist options....but in google chrome they didn't.
In Firefox and IE it pops up with the correct requested street names. Here is some Code:
the HTML:
<li>
<label>Straße <span class="required">*</span></label>
<input id="input_strasse" type="text" value ="Strasse" autocomplete="off" list="input_strasse_datalist" class="field-long" placeholder="Straße" />
<datalist id="input_strasse_datalist" ></datalist>
</li>
JS:
$(document).on("keyup", "#input_strasse", function () {
var inputStr = $('#input_strasse').val();
var charStr = inputStr.charAt(0).toUpperCase() + inputStr.substr(1);
var UrlToWebservice = window.localStorage.getItem("url_to_webservice");
console.log("buchstabensuppe: ", charStr)
$.ajax({
type: 'POST',
url: UrlToWebservice + 'SP_SELECT_Strassen',
data: { 'charStr': charStr },
crossDomain: true,
dataType: 'xml',
success: function (response) {
// var strassen = new Array;
$(response).find('STRASSE').each(function () {
var strasse = $(this).find('NAME').text();
var plz = $(this).find('PLZ').find('plz').text();
var ort = $(this).find('PLZ').find('ORT').text();
var arstrasse = $(this).find('AR').first().text();
console.log("arstrasse ", arstrasse)
$("#input_strasse_datalist").append('<option data-ar = ' + arstrasse + ' value = "' + strasse + ' (' + plz + ', ' + ort + ')">' + strasse + ' (' + plz + ', ' + ort + ')</option>')
$("#input_plz").val(plz)
$("#input_ort").val(ort)
})
},
error: function () {
window.location.hash = "httperror";
}
})
})
I recognized that user-agent gives datalist display: none; if I gave the datalist display: block; but it looks like this:
So it is not inside the Dropdown and no option is selectable. It should look like this:
The really strange thing is, that it works perfectly on the local version of the app. Only when I run it at the server in the local chrome the strange behaviour appears. I'm really clueless. Please help. Thanks!
Seems to work after updating chrome.
No problem anymore with Version 63.0.3239.84.

How to use form data in codepen

I'm working on the wikipedia viewer for free code camp and I'm trying to make the search bar work.
Ideally I would just like to have the user type in some text, then have that become a string in my code when the user hits submit. This is the html for the search bar so far
<form method="get">
<input type="text" placeholder="Search articles" class="srchbox" name="Search" id="searchbar">
<button type="submit" class="btn">Search</button>
</form>
and the api setup I have to make the search
var apiURL = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&generator=search&search=" + textInput;
$(document).ready(function() {
$.ajax({
url: apiURL,
dataType: "jsonp",
success: function(data) {
var wikiAPI = JSON.stringify(data, null, 3);
console.log(wikiAPI);
var wikiHTML = "";
for (i=0; i < data[1].length; i++)
{
wikiHTML += ("<a href =\"" + data[3][i] + "\" target=\"_blank\">")
wikiHTML += "<div class = \"wikicontent container-fluid\" style = \"color:black;\">";
wikiHTML += ("<h2>" + data[1][i] + "</h2>");
wikiHTML += ("<h3>" + data[2][i] + "</h3>");
wikiHTML += "</div></a>"
}
$("#articles").html(wikiHTML);
I'm a bit lost on how to pull this off so any help would be great. Thank you!
You can use submit event, set query to #searchbar .value
$("form").on("submit", function(e) {
e.preventDefault();
if (this.searchbar.value.length) {
var url = "https://en.wikipedia.org/w/api.php?format=json"
+ "&action=opensearch&generator=search&search="
+ this.searchbar.value;
$.ajax({url:url, /* settings */});
}
});

Ajax call jsonp from PHP

Hi guys so i made a code that parses a CSV file into a JSON ARRAY with PHP. So when you go to this URL you get the PHP output:
http://www.jonar.com/portal/mynewpage.php
Now i used this code to append my JSON ARRAY to HTML but now things have changed since i am using PHP i am not sure how to use it and what to do differently.
Also my ajax call is always empty which is weird..
$.ajax({
type: 'GET',
url: 'http://www.jonar.com/portal/mynewpage.php',
dataType: 'jsonp',
success: function(response) {
alert(response);
}
});
I used this to append my JSON ARRAY but now if i can get the response do i use the same code or will it have to be altered?
$.each(results.data.slice(1), // skip first row of CSV headings
function(find, data) {
var title = data.title;
var link = data.link;
var date = data.date;
var type = data.type;
var where = data.where;
var priority = data.priority;
if (priority == '1') {
$('ul.nflist').prepend($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
} else if (where == 'pp', 'both') {
$('ul.nflist').append($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
}
});
the reason i used PHP is to avoid cross domain issue
Thanks for the help guys!

JQuery Form Submission with enter key AJAX API

I've tried various solutions, but none are suitable for my particular case!
How can I make it so that when the user presses 'Enter' the form submits & searches.
I also want to try and remove the JavaScript from the HTML document, and move it to the ajax.js document & select it.
I'm unsure of the correct syntax to do so.
I am using rotten tomatoes API with AJAX by the way.
search.php
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="button" id="button" value="Go!" onClick="filmlist(this.form)">
</form>
ajax.js
function filmlist (form) {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
}
}
$("form").submit(function(){
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
return false;
});
or you can just return false at the end of your filmlist function.
You can detect an enter keypress in the #inputbox element with the following jQuery code:
$('#inputbox').keyup(function(e)
{
if(e.keyCode == 13)
{
//do your stuff
}
});
You can also use $('#inputbox').change() to directly load movies when the user is typing.
Do not forget that some old or mobile browser do not have JavaScript support. Always build an server side solution as fallback.

Categories

Resources