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.
Related
I have a Ask Question form by which client can ask any question to us. While client submit the form we will give him a thanks message for 5 seconds then hide the message and show again the Ask Question form in that div.
But while the from comes after successful message, form input values is still there. I want a fresh from without any input value like the form before submitting.
Here is my ajax code
$.ajax({
url:"{{ url('/ask_question_form') }}",
type: 'GET',
data: {_token :token, name : name, email : email, contact : contact, question : question},
success:function(msg){
// console.log(msg);
$('.question-modal .textwidget').hide();
trHTML = "";
trHTML += "<div id='user-question' style='margin-top:50%; color:#0071BC'>";
trHTML += "Thanks for your question. We will save your question for further query and give a feedback as soon as possible.";
trHTML += "</div>";
$('.question-modal').append(trHTML);
setTimeout(function() {
$('.question-modal #user-question').remove();
$('.question-modal .textwidget').show();
}, 5000);
}
});
Where textwidget is the class name of that form
The best solution is-
$("#form")[0].reset();
use this code when your success message comes.
After completing 5 seconds and when you hide the "success message" at that time you can reset your form
$("#formId").get(0).reset();
Here "formId " id of your form.
Erase values of all fields once you successfully submit the form.
document.querySelector('get-your-field1').value = '';
document.querySelector('get-your-field2').value = '';
document.querySelector('get-your-field3').value = '';
document.querySelector('get-your-textarea').value = '';
Or you can use form reset.
const form = document.querySelector('form');
const btn = document.querySelector('button');
btn.addEventListener('click', event => {
event.preventDefault();
form.reset();
});
<form>
<input />
<input />
<button type="submit">submit</button>
</form>
Here is an example to do a form reset function:
function reset(){
setTimeout(function(){
var form = document.getElementById('myForm');
form.reset();
}, 1000);
}
var btn = document.getElementById('btn');
btn.onclick = function(){
reset();
}
<form id="myForm">
<input value="" />
<br />
<input value="" />
<br />
<input value="" />
<br />
<input value="" />
<br />
<button id="btn" type="button">reset</button>
</form>
Please note, that it seems that you are using some token along with the form.
This means, that if you reset the values, this token will still be there,
and maybe the server will not accept the next form submission, due the duplicate use of that token.
You will need to set a new token, when the server respond.
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.
Problem: Multiple forms on the same page, but only the first one is being submitted.
Tried the following:
Equating the data-ids of submit button and Form inorder to submit the clicked form (No Luck)
Dynamic form creation using Javascript.(disbanded that idea after a few tries since it was on a deadline)
Usecase
The number of forms depends on the User. If there is just one comment from him, the form submits, while if there are say 4 forms, only the first one will submit.
Javascript:
$(function() {
$(".submit").click(function() {
var data_id = $(this).data('id');
var form_id = $(this.form).data('id');
if (parseInt(data_id, 10) == parseInt(form_id, 10)) {
var commentid = document.getElementByID('commentid');
alert(commentid + formid);
} else {
alert("10");
}
});
});
PHP code:
if($comment['Comment_Username'] ==$this->getUser()->getName())
{$output .='div class="panel" data-class="'.$comment['CommentID'].'">';
$output .='<form class="form" action="" method="post" data- id="'.$comment['CommentID'].'">';
$output .='<textarea name="edit_text' class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
$output .='<input name="commentid" type="hidden" id="commentid" value="'.$comment['CommentID'].'"/>';
$output .='<input type="button' data-id="'.$comment['CommentID'].'" class="submit" value="submit"/>';
Any help would be greatly appreciated.
Thanks in advance
Wrong quote used here
$output .='<textarea name="edit_text" class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
Sorry for keep asking this, but I just can't figure it out. I've reduced the question to just the bare minimum.
How can I validate a dynamically generated form? Below is my attempt, but as seen, it shows up as passing validation.
https://jsfiddle.net/j2pgobze/1/
<form id="myForm">
<input type="text" name="email" id="email" value="bademail" >
</form>
<button id="validate">validate</button>
var myValidateObj = {
rules: {
email: {
email: true
}
}
};
$(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#validate').click(function () {
//Validate the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
console.log('Option 1', $('#myForm'), $('#email'), $('#email').val(), validate1.element('#email'), $('#email').valid(), $('#myForm').valid());
//Validate dynamically created form
var input = $('<input />', {
type: 'text',
name: 'email',
value: 'bademail'
});
//input.prop('value', 'bademail');
var form = $('<form />').append(input);
var validate = form.validate(myValidateObj);
console.log('Option 2', form, input, $('#email').val(), validate.element(input), input.valid(), form.valid());
});
});
The button needs to be inside the form and be a type="submit" in order for the plugin to capture the click.
Do not put .validate() within a click handler (See item 1). It's only used to initialize the plugin on a form. Exception, below we are creating the new form within a click handler and then immediately calling .validate() on the new form.
With these two small changes, the validation on the static form is working: jsfiddle.net/j2pgobze/3/
I rewrote your DOM manipulation code for clarity. I simply duplicated the HTML for the form and gave it a new ID: http://jsfiddle.net/zem84tfp/
$(function () {
// INITIALIZE plugin on the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
$('#newform').one('click', function () {
// code here to create new form; give it new ID
// do not duplicate ID on anything else
// INITIALIZE plugin on the new form
var validate = $('#myForm2').validate(myValidateObj);
});
});
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
});
}