I'm submitting a form with jquery and can't seem to stop the page from reloading after the form submits.
My current code looks like this:
HTML:
<form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" />
<div class="control-group">
<label class="control-label">Image Path</label>
<div class="controls">
<input type="text" name="imagepath" id=imagepath />
</div>
</div>
<div class="form-actions">
<input type=button value="Send" id="sendemailbtn" class="btn btn-primary" />
</div>
</form>
jQuery:
$("#sendemailbtn").click(function(e) {
e.preventDefault();
$("#basic_validate").submit();
if ($("#basic_validate").children('.control-group').hasClass('error')) {
return false;
} else {
$.post('send_email.php', $("#basic_validate").serialize(), function(data) {
// I see output on the server side but never hit this area after the submission,
console.log(data);
}, "json");
}
});
$("#basic_validate").submit();
Is your culprit. That line submits the form and makes the page reload.
According to the submit doc,
[...] We can cancel the submit action by calling .preventDefault() on
the event object or by returning false from our handler.
As .preventDefault() doesn't seem to work for you, try :
$("#basic_validate").submit(function(){
if ($("#basic_validate").children('.control-group').hasClass('error')) {
return false;
}
else {
$.post('send_email.php', $("#basic_validate").serialize(), function(data) {
// I see output on the server side but never hit this area after the submission,
console.log(data);
}, "json");
}
return false; //This prevents reloading
});
That's because .submit() works that way. If you want to submit the form with AJAX then you want to make an AJAX request manually with $.post without .submit():
$("#sendemailbtn").click(function (e) {
e.preventDefault();
if (!$("#basic_validate").children('.control-group').hasClass('error')) {
$.post('send_email.php', $("#basic_validate").serialize(),
function(data) {
console.log(data);
}, "json");
}
});
Related
I want to add css to a class when my form is submitted because it take long time, but nothing change! here is my form
<form method="post" class="std" enctype="multipart/form-data">
<button type="submit" name="submitAddProduct" class="btn btn-default button button-medium">
<span>Garder<i class="icon-chevron-right right"></i></span>
</button>
</form>
the div I want to change :
<div id="circlecontainer"></div>
and my script :
$('form.std').submit(function(e){
$( "#circlecontainer" ).removeClass('whatever').addClass('whatever');
});
I want the button to be disabled too when the submit goes on?
Try this.
<form id="myForm" method="post" class="std" enctype="multipart/form-data">
<button type="submit" id="submitBtn" name="submitAddProduct" class="btn btn-default button button-medium">
<span>Garder<i class="icon-chevron-right right"></i></span>
</button>
</form>
$('#myForm').submit(function(e){
$("#circlecontainer").addClass('whatever');
$("#submitBtn").prop('disabled', true).html('Please Wait...');
});
Reason 1. you will need e.preventDefault(), otherwise submit the form will refresh the whole page
Reason 2. Since reason 1, You will need to use ajax to post the form data instead of using default form event, please refer to this question for how to set it up in your submit function jQuery AJAX submit form
<script type="text/javascript">
$( "#circlecontainer" ).removeClass('whatever')
var frm = $('.std');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: //'your post url',
data: frm.serialize(),
success: function (data) {
$("#circlecontainer").addClass('whatever');
}
});
ev.preventDefault();
});
</script>
Simple add a listener to your button and change the class attribute
var divClassChanger=function()
{
var div=document.getElementByID("circlecontainer");
div.setAttribute("class", "someotherclass");
document.getElementById("yourBtnId").disabled = true;
};
document.getElementById("yourBtnId").addEventListener("click",divClassChanger);
you only need a id in you button
You really need to consider using Ajax request as this will definitely solve your problem. As you have it
<form method="post" class="std" enctype="multipart/form-data">
<button type="submit" name="submitAddProduct" class="btn btn-default button button-medium">
<span>Garder<i class="icon-chevron-right right"></i></span>
</button>
</form>
AJAX Request Script
$('form').on("submit", function(e) {
e.preventDefault();
var $form = $(this), url = $form.attr('action');//url could be your PHP script
var posting = $.post(url, {$('yourinputs').val()});
posting.done(function(data){
$('.circlecontainer').removeClass('yourclass');
});
});
This should work.
Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly
I have the following function
(inside onchange; console.log works well)
$("#prof_picture").ajaxForm(
{
target: '#preview',
success: function(response){
console.log("called");
}
});
The success function is not called and therefore no feedback is received. Feedback is echoed in the following way "{message:"success",action:"something",data:Array}". Can someone help me please? Thank you very much
Here is the form
<form id="profile_picture_upload" enctype="multipart/form-data" action="profile/uploadProfilePicture.php" method="post" name="prof_picture">
<input id="profpic1" style="display:none;" name="profile_picture" type="file">
<a id="change_profile_picture" class="profile_option" onclick="$('#profpic1').click();">Upload</a>
</form>
As Quentin mentioned, the form isn't submitting.
Bind the ajax to the correct form ID instead of the name of the form
$("#profile_picture_upload").ajaxForm(
{
target: '#preview',
success: function(response){
console.log("called");
}
});
And use this html to submit the form
<form id="profile_picture_upload" enctype="multipart/form-data" action="profile/uploadProfilePicture.php" method="post" name="prof_picture">
<input id="profpic1" style="display:none;" name="profile_picture" type="file" onchange="$('#profile_picture_upload').submit();">
<a id="change_profile_picture" class="profile_option" onclick="$('#profpic1').click();">Upload</a>
</form>
though it'll click through to the next page if you do this, so you probably want to add the return false to prevent it from leaving this page.
I have a problem that others seem to have, but I cannot get the recommended solution (i.e., "return false;") to work. Any help would be great!
Description:
When the form is submitted, I want to validate the input is in the correct format (i.e., type="email") and launch an alert (i.e., "Form submitted.") without the page refreshing. Currently, the alert does not appear and the page refreshes.
Test Code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- JavaScript -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<!-- Form -->
<form>
<input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
<button type="submit" id="submit">Submit</button>
</form>
<!-- Alert on Submission -->
<script>
console.log("Ready to Go!");
$('#submit').submit(function () {
alert("Form submitted.");
return false;
});
</script>
</body>
</html>
You will want to catch the submit event of the form. There is no submit event on a button.
$('form').submit(function () {
if (*everything ok*) {
alert("Form submitted.");
} else {
return false;
}
});
Ideally you would help identify your <form>, either with an ID or a class, i.e.:
<form id="xyz-form">
And then change your selector to:
$('#xyz-form').submit(...);
Now this is only to stop the form from submitting when there are errors. When return false; isn't the path the submit callback takes, your page is going to refresh. If you want to submit the data to the server without a refresh, you will need to approach this differently.
Give your form an ID, and change your jquery to use #formid instead.
For example :
<form id="form">
<input type="email" placeholder="Email" value="" size="25px" required="required" id="userEmail">
<button type="submit" id="submit">Submit</button>
</form>
<script type="text/javascript">
$('#form').submit(function () {
alert("Form submitted.");
return false;
});
</script>
The event handler attached to the submit function in jQuery can be the form element or a div element. Read more on jQuery API
You can implement a click event when the user clicks on the submit button without its default submitting behavior with jQuery's preventDefault function
console.log("Ready to Go!");
$('form').submit(function () {
alert("Form submitted.");
return false;
});
$("#submit").click(function(e){
if (hasError){
e.preventDefault();
}
else{
alert("success");
}
})
The if and else statements are created for simple validation. For the scope of your question, I leave most of the coding for your creativity. But you can basically create a simple function to check for errors with the user inputs, if there are errors,prevent the submit button's default submission behavior. If the inputs are not empty and if inputs are free of errors, alert the user that the form has been submitted.
try this instead
$('#submit').click(function () {
alert("Form submitted.");
return false;
});
it'll accomplish what you want.
basically the click fires before the submit
try this snippet to clear things up
console.log("Ready to Go!");
$('#submit').click(function () {
alert("Form submitted.");
//return false;
return true;
});
$("form").submit(function( event ) {
alert("woot woot");
});
I have 2 divs:
<div class="lobsummary">
<input type="submit" name ="sbmtbtn">
<input type="submit" name ="sbmtbtn">
</div>
<div class="applicationsummary">
</div>
I want to show applicationsummary when sbmtbtn is submitted so I used the below script:
$('.lobsummary input:submit').submit(function (event) {
$('.applicationsummary').show();
$('.lobsummary').hide();
});
But its not working.
EDIT: The divs are enclosed in <% Html.BeginForm("Index", "Home"); %> which I am using to pass values to my controller from the view.
Use event.preventDefault() it stops the default action
$('.lobsummary input[type=submit]').click(function (event) {
event.preventDefault();
alert($(this).index() + 1);
$('.applicationsummary').show();
$('.lobsummary').hide();
});
#Rajaprabhu Aravindasamy is right,use submit() over a form:
$("form").submit( function () {
return false;
} );
HTML on the client side will be like:
<div class="lobsummary">
<form action="/"method="post">
<input type="submit" name ="sbmtbtn">
</form>
<form action="/"method="post">
<input type="submit" name ="sbmtbtn">
</form>
</div>
<div class="applicationsummary">
</div>
Just use click() to test your jquery selection:
$('.applicationsummary').hide();
$(".lobsummary form:eq(0)").click(function () {
alert(1)
$('.applicationsummary').show();
});
$(".lobsummary form:eq(1)").click(function () {
alert(2)
$('.applicationsummary').hide();
});
Then replace the click to submit.
When the form was submitted, it reloaded the whole page and that's why it was not hiding because it was going back to its default view. So I used if statements in my view to hide the forms.