Using AJAX to submit form - javascript

I have developed a Python API and am now integrating it with a HTML template I have downloaded. It is a simple one page HTML template with a form to accept a album name and artist name. I am looking to process the form using AJAX. So once the form has been successfully submitted, it is replaced with a message returned by the API.
The (simplified) html snippet is:
<div class="form">
<form role="form" action="form.php" id="signup">
<div class="form-group">
<label>Artist Name</label>
<input type="text" name="artist" id="artist">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" name="album" class="album">
</div>
<button type="submit" class="btn">Submit!</button>
</form>
</div>
Then I have a JS file I import at the beginning of the html file. Below is the JS file.
$(function() {
var form = $('#signup');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = {
'artist' : $('input[name=artist]').val(),
'album' : $('input[name=album]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'form.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
I think the issue is with the .done(function(data)) however, the website I found the code on wasn't clear.
form.php returns a JSON string. At the moment when I use the form, it sends the information to the Python API and the Python API returns a JSON message. But I cannot access the JSON message. It is in contains
'code': X, 'message':'returned messaged...'
ideally I would like to do a if/else statement. So
if code = 1:
display: Success
etc but I have no idea where to start with it in PHP/JS.

I was able to get it working eventually after seeing a few other stack overflow answers and another website.
I added one div to the html file under the button before the end of the form to make:
<form>
...
...
<button type="submit" class="btn">Submit!</button>
<div id="thanks" style="display:none;"></div>
</form>
Then, in the JS file I amended .done(function(data)) to be:
.done(function(data) {
if (data.result == '1') {
$('#thanks').show().text("Success!");
$('input[type="text"],text').val('');
} else if (data.result == '2') {
$('#thanks').show().text("Album and Artist already exists");
} else {
$('#thanks').show().text("Uh Oh. Something has gone wrong. Please try again later or contact me for more help");
}
});

Related

How can I get a return value from a post request sent from javascript to flask

New to flask here. I need to pass an integer variable from html/javascript to python flask in order to perform a calculation and return the result value to javascript so that I can display it on the DOM without refreshing the page. Below is the HTML structure I'm dealing with.
<form action="/buy" method="post" id="buy-form">
<h4>Price</h4>
<input
type="text"
id="limit-price"
name="limit-price"
/>
<h4>Quantity</h4>
<input
type="text"
id="limit-quantity"
name="limit-quantity"
/>
<button type="button" id="maximize-buy">Max</button>
<input type="submit" name="buy" value="BUY" id="submit-buy" />
</form>
I want to pass the value thats typed into the limit-price text input over into flask (using Javascript) at the click of the maximize-buy button in order to perform a calculation in python flask and then return that result back to Javascript so that I can display it on the page without refreshing.
You could use ajax
<form>
..... your form..
<div id="div-id></div>
</form>
<script>
data ={
price = $('#limit-price').val(),
quantity = $('#limit-quantity').val()
}
$.ajax({
url: url,
method: "POST",
data: data
}).done(function (data) {
$('#div-id').html(data['val']);
}).fail(function (error) {
alert(error);
});
</script>
And create a function in flask
#app.route(url)
def calc():
quantity = request.form['quantity']
price = request.form['price']
return jsonify({'val': quantity*price})

grabbing form with jquery not working

I am using JQuery 3.2.1 to grab input forms. the problem is that I don't get anything out, empty object or empty string. I tried with serialize, serialize array, code from SO to get the fields and transform to json, nothing did work.
I am sure that I wrote correctly the form id because the subscription of the function is successful.
here are part of the html:
<form role="form" id="organisationform">
<div class="row col-sm-offset-1">
<div class="form-group col-sm-5">
<label for="name" class="h4">Nom Organisation</label>
<input type="text" class="form-control" id="nomOrg" placeholder="Nom de l'organisation" required>
</div>
<div class="form-group col-sm-5">
<label for="lastname" class="h4">Identificateur </label>
<input type="text" class="form-control" id="idOrg" placeholder="Entrer IDentificateur" required>
</div>
</div>
...
</form>
and here is the js code:
onSubmit('form#organisationform', function() {
send('http://localhost:8080/organisation/ajouter', 'form#organisationform');
});
in an other file:
function grabForm(formId) {
var data = {};
$(this).serializeArray().map(function(x){data[x.name] = x.value;});
return data;
}
function send(url, formId) {
var data = grabForm(formId);
$.ajax({
url: url,
...
});
}
function onSubmit(idform, fn) {
$(idform).submit(function(event) {
event.preventDefault();
fn();
});
}
the problem is on the grab thing function it's returns an empty object, but before this form it was serialize function.
in an other test, I just Copy-Paste code from SO:
$('#organisationform').submit(function () {
var $inputs = $('#organisationform :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
alert(values);
//Do stuff with view object here (e.g. JSON.stringify?)
});
same problem.
SO how can I fix this? or how can I do it?
Seems like you are wrapping the jQuery functions in a load of your own functions which don't actually seem to add any value, but are overcomplicating things, in particular making the scope uncertain and making the flow of control hard to follow.
This should be sufficient to submit the form via ajax:
$("form#organisationform").submit(function(event) {
event.preventDefault();
$.ajax({
url: "http://localhost:8080/organisation/ajouter",
data: $(this).serialize(), //serialise the form, which due to the scope can be fetched via 'this',
method: "POST", //assuming it's a POST, but set it to whatever is right for your server
success: function(data) {
console.log(data); //receive any response from the server
},
error: function(jQXHR, textStatus, errorThrown) {
console.log(errorThrown + " " + textStatus); //log any HTTP errors encountered
}
//...etc
});
});
You may need to tweak things depending on what exactly the server expects to receive.
ouch! I changed the input with name attributes instead of id, now it can grab things!

Javascript from processor - unable to debug issues

I have a form that I'm trying to submit and process with javascript using the code outlined below:
Form:
<form id="my_form_id" method="POST" action="my_processor_script.php">
<input type="text" id="form_id_1" name="form_field_1">
<input type="text" id="form_id_2" name="form_field_2">
<input type="text" id="form_id_3" name="form_field_3">
<input class="cbp-mc-submit" type="submit" name="save_settings_button" id="save_settings" value="Save Settings" />
</form>
Script:
<script>
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
alert("Form Processed");
},'json');
return false;
});
});
</script>
Processor:
<?php if (isset($post_data['save_settings_button']))
{
$form_field_1 = $_POST['form_field_1'];}
$form_field_2 = $_POST['form_field_2'];}
$form_field_3 = $_POST['form_field_3'];}
}
?>
Once I have the variables I then store them in a database.
The form works great if I just post from the form to the processor script without using the javascript however when I use the javascript nothing happens. I'm obviously doing something very wrong but can work this out at all as I cant see what is being received by the processor. Has anyone got any ideas on how i can get this to work?
It would also be great if I can return the data so that I can see what is being passed to the script as this would help me to debug any issues?

How to submit a form in Semantic UI?

I know how to validate a form using Semantic UI, and can even read in console the message "Form has no validation errors, submitting." However, where is this submitting to? I want to actually submit the form, but the way Semantic UI is laid out I don't seem to be able to specify where to submit to or anything.
I read this tutorial, but that uses Angular for submission and not just Semantic UI.
Am I missing something really simple here?
You can use jQuery's ajax:
//Get value from an input field
function getFieldValue(fieldId) {
// 'get field' is part of Semantics form behavior API
return $('.ui.form').form('get field', fieldId).val();
}
function submitForm() {
var formData = {
field1: getFieldValue('someId')
};
$.ajax({ type: 'POST', url: '/api/someRestEndpoint', data: formData, success: onFormSubmitted });
}
// Handle post response
function onFormSubmitted(response) {
// Do something with response ...
}
EDIT: also, you can use the onSuccess method of the form to run the submitForm function, ie when you initialize the form:
$('.ui.form').form(validationRules, { onSuccess: submitForm });
onSuccess will only be called when the 'Submit' button is clicked and the form is valid based on the rules you specify.
EDIT: If you want the regular HTML form behavior, you will need to add the semantic css classes to the form tag.
<form class="ui form" method="POST" action="/signup">...</form>
And then you set up the validation rules using jQuery. This will give you the default HTML form behavior, ie when you hit the submit button, it will make a POST request to /signup in the case above. If any of your rules trigger, the submit is prevented until there is no validation errors.
use the original submit button but add semantic button style:
<input type="submit" value="Submit" class="ui button" />
<input type="submit" value="Submit" class="ui teal button big"/>
Semantic UI has it's own API to submit form. for example:
$('.ui.form .submit.button')
.api({
url: 'server.php',
method : 'POST',
serializeForm: true,
beforeSend: function(settings) {
},
onSuccess: function(data) {
}
});
The easiest way is to retrofit a standard HTML form use the code below.
Start with a basic working standard HTML form with a submit button and this will take your values and post them to your form destination, returning the output below your form submit button.
Its a good time to double check you are successfully linking to jquery, semantic javascript and semantic css at this point.
Add class="ui form" to your form tag .
Add the javascript below.
.
$(document).ready(function() {
// validation
$('.ui.form').form({
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter an email'
}
]
}
},
{
inline: true,
on: 'blur',
transition: 'fade down',
onSuccess: validationpassed
});
// called if correct data added to form
function validationpassed() {
// Multiple instances may have been bound to the form, only submit one.
// This is a workaround and not ideal.
// Improvements welcomed.
if (window.lock != "locked") {
var myform = $('.ui.form');
$.ajax({
type: myform.attr('method'),
url: myform.attr('action'),
data: myform.serialize(),
success: function (data) {
//if successful at posting the form via ajax.
myformposted(data);
window.lock = "";
}
});
}
window.lock = "locked";
}
// stop the form from submitting normally
$('.ui.form').submit(function(e){
//e.preventDefault(); usually use this, but below works best here.
return false;
});
function myformposted(data) {
// clear your form and do whatever you want here
$('.ui.form').find("input[type=text], textarea").val("");
//$('.ui.submit.button').after("<div>Message sent. Thank you.</div>");
$('.ui.submit.button').after(data);
}
});
Basic form:
<form action="process.php" method="post" class="ui form">
<div class="field">
<label>title</label>
<input name="email" type="text">
</div>
<input type="submit" class="ui button"/>
</form>
If you want the error message to show in a box rather than within the form itself include this in your form, and remove the words "inline: true," and Semantic UI does the rest:
<div class="ui info message"></div>
NOTE: Using form tags with Semantic UI isn't strictly necessary as you only really need a div with the classes "ui form", however this retrofit code does require a form tag.
What if you don't wana use ajax?!
Use this one:
$( "#reg_btn" ).click(function(event){
event.preventDefault();
$('#register_form').submit();
});
in this case u can use <button> tag... there is no need to use classic tag instead
Semantic UI is based on jQuery and CSS so if you want to submit your form data you have some way to do that:
Send your form data with AJAX
Use some jqQuery plugins like this
Trick!
Put a submit button and set its display to none. When a user clicks on the div button throw that event to the submit button, in this way:
$("div_button_selector").on("click", function(){
$("input[type='submit']").trigger('click');
});
See post Adding errors to form validation doesn't work? for form and error validation. Since Semantic UI is a client side tool for user interface, this is the php for "self submitting / same code page" contact email. Since the purpose of Semantic UI is not logic processing, what language and or method do you want to use for form submission? JS/jquery client side or serverside php, rails, etc.? Keep in mind Semantic UI is dependent on jquery.
<?php
if (isset($_POST["email"]))
{
if ($_POST["email"] != "")
{
$from = htmlentities($_POST["email"]);
$subject = htmlentities($_POST["subject"]);
$message = htmlentities($_POST["message"]);
$message = wordwrap($message, 70);
mail("valid-server-email-username#valid-server-address", $subject, $message, "From: $from\n");
$_POST["email"] = "";
$_POST["subject"] = "";
$_POST["message"] = "";
unset($GLOBALS['email']);
header("location: /");
}
}
If you have a form like this
<div class="ui form segment">
<p>Tell Us About Yourself</p>
<div class="field">
<label>Name</label>
<input placeholder="First Name" name="name" type="text">
</div>
<div class="field">
<label>Username</label>
<input placeholder="Username" name="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="ui blue submit button">Submit</div>
</div>
you can use the foolowing script to send the form
$('.ui.blue.submit.button').on('click', function() {
submitForm();
});
function submitForm() {
var formData = $('.ui.form.segment input').serializeArray(); //or .serialize();
$.ajax({
type: 'POST',
url: '/handler',
data: formData
});
}

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Categories