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;
});
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');
}
});
}
I have a form that is executed every time a submit button is clicked. When the submit button is clicked, a modal is shown and the modal is populated with JSON data. The application /addresschecker checks against the addresses posted and sends me an error message if I get a code return number of 2003. If not I select the return data via JSON using jQuery's $.each
The application works but when I close the modal, refill out the form and click submit, the form does not make a new call to /addresschecker I looked in my network tab of chrome and it seems to be using the old data. I am thinking that I need to force a new Ajax call everytime a user clicks on the submit button or clear the cache somehow. Not sure why I'm seeing old data
<form id="Validate">
<input class="form-control" id="adr1" name="address1" type="text" placeholder="Address 1" />
<input class="form-control" id="adr2" name="address1" type="text" placeholder="Address 1" />
<button type="submit" >Submit</button>
</form>
<div class="modal hide">
<!-- JSON Data returned -->
<div id="Message_1"></div>
<div id="Message_2"></div>
<div id="error_message"></div>
</div>
// My main form code
submitHandler: function(form) {
$.ajax({
url: '/addresschecker',
type: 'post',
cache: false,
dataType: 'json',
data: $('form#Validate').serialize(),
success: handleData
});
function handleData(data) {
var mesgcheck = data.message;
if (data.code == '2003') {
$("#error_messag").html(mesgcheck);
} else {
// Display Modal
$(".modal").removeClass("hide");
$.each(data, function(i, suggest) {
$(".adr1").val(suggest.address1);
$(".adr2").val(suggest.address2);
});
}
}
}
Let ajax handle your request.
Use this:
<input type="button" value="submit">
Instead of type submit.
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.
I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").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.
});
I have login form where are two buttons - "login" and "forgot password?" And I need to check what button user clicked.
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
</form>
var_dump($_POST) says:
array(2) { ["email"]=> string(0) "" ["password"]=> string(0) "" }
I am trying both ways (input type=submit and button type=submit) but none of them send the "submit" value.
(I am using jquery ajax)
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php", /* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function(data){
$("#login-error").html(data);
},
error:function(){
$("#result").html('There is error while submit');
}
});
});
Please do you know where the problem can be? I know, there are lot of threads about value of button but nothing works for me. I also tried this example:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2
The .serializeArray() or .serialize() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
Refer..
http://api.jquery.com/serialize
http://api.jquery.com/serializeArray
jQuery serializeArray doesn't include the submit button that was clicked
This is one way to do it, concatening data string with specific clicked button name attribute:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit">Login</button>
<button type="button" name="forgot" class="submit">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize() + '&' + this.name;
console.log(values);
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php",
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
But better would be to target specific server side script depending which button is clicked, e.g:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit" data-url="login.php">Login</button>
<button type="button" name="forgot" class="submit" data-url="forgot.php">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: $(this).data('url'),
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
It will be a lot easier to check if you name the submit input and the button differently.
You currently have this set up like this:
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
Try changing the name of the button to something like:
name="forgot"
then you can run a check on it such as
if (isset($_POST['submit'])){
stuff here
}
and a separate check for
if (isset($_POST['forgot'])){
stuff here
}
If there is not event in function then it will not prevent the submit function and by default get will be called and and $_POST will be empty for sure
Change
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
To
$("#loginForm").click(function(event){
/* Stop form from submitting normally */
event.preventDefault();
Make one more change
data: values,
To
data:$("#loginForm").serialize(),
Remove one submit type there should be only one submit type make it type of button and call onbutton click functiuon to submit via ajax it will work same as submit.