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
});
}
Related
After changing my button type to submit it's not submitting the form. Somehow, the AJAX request is not working after that. If I change it to type="button" then it's working, but I want this because required validation is not working while giving type="button". It only works when I'm giving button type submit but then the form is not submitting.
<form>
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
$("#passwordButton").on('submit', function(e) {
e.preventDefault();
const email = $("#passwordReset").val();
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
I want my form to be submitted while checking the required condition also.
Quoting from MDN:
Note that the submit event fires on the element itself, and not on any or inside it. (Forms are submitted, not buttons.)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Attach the listener to the click even of the button, or to the submit event of the form.
HTMLFormElement: submit event
Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)
Try click event instead:
$("#passwordButton").on('click', function(e) {
Update: I think simply submit event on the form is enough here as the event will fire on clicking any input type=submit:
$('#myForm').on('submit', function(){
alert('Your form is submitting');
/*
Your code here
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
I think you should just create a normal like <button onclick="Submit()">save</button>
and write Code like that:
Submit(e){
e.preventDefault();
const email = $("#passwordReset").val();
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
}
Add Id or class attribute to your form.
<form id="formYouWantToSubmit">
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
Then,
$("#formYouWantToSubmit").on('submit', function(e) {
const email = $("#passwordReset").val();
// This will validate if email having any value (from string point of view)
if (!email) {
e.preventDefault();// To restrict form submission
//### Do anything here when validation fails
return false;
}
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
Things to remember:
button type submit will ultimately submits the form to current page (due to action attribute is missing)
When we user Ajax to do something we ultimately seek a 'page-load-less' activity. In your case you are doing both submitting the form using submit button and making Ajax request, which will hard to get executed and if any chance it gets executed you won't be able witness any 'success' or 'error' activities because until then page already been reloaded.
I am trying to submit a form with dynamic inputs. I am able to add a several inputs via the javascript. However, when I submit, it only picks up the first added input value. I hope someone can take a look at this for me as I've tried to fix this for so long. Thank you
Controller
public function update(){
$this->form_validation->set_rules('first_name', 'Firstname', 'trim|required|xss_clean');
$this->form_validation->set_rules('last_name', 'Lastname', 'trim|required|xss_clean');
$this->form_validation->set_rules('phone_number', 'Phone', 'trim|required|xss_clean');
$this->form_validation->set_rules('date_of_birth', 'Date of Birth', 'trim|required|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('country', 'Country', 'trim|required|xss_clean');
$this->form_validation->set_rules('active', 'Is Active', 'trim|required|xss_clean');
$id = $this->input->post('id');
$person_id = $this->input->post('person_id');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$date_of_birth = $this->input->post('date_of_birth');
$phone_number = $this->input->post('phone_number');
$account_number = $this->input->post('account_number');
$address = $this->input->post('address');
$country = $this->input->post('country');
$active = $this->input->post('active');
if($this->form_validation->run()==false){
$this->edit();
}else{
$person = array(
'first_name'=>$first_name,
'last_name'=>$last_name,
'date_of_birth'=>$date_of_birth,
'phone_number'=>$phone_number,
'address'=>$address,
'country'=>$country,
);
$account = array(
'is_active'=>$active
);
print_r($account_number);
}
}
View
<script>
$(document).ready(function(){
var max_fields = 5;
var wrapper = $("#new_account_number_container");
var addInput = $("#addInput");
var i;
$(addInput).click(function(e){
i = $("#new_account_number_container input").length;
e.preventDefault();
if(i<max_fields){
i++;
$(wrapper).append('<div><input type="text" name="account_number[]" class="form-control" placeholder="Account Number" required autofocus>Remove<div>');
}
});
$(wrapper).on("click",".remove", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
i--;
});
});
</script>
<div id="new_account_number_container" class="form-group col-sm-8">
<input type="text" name="account_number[]" class="form-control" placeholder="Account Number" autofocus>
<br>
</div>
<div class="form-group col-sm-8">
<button class="pull-right btn btn-primary" id="addInput">Add</button>
</div>
First thing, I can not see <form> in your code. Without this tag, you can not get desired behaviour:
After that,
To give you formatted code snippet I am posting that suggestion as an answer:
// this is the id of the form
$("#form_id").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form_id").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
We need to remember that, PHP serves as back-end application. So anything dynamic (like DOM input text in your case) may NOT be submitted simply because the <form> tag is not updated that you have new text-box input.
One of the thing you could do is to use ajax for form submitting. Because it is Client-Side Script, it could detect all DOM input text box on your page, and serialized it before send the request to the back-end.
First by adding a <form> tag between your input and button component. Example like <form id="frm" name="frm">.
Second, by adding a button which trigger a JavaScript function.
function update(){
if(confirm("Are you sure?")==true){
$.post(
"*absolute_project_root_path*/*controller*/update",
$('#frm').serialize(),
function(response){
//what to do with your response..
}
);
}
return false;
}
Then you can access the submitted form in the back-end like usual.
I've been trying to use stripe to accept payment and I've been trying to make a rough prototype for it from a guide I found but I can't seem to get it working. The new input named "stripeToken" never inserts after the submit. This causes my PHP script to never execute. I'm trying to understand why it never inserts. Here's the scripts:
Javascript: (In the head of page)
<script src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('mykeyishere');
</script>
<script>
// Event Listeners
$('#payment-form').on('submit', generateToken);
var generateToken = function (e) {
var form = $(this);
// No pressing the buy now button more than once
form.find('button').prop('disabled', true);
// Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
// Prevent the form from submitting
e.preventDefault();
};
</script>
HTML/Javascript: (Tried JS both in the head and in the form)
<form action="index.php" method="POST" id="payment-form">
<script>
var stripeResponseHandler = function (status, response) {
var form = $('#payment-form');
// Any validation errors?
if (response.error) {
// Show the user what they did wrong
form.find('.payment-errors').text(response.error.message);
// Make the submit clickable again
form.find('button').prop('disabled', false);
} else {
// Otherwise, we're good to go! Submit the form.
// Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
// Call the native submit method on the form
// to keep the submission from being canceled
form.get(0).submit();
}
};</script>
<span class="payment-errors"></span>
<div class="row">
<label>
<span>Card Number</span>
<input type="text" data-stripe="number">
</label>
</div>
<div class="row">
<label>
<span>CVC</span>
<input type="text" data-stripe="cvc">
</label>
</div>
<div class="row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" data-stripe="exp-month">
</label>
<input type="text" data-stripe="exp-year">
</div>
<button type="submit">Submit</button>
</form>
You should remove that script tag from inside the form and put it next to the other script tag.
also try wrapping your event binding in a document.ready
$(document).ready(function(){
$('#payment-form').on('submit', generateToken);
var stripeResponseHandler = function (status, response) {
var form = $('#payment-form');
// Any validation errors?
if (response.error) {
// Show the user what they did wrong
form.find('.payment-errors').text(response.error.message);
// Make the submit clickable again
form.find('button').prop('disabled', false);
} else {
// Otherwise, we're good to go! Submit the form.
// Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
// Call the native submit method on the form
// to keep the submission from being canceled
form.get(0).submit();
}
};
var generateToken = function (e) {
var form = $(this);
// No pressing the buy now button more than once
form.find('button').prop('disabled', true);
// Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
// Prevent the form from submitting
e.preventDefault();
};
});
From what I can guess ( and its not a good guess), is that the #payment-form does not get bound correctly because the script is getting ran before the dom is ready?
Also another thing caught my eye. You have e.preventDefault() which stops the form from being submitted, but then you have a responsehandler. does that response handler get called? Is there some request that goes out to stripe and comes back?
Check in your network window and see if that is happening. The form only gets submitted in the form.get(0).submit(); part of the response handler, so after stripe completes.
There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
You cannot attach events before the elements you attach them to has loaded
It is recommended to use eventListeners - here one when the page loads and another when the form is submitted
This works since IE9:
Plain/Vanilla JS
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
Not recommended but will work
If you do not need more than one event handler, you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm() method returns false.
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests.
These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
Use #Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
On a website I'm working on, when you click sign on, a jquery dialoge modal pops up, but you have to click on OK to submit the form, you can't just hit enter. I need it to be able to have enter work also. It seems like what I have should work, but it doesn't
I'm using jquery-1.3.2.js. I also have a php file with the following piece of code in it: `
<tr valign="top" align="right" style="height:40px"><td >
<div id="signin">
<table style="margin-top:4px;margin-right:4px;border-style:solid;border-width:1px">
<tr><td style="width:165px;">
<div><center>
<a title="Sign In" onclick="LoginDialogOpen()" href="javascript:void();">Sign In</a><b> | </b>
<a title="Create Account" href="CreateAccount.html">Create Account</a>
</center></div>
</td></tr>
</table>
</div>
</td></tr>
<div id="Signin_Dialog" >
<div id="bg">
<label><span>Email:</span></label>
<input type="text" name="email" id="email" class="dialog-input-text"/>
<br>
<label><span>Password:</span></label>
<input type="password" name="password" id="password" class="dialog-input-text"/>
<br>
<br>
<center><b><label id="login_error" style="color:red"><span> </span></label></center></b>
</div>
</div>
<script>
$('#login_dialog').dialog({
autoOpen: false,
width: 310,
overlay: { opacity: 0.5, background: "black" },
modal: true,
buttons: {
"Ok": function() {
$("body").addClass("curWait");
sql = "select client_id from users where email = '" + $("#email")[0].value + "' and login_password='" + $("#password")[0].value + "'";
$.get('BongoData.php', { task:"SQLResultToJSON", sql: sql}, ResultOfLoginAttempt, "json");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
</script>`
i have a javascript file with the following function:
function LoginDialogOpen(){
$('#login_dialog').dialog('open');
$('#login_dialog').keypress(function(e) {
if (e.which == 13) {
$("body").addClass("curWait");
sql = "select client_id from users where email = '" + $("#email")[0].value + "' and login_password='" + $("#password")[0].value + "'";
$.get('BongoData.php', { task:"SQLResultToJSON", sql: sql}, ResultOfLoginAttempt, "json");
}
});
}
That is the code I have, I don't understand why it isn't working.
I also had it try $('#login_dialog').dialog('isOpen'); right after i opened it, but it always returned false oddly enough. Please help if you can.
I strongly recommend to consider all notes made by the others regarding raw client side SQL!
Regarding your actual question I propose the following:
Put a form in your login dialog like so:
<div id="login_dialog">
<form method="get" action="BongoData.php">
<input type="text" name="email" />
<input type="password" name="password" />
<input type="submit" />
</form>
</div>
Then in your script part where the dialog is initialized write something like:
$('#login_dialog').dialog({
autoOpen: false,
width: 310,
overlay: { opacity: 0.5, background: "black" },
modal: true,
buttons: {
"Ok": function() { $('#login_dialog form').submit(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
// hide the original submit button if javascript is active
$('#login_dialog form input[type=submit]').hide();
// register a submit handler to submit the form asynchronously
$('#login_dialog form').submit(function () {
// calling serialize() on a form transforms form inputs to a string suitable for $.get and $.post
$.get($(this).attr('action'), $(this).serialize(), ResultOfLoginAttempt, "json");
// prevent that the browser submits the form.
return false;
});
// and register a key listener to submit the form if the user presses enter on the password input field
$('#login_dialog form input[type=password]').onKeyDown(function (e) {
if (e.which == 13) {
// just trigger the submit handler
$('#login_dialog form).submit();
}
});
With these preparations you can simplify your javascript a lot:
function LoginDialogOpen(){
$('#login_dialog').dialog('open');
}
Some additional notes:
Don't use SQL in your javascript. Instead write a customized php file with prepared sql to verify login data. In this solution the login form degrades gracefully if no javascript is present as it is a standard html form which can be sent by the browser. You should also be aware of the fact, that some browser send forms (i.e. trigger the submit handler) on Enter without further requirements, but as it's browser specific you cannot rely on this if it's a must for your application. As a last action you should eventually check whether you need to close the dialog manually within your "ResultOfLoginAttempt" method.
Look at the Tamper Plugin for Fire Fox : Tamper Data 10.1.0
Genertate SQL on the client side is bad. You can hijack the http request.
I think you mean if (e.keyCode == 13) { rather than if (e.which == 13) {.
Also Ian Elliot is right. You should never have the actual sql as any part of your javascript or any part of your form. You can submit values to the server that will eventually be interpolated into your SQL*, but never the complete SQL.
*Once the values have been properly validated, sanitized, & optionally passed through another layer of abstraction (think MVC).