I'm currently creating a subscription form using jQuery. My problem is I want to make this form stay in the same page after user click "SUBSCRIBE" button and when the process is successful, the text on button "SUBSCRIBE" change to "SUBSCRIBED".
Below is the code :
HTML:
<form action="http://bafe.my/sendy/subscribe" class="subcribe-form" accept-charset="UTF-8" data-remote="true" method="post">
<input type="hidden" name="authenticity_token" />
<input type="hidden" name="list" value="ttx7KjWYuptF763m4m892aI59A" />
<input type="hidden" name="name" value="Landing" />
<div class="form-group">
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Masukkan email anda" />
<span class="input-group-btn"><button type="submit" class="btn btn-primary">SUBSCRIBE<i class="fa fa-send fa-fw"></i></button></span>
</div>
</div>
</form>
jQuery:
$(".subcribe-form").submit(function(){
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
} else{
$(this).removeClass("has-error");
}
});
if (!validEmail) alert("Please enter your email to subscribe");
return validEmail;
});
You can use event.preventDefault to prevent the form submission but you also need to send the data to the server so for this you can use jQuery ajax ( see below code )
$(".subcribe-form").submit(function(event){
event.preventDefault()
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
}
else{
$(this).removeClass("has-error");
}
});
if (!validEmail) { alert("Please enter your email to subscribe");
}else {
//for valid emails sent data to the server
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('.subcribe-form').serialize(),
success: function(serverResponse) {
//... do something with the server Response...
}
});
}
return validEmail;
});
Add preventDefault so that form submission is prevented
$(".subcribe-form").submit(function(event){
event.preventDefault()
use serialize and post to send your data to desired url
Just handle the form submission on the submit event, and return false:
if using AJAX : (With ajax you can either do that, or e.prenventDefault (), both ways work.)
$(".subcribe-form").submit(function(){
... // code here
return false;
});
If using simple form :
$(".subcribe-form").submit(function(e){
... // code here
e.preventDefault();
});
In my opinion it would be easier to do it using PHP. If you do not want to use PHP, then you can ignore this answer.
If you want to give it a try, you can do the following:
1. Remove the action attribute from the form tag.
2. Write PHP code similar to:
if (isset($_POST['submit']) { // "submit" is the name of the submit button
onSubmit();
}
function onSubmit() {
/* your code here */
}
This is how I stay on the same page, a minimal example using jQuery:
<form id=f
onsubmit="$.post('handler.php',$('#f').serialize(),d=>r.textContent+=rd.innerHTML=d);return false">
<textarea name=field1 id=t>user input here</textarea>
<input type=submit>
</form>
<textarea id=r width=80></textarea>
<div id=rd></div>
The key is to return false from the form onsubmit handler.
Related
So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});
I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}
Why my page reloads even I used ajax to it and it also disappears my input text after clicking the submit button. I already used show to solve it but it doesn't work.
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="text" name="name" id="name">
<span id="namenotif" style="color:red;"> <span>
<br>
<input type="text" name="price" id="price">
<span id="pricenotif" style="color:red;"> <span>
<br>
<input type="submit" name="submit" id="save"><br>
</form>
<script>
$(document).ready(function() {
$(document).on("click","#save",function(){
var name = $("#name").val();
var price = $("#price").val();
if(name==""){
$("#namenotif").html("Enter a name");
$("#name").show("fast");
$("#save").show("fast");
}
else if(price==""){
$("#pricenotif").html("Enter a price");
$("#price").show("fast");
$("#save").show("fast");
}else{
$.ajax({
url:"addproduct.php",
type:"POST",
data:{name:name,price:price},
success:function(data){
alert("Successful");
}
});
}
});
});
</script>
add return false to end of function, that handle click event
Two solutions:
Change the button type='submit' to type='button'
or ( and preferably )
Change the event listener to listen for the form's onSumbit event then call event.preventDefault or in jQuery, I think you just do return false in the callback.
The form is being submitted I think, because it is the default behavior of submit button to submit the form, no matter if you used ajax or not. so you can prevent the default behavior by simple adding a code in jquery. Modify the code like this:
$(document).on("click","#save",function(e){
e.preventDefault();
...............
Rest of the codes can remain same. so only prevent the default action, it should work.
Its because of type="submit"
Use
<input type="button" name="submit" id="save"><br>
Or
<a href="javascript:void(0) id="save">
or
jquery's preventDefault();
When I am submitting the FORM using SUBMIT button, it takes me to the ACTION page. But I want to stay in same page after submission and show a message below the form that "Submitted Successfully", and also reset the form data. My code is here...
<h1>CONTACT US</h1>
<div class="form">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSe0dybzANfQIB58cSkso1mvWqKx2CeDtCl7T_x063U031r6DA/formResponse" method="post" id="mG61Hd">
Name
<input type="text" id="name" name="entry.1826425548">
Email
<input type="text" id="email" name="entry.2007423902">
Contact Number
<input type="text" id="phone" name="entry.1184586857">
Issue Type
<select id="issue" name="entry.1960470932">
<option>Feedback</option>
<option>Complain</option>
<option>Enquiry</option>
</select>
Message
<textarea name="entry.608344518"></textarea>
<input type="submit" value="Submit" onclick="submit();">
</form>
<p id="form_status"></p>
</div>
You need to use Ajax for sending Data and no refresh the page.
//Jquery for not submit a form.
$("form").submit( function(e) {
e.preventDefault();
return false;
});
//Ajax Example
$.ajax({
data: {yourDataKey: 'yourDataValue', moreKey: 'moreLabel'},
type: "POST", //OR GET
url: yourUrl.php, //The same form's action URL
beforeSend: function(){
//Callback beforeSend Data
},
success: function(data){
//Callback on success returning Data
}
});
Instead of adding onclick="submit()" to your button try capturing the submit event. In your submit function you also need to return false and prevent default to prevent the form from not submitting and taking you to the action page.
Using jQuery it would look something like this:
$("#id_form").on("submit", function(e){
//send data through ajax
e.preventDefault();
return false;
});
i am making a registration form in which php code and html form are in the same page , and i have also have a java script which validate the fields, but if the validation is done, i need to post the data by calling php and submit in database
if(isset($_POST['Name'])){
$order = "INSERT INTO `reg_form`(`Name`) VALUES ('$_POST[Name]')";
$result = mysql_query($order, $db2);
if (!$result) {
echo("<br>Input is failed");
} else {
echo 'Regestered successfully !!!';
}
}
<form name="register" id="register" class="b1 f_l" action="register.php" method="post">
<div class="input-group" style="padding-top: 20px;">
<span class="label_1">Name </span>
<input type="text" class="inp_t" placeholder="Your Name" name="Name" id="name" required>
</div>
<div style="padding-top: 20px;">
<button type="submit" class="btn btn-primary register" value="submit" >Submit</button>
</div>
</form>
<script language=JavaScript>
$('#register').validator()
.submit(function(e){
var form = $(this);
var valid = form.validator({messageClass: "alert alert-danger validate_error", position: 'center right'});
if (valid.data("validator").checkValidity()){
alert('not working');
}// VALID
e.preventDefault();
return false;
});// SUBMIT
</script>
So you only want to prevent the default action if the form is not validated properly:
if (valid.data("validator").checkValidity())
{
// Assuming this means Validation failed
alert('not working');
e.preventDefault();
return false;
}
else
{
// It's working, let the submission go through
return true;
}
Now you need to give your submit button a name so that PHP can know about it
<button type="submit" name='submit-btn' class="btn btn-primary register" value="submit" >Submit</button>
And lastly you need to update your PHP script to handle the form submission.
Put this script at the top of your register.php file since that's where your form is submitting to, and since you're submitting via POST, check the post array:
// Submit button value check here
if(isset($_POST['submit-btn'] && $_POST['submit-btn'] == "submit")
{
// Handle your form submission here
// Read the data from the $_POST array using the name you gave to the form elements
// Create a database connection and store your data in the database
}
You should write "return true" some where in your JS function for the form to submit. If the validation is successful then return true from your JS function
You have to call event.preventDefault() only when validation fails. So moving it to else clause.
<script language=JavaScript>
$('#register').validator()
.submit(function(e){
var form = $(this);
var valid = form.validator({messageClass: "alert alert-danger validate_error", position: 'center right'});
if (valid.data("validator").checkValidity()){
alert('not working');
return true;
}// VALID
else {
e.preventDefault();
return false;
}
});// SUBMIT
</script>
call the validator function using onClick="validate()" and when the validation is successful, submit the form with document.getElementById("register").submit();
I have implemented a simple javascript validation but the validation and the form submission never happen together ...
When i use "onsubmit" (like below) it will goto the next page without validation
if i use "onclick" on the end of the form
<input type="button" name="submit" id="send" value="Search Flights" onclick="return validate_booking_form();" />
</form>
it will validate the input .. but the form wont be submitted even the correct input
This is the code i have used
//Javascript Validation
function validate_booking_form()
{
chk_fromcity();
chk_tocity();
chk_depature_date();
}
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
})
}
else
{
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
}
}
and the form
<form method="POST" action="../controller/booking.php" name="search_flights_names" onsubmit="return validate_booking_form();" >
/// Form content
<div class="form_input_container">
<div class="form_input">
<input type="text" id="from_cities" name="from_city" class="fieldInput" onblur="return chk_fromcity()" />
</div>
</div>
<input type="submit" name="submit" id="send" value="Search Flights" />
</form>
Submit is the proper button to use.
Try putton onsubmit in your form element and have the validation occur there instead of on the click event. That way pressing enter won't bypass all of your validation.
Try using Jquery validate. I think it should pretty much solve your problem
return false from chk_fromcity() to stop the form posting to action.
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
});
return false;
}
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
// return true; // default is true which is why you were passing the validation
}