I want use loader.gif to display as processing before confirmation message shown when hit on submit button for contact form
loader.gif must be shown next to submit button
Can anyone plz help me to put code, as I don't know to which code to insert????
My fiddle link: http://jsfiddle.net/jPp64/
HTML
<div class="form-group">
<label for="exampleInputArea">Area</label>
<select style="color:#000 !important" class="form-control" id="exampleInputArea" placeholder="Select Month" name="exampleInputArea">
<option value="" >--Select Area--</option>
<option value="Area1">Area1</option>
<option value="Area2">Area2</option>
<option value="Area3">Area3</option>
</select>
<div style="color:red;" id="areaerror"></div>
</div>
<div class="form-group last">
<button class="btn btn-lg btn-red mailbtn">Submit</button>
</div>
JS
$('.mailbtn').live('click',function(){
area = $('#exampleInputArea').val();
if (area.length == 0 || area == '') {
$('#exampleInputArea').val('')
$('#areaerror').text('Area is Required');
return false;
} else {
$('#areaerror').text('');
}
$.ajax({
type: "POST",
async : false,
url: "mail.php",
data: {area:area}
})
.done(function( msg ) {
$('.mail_middle').html('');
$('.mail_middle').html('We will call you to confirm your delivery address.<br/>Thank you.');
return false;
});
});
All you need to do is put an image next to the Submit button where you want it and set the CSS on it to display: none; to hide it. Then when you are inside your .live('click') event, the first line should show the image using $('#imgId').show(); with jQuery. Then just hide the image again when the ajax is complete.
Keep in mind that since you'll probably be using a gif, you need to make your ajax call asynchronous so change the async: false to true. If you don't do this, your animated gif will appear as a static image because synchronous calls will lock the browser.
You could have your GIF in a div (where you like) with style="display:none;"
When you're sending your ajax request, simply use a jQuery's show().
When the data is received, use hide().
Example:
[...]
$.ajax({
type: "POST",
async : false,
url: "mail.php",
data: {area:area}
})
success: function(){
$('#ID_YOURGIF').show();
},
.done(function( msg ) {
$('.mail_middle').html('');
$('.mail_middle').html('We will call you to confirm your delivery address.<br/>Thank you.');
return false;
});
$('#ID_YOURGIF').hide();
[...]
Related
I have the following html:
<div class="form-outline mb-4">
<input type="text" id="PlanID" asp-for="PlanID" name="PlanID" class="form-control form-control-lg" value="#Model.PlanID" />
<label id="errorLabel" name="errorLabel" class="form-label text-danger" for="PlanID"></label>
</div>
<button class="btn btn-primary btn-lg btn-block" type="button" disabled id="nextButton" name="nextButton" onclick="DisplayProgressMessage(this, 'Next');">Next</button>
And I have the following jquery:
$.ajax({
type: "POST",
url: "#Url.Action("CheckPlanID")",
data: {PlanID: planID},
dataType: "text",
success: function (msg) {
if (msg.length > 4) {
console.log(msg.length);
$("#nextButton").prop("disabled", true);
$("#errorLabel").text = msg;
}
},
error: function (req, status, error) {
console.log(msg);
}
});
I have additional jquery that keeps the button disabled until the length of the data in the input is 4. When the length is 4, I enable the button.
When running the code, as soon as the length of the data in the input box is 4, the button is enabled and I click on it. the ajax executes and sends the data to my controller. The controller processes the data and will send back a string. If the length of the returned string is greater than 4, then the string being returned is an error string and that error string should get displayed to the user.
When I run the code and force an error, I can see the length of the error string being displayed in the console so I know this section of code is being executed. The button gets disabled, but the text of the errorLabel is not changing.
The text of the errorLabel should change to the error message. Is there something else that needs to be done? Am I missing something?
Thank you!
In jQuery, text is a method not an attribute so to fix your issue you'd simply change this
$("#errorLabel").text = msg
into this
$("#errorLabel").text(msg)
Also it seems, based on your code if (msg.length > 4), you only change the text if msg length is greater than 4. That means, unless msg has 5 characters or more the text won't change.
Learn more about text() method on jQuery docs.
I need to submit a form using FormData() but in the form i use a button with type="button" instead of type="submit" which will refresh the page. I tried to search on google for solution but so far couldn't find the right answer or a clear answer. I will be posting a simple form with 3 inputs and start from here if i want to go bigger. When i var_dump[$_POST] i get empty array[0]{}
please help.
$("#discussion_submit_button").on("click", function(e){
//$("#discussion_form").submit(function(e){
e.preventDefault();
var title = $("#discussion_title").val();
var discussion = $("#discussion_input_textarea").val();
if (title == '' || discussion == '') {
$(".discussion_label_arrow, .discussion_required_fields").fadeIn("Slow");
// error message, we select span tag with ID error_message and we change its content to this text
setTimeout(function(){
$('.discussion_label_arrow, .discussion_required_fields').fadeOut("Slow");
}, 2000);
} else {
var formData = new FormData(this);
alert(formData);
$.ajax({
url: "widgets/discussion_board_submit.php",
method: "POST",
cache: false,
processData: false,
contentType: false,
data: formData,
success:function(data){
//alert(data);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" class="discussion_form" id="discussion_form">
<div class="discussion_label_div"><span class="discussion_label_span">Title</span><span class="discussion_label_arrow"><span></div>
<div class="discussion_input_div"><input type="text" name="discussion_title" class="discussion_input" size="50" id="discussion_title"/></div>
<div class="discussion_label_div"><span class="discussion_label_span">Subject</span><span class="discussion_label_arrow"><span></div>
<div class="discussion_label_div"><span class="discussion_label_span">Discussion</span><span class="discussion_label_arrow"><span></div>
<textarea rows="5" cols="50" name="discussion_textarea" class="discussion_input_textarea" placeholder="Open your discussion..." id="discussion_input_textarea"></textarea>
<input type="button" name="discussion_submit_button" value="Assert" class="share_button" id="discussion_submit_button"/>
</form>
and this is my php :
var_dump($_POST);
Instead of validating the form with javascript add a required attribute to the fields that can't be empty.
If you like You can use css styling such as :invalid to style them
user will get focus on the first element that is wrong and will be able to correct it when they try to submit it.but that can't happen unless the submit event is triggered which won't happen if you use a button.onclick or a type="button" and prevent the flow. And that is your mistake.
when you construct your formdata the argument becomes a button element and not a form which the FormData requires
new FormData(this); // <-- `this` is a button elm in your case
So when you use constraint validation, then submit event will only get trigger if all fields are valid. So you will always have a valid form on the submit event and this will be referred to the form element which you need for the FormData
So here is what i should have done:
function form2ajax(evt) {
evt.preventDefault();
var formData = new FormData(this);
// Having html define the markup
// makes you able to reuse this function
// for other forms
$.ajax({
url: this.action,
method: this.method,
cache: false,
processData: false,
contentType: false,
data: formData,
success: function(data) {
//alert(data);
}
});
// Just Another solution to submit the form...
// fetch(this.action, {method: this.method, body: formData})
// .then(res => res.text())
// .then(console.log)
}
$("#discussion_form").submit(form2ajax)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="widgets/discussion_board_submit.php" class="discussion_form" id="discussion_form">
<div class="discussion_label_div">
<span class="discussion_label_span">Title</span>
<span class="discussion_label_arrow"><span> <!-- note missing / in span -->
</div>
<div class="discussion_input_div">
<!-- note required attribute -->
<input type="text" required name="discussion_title" class="discussion_input" size="50" id="discussion_title"/>
</div>
<div class="discussion_label_div">
<span class="discussion_label_span">Subject</span>
<span class="discussion_label_arrow"><span> <!-- note missing / in span -->
</div>
<div class="discussion_label_div">
<span class="discussion_label_span">Discussion</span>
<span class="discussion_label_arrow"><span> <!-- note missing / in span -->
</div>
<!-- note required attribute -->
<textarea required rows="5" cols="50" name="discussion_textarea" class="discussion_input_textarea" placeholder="Open your discussion..." id="discussion_input_textarea"></textarea>
<!-- note using type=submit instead of type=button -->
<!-- type=button don't trigger a submit -->
<input type="submit" name="discussion_submit_button" value="Assert" class="share_button" id="discussion_submit_button"/>
</form>
The problem is you pass this to FormData constructor, but it requires form element to initialize object.
You can do this:
var formData = new FormData(this.form);
or just pick form from DOM:
var formData = new FormData($("#discussion_form")[0]);
Just remember you have to pass HTMLFormElement to FormData, so you can't use jQuery object. That is why I pick first element from the jQuery array.
I have a form on a page.
<div id="form_catch">
<form id="form2">
<div><input type="button" value="Dear Diary" id="add" /><input type="button"
value="Dear Friend" id="add_1" /></div>
<div><input type="text" id="salutations" name="salutations" value=""/></div>
<input type="submit" value="Submit" class="submit" />
</form>
</div>
I use a javascript to manipulate this form
$(document).ready(function(){
var form_box_copy = $('#form_catch').html()
$("#add").click(function(){
$('input#salutations').val('Dear Diary,');});
$("#add_1").click(function(){
$('input#salutations').val('Dear Friend,');});
//console.log('test button');
$("form#form2").submit(function(evt){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://wei.rocks/test2.html',
type: 'GET',
data: {
format: 'html'
},
enctype: 'multipart/form-data',
processData: false,
error: function(){alert('You Failed');},
success: function (response) {
alert('You passed');
$('#form_catch').html(form_box_copy + "html replaced");
$('#form_catch').append("Test222222222");}
});
return false;
})
})
When I run the page the scrip works as designed I ajax the form, the task are successful. After success It replaces the form with a fresh copy of it self. All this work except when it is complete the Replacement of the form is no long working with the Java script.
The reason this is happening is because when you replace the form with the new html, it discards the submit event registration attached to the form.
To bypass it you can either re-register the event or, as a better approach, register the event at the document level.
Simply change:
$("form#form2").submit(function(evt){
// your code
});
to:
$(document).on('submit', '#form2', function(evt) {
// your code
});
});
This should now work since the event is registered at the document level and not at the form level (and the document is never being replaced).
In general if you are replacing DOM elements, then the events registered to them will no longer work. This is why registering to the element's parent is a better approach (when needed).
See this codepen for working example.
Hope this helps.
I have an html page with some checkboxes:
<div class="col-md-2">
<div class='form-group employe-admin-contactP'>
<input type="checkbox" class="readymade-checkbox admin" name="" id="admin-${member?.user?.id }" data-id="${member?.user?.id }"
<g:if test="${member?.isAdmin()}">
checked
</g:if>
/>
<label for="admin-${member?.user?.id }" name="" class="readymade-label admin"></label>
</div>
</div>
Each time the user click on the checkbox (check/uncheck) a the following function which I wrote in js file have to be triggered:
$(document).ready(function() {
$('.readymade-checkbox.admin:not(checked)').on('click',function(){
var contact = {id:$(this).data('id') }
$.ajax({
url: makeUserAdmin,
type: "post",
data: {
id: JSON.stringify(contact), companyId: $('#teamCompanyId').val()
},
success: function (data, textStatus) {
jQuery("#updateCompanyteam").html(data);
}
})
return false;
});
})
The problem is that this the function is triggered only once.
I bet that jQuery("#updateCompanyteam").html(data); will modify the HTML area of the checkbox ".readymade-checkbox.admin". You need a persistant listener for your click event (which will be available even if the DOM is modified), or to refresh your listeners.
This issue has been already resolved in several threads like this one.
Cheers
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
});
}