Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)
My form is inside a modal and this is my script
$(function() {
$("#applyForm").on('submit' , function(e) {
$.ajax({
type: 'POST',
url: $("#applyForm").attr("action"),
data: $('#applyForm').serialize(),
success: function(data){
alert('successfully submitted')},
error: function(data){
alert('something went wrong')
}
});
});
});
It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.
How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.
Heres the form
<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">
MY FORM DATA
<button type="submit" id="submit" class="btn btn-warning">Apply now</button>
Any help would really be appreciated !
Thanks
J
The form is being submitted twice. Once with the form action and the other time with the ajax call. If you prefer to have only the ajax call sent, returning false outside the ajax function should do the trick. When to use PreventDefault( ) vs Return false?
$(function () {
$("#applyForm").on('submit', function (e) {
//e.preventDefault();
$.ajax({
type: 'POST',
url: $("#applyForm").attr("action"),
data: $('#applyForm').serialize(),
success: function (data) {
alert('successfully submitted')
},
error: function (data) {
alert('something went wrong')
}
});
return false;
});
});
Try this if you want the page not to reload:
$(function() {
$("#applyForm").on('submit' , function(e) {
e.preventDefault();
//... the rest of your code
//or add return false;
return false;
});
});
As you catch the actual submiting the "normal" process will happen, you don't wan't that. So you have to stop it by e.preventDefault(). You can read the documentation about it here.
Or look right here for an example where it stays on the same page.
$("#form").submit(function(e){
e.preventDefault();
$(this).append("The page is staying here");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
<input type="text" name="first" id="first">
<input type="submit" value="enter">
</form>
Hopefully this helps you.
I Hope this work.
1) <button type="submit" id="submit" class="btn btn-warning">
Apply now</button> with preventDefault method
2) button type="button" id="submit" class="btn btn-warning">Apply now</button>
change the type="submit" to type="button"
Example
<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="text" value="1">
<input name="listing_id" type="text" value="999">
MY FORM DATA
<button type="button" id="submit" class="btn btn-warning">Apply now</button>
</form>
$(document).ready(function(){
$("#applyForm").on('click','#submit' , function() {
alert("Click check")
console.log($('#applyForm').serialize())
});
});
You're not preventing the default form submission behavior. To fix up, add the following immediately before your Ajax call:
e.preventDefault();
Extra tip: to ensure the form only gets submitted once per "submit" click, stop the propagation of the click event from bubbling up through the DOM.
Immediately following the preventDefault, put this:
e.stopPropagation();
Related
I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?
How do i accomplish the form and script so I do not have to refresh?
Here is the form:
<form role="form" class="form-horizontal validate" name="create_form" id="create_form">
<div class="form-group">
<label class="col-sm-2 control-label" for="name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
</div>
</div>
<div class="form-group-separator"></div>
<div class="form-group">
<button id="submit_btn" class="btn btn-success">Create</button>
<button type="reset" class="btn btn-white">Reset</button>
</div>
</form>
And here is the AJAX part:
$(document).ready(function(){
$("#submit_btn").on("click", function () {
$.ajax({
type: 'POST',
url: 'data/create.php',
cache: false,
data: $('#create_form').serialize()
})
.done(function(data){
$("#name").val("");
})
.fail(function() {
console.log("ERROR");
});
// Prevent refreshing the whole page page
return false;
});
});
Hoping for help and thanks in advance :-)
use submit instead of click.
$('#submit_btn').on('submit', function(e) {
e.preventDefault();
... //rest of the code
});
I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
I am trying to get this ajax o work on the first button, on the second button I am just trying to see if I at least hit the jquery but this is not happening for some reason, my code is as follows.
<form id="postform" >
<input class="btn btn-lg" style="border: 1px solid gray;" name="email" id="email" type="email" placeholder="Enter Your Email" required>  
<button class="btn btn-info btn-lg" id="emailbutton" onsubmit="submitting()" type="submit">Submit</button>
<input class="btn btn-info btn-lg" type="submit" id="#inputbutton" value="Shooter" ></input>
</form>
<script>
(function ($) {
function submitting(e)
{
e.preventDeafault();
$('#emailbutton').on('submit', (function () {
alert("Clicked");
$.ajax
({
type: 'POST',
url: 'bootstrap/php/form.php',
data: $(this).serialize(),
success: function (result) {
console.log(result);
$('#postform').html(result);
}
});
}));
}
function subshooter() {
$('#inputbutton').click(function() { alert('testbutton clicked'); });
}
});
</script>
My main aim to get the ajax working so when people submit their email address on a form the resulting ajax will process a php file and the html will change to something like "Thank You" without refreshing the entire page.
Modified Html
<form id="postform" >
<input class="btn btn-lg" style="border: 1px solid gray;" name="email" id="email" type="email" placeholder="Enter Your Email" required>  
<button class="btn btn-info btn-lg" id="emailbutton" type="submit">Submit</button>
<input class="btn btn-info btn-lg" type="submit" id="inputbutton" value="Shooter" ></input>
</form>
your script have so many errors that is the reason why it is failed... in future always check browser console...
corrected js:
<script src="https://code.jquery.com/jquery-1.10.2.js" ></script>
<script>
$(document).ready(function (){
$('#inputbutton').on('click',function() { alert('testbutton clicked'); });
$('#postform').on('submit',function(e){
e.preventDefault();
alert("Clicked");
$.ajax({
type: 'POST',
url: "bootstrap/php/form.php",
data: $(this).serialize(),
success: function (result) {
console.log(result);
alert("success");
$('#postform').html(result);
},
error: function (){
alert("Unable To post");
}
});
});
});
</script>
When submitting gets called, it is attaching a click event to the button, but that event has already happened, so it would not get called again until the Submit button has been clicked again.
Likewise, preventDeafault is misspelled and most likely causing execution to stop.
Another problem is that you are not passing in an event to submitting, so e will be undefined.
Since you are using jQuery, you should attach the event using jQuery, which will give you access to the event and the preventDefault function:
$('form').submit( function (e) {
e.preventDefault();
});
You should use the below code:
<script>
(function ($) {
$('#inputbutton').click(function() {
alert('testbutton clicked'); });
});
function submitting(e)
{
e.preventDefault();
$('#emailbutton').on('submit', (function () {
alert("Clicked");
$.ajax
({
type: 'POST',
url: 'bootstrap/php/form.php',
data: $(this).serialize(),
success: function (result) {
console.log(result);
$('#postform').html(result);
}
});
}));
}
</script>
Mistakes that you made:
the function to prevent default is e.preventDefault();
In jquery you should bind the click event to the button on page load.
Since submitting(e) is a function it should be outside the onbody load event i.e document.ready({ ... }) function.
UPDATE - the contact form is found at this URL.
I am trying to get the following contact form to function, using this tutorial.
I manage to get everything to work as expected on my computer using apache webserver.
After uploading the files to an online website, the ajax function does not kick in.
I seems like the e.preventDefault(); stops working after the upload, and the form is redirected to a new site,and not just being processed on the site without the reload.
I have also been trying to use the return false; instead of e.preventDefault(); without any success.
Her is my code:
.html
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
Please help!
That's because your JS is missing a closing });. Please check this demo to confirm that the default action is indeed prevented and the ajax does kick in. However, I was expecting a POST but instead I am seeing an OPTIONS request.
NOTE: Giving an element a name or id attribute value of submit is bad practice. You cannot for example use JavaScript to submit the form via default form submission -- this.submit() or $('form')[0].submit() without getting the error ...submit() is not a function .....
$(function() {
$('form').submit(function(e) {
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$("#loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$("#loading").fadeOut(function() {
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
});
}); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
Since you are submitting via AJAX anyway, you may find it easier to change your input type to button, and bind to click instead of form submit, to avoid the default submit behaviour you are trying to circumvent.
<form accept-charset="UTF-8" action="/twitts" class="dialog " id="twitt-form" method="post" title="Dialog" selected="true">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓">
<input name="authenticity_token" type="hidden" value="BkLNJsJfbEzfQrCTDWHW4OvvOh0l2pLPxxEJ/bGt2IY="></div>
<input id="anonymous_id" name="anonymous[id]" type="hidden" value="22">
<fieldset>
<h1>Отправить сообщение</h1>
<a class="button leftButton" type="cancel">Отмена</a>
<a id="submit-twitt" class="button blueButton">Отправить</a>
<!-- <input class="button blueButton" id="submit-twitt" name="commit" type="submit" value="Отправить" /> -->
<input id="twitt-text" name="twitt[text]" size="30" type="text">
</fieldset>
<div class="spinner"></div>
</form>
when i call
$('#twitt-form').submit();
In the debugger or inside click event handler just nothing happened. And even if set .submit handler to the form
$('#twitt-form').submit(function() {
$('#twitt-text').val('');
$('#twitt-form').attr('selected', false);
return false;
});
Handler DOES work, but form does not submit any data. Why ?
And more: when I press Enter on form field #twitt-text form just submit well and .submit handler works also.
$('#twitt-form').submit(function() {
$('#twitt-text').val(''); <--- this it will make form value empty
$('#twitt-form').attr('selected', false);
return false;
});
why you are using return false without any condition.
return false;
is to prevent default form action. that is why form is not being submitted.
There are three problems I see with this code and two of them have been brought up now:
Inside your submit function, the first line will clear the input text field, so even if it submits, it won't submit anything.
The second thing is that #twitt-form is the form itself, so it doesn't have a selected attribute.
The form submit will be cancelled by the use of return false;.
Now if you were trying to prevent the page from going anywhere by submitting the form by AJAX, this is an example of what you can do:
$('#twitt-form').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(dataFromTheServer) {
// do whatever
}
});
$('#twitt-text').val('');
e.preventDefault();
return false;
});
But other than that I'm not sure what you're trying to do here.
Well im new to jquery and ajax and the code below doesnt work after 2nd attemp of submit form... heres the javascript code:
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#myForm2').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
$('#me').submit(function() {
$("#div2").load("main.php");
return false;
});
});
function showRequest(formData, jqForm, options) {
return true;
}
function showResponse(responseText, statusText, xhr, $form) {}
by the way im using jquery form plugin.....
and for the index.php
<form id="me" action="" method="post">
Message: <input type="text" name="mess">
<input type="submit" value="submit">
lastly for the main.php
<form id="myForm2" action="index.php" method="post"><div>
Name:</td><td><input name="Name" type="text" />
<input type="reset" name="resetButton " value="Reset" />
<input type="submit" name="submitButton" value="Submit1" />
</div></form>
<h1>Output Div (#output2):</h1>
<div id="output2">AJAX response will replace this content.</div>
</div>
You downloading your form after page load ( *$("#div2").load("main.php")) and your events are already binded. So when your second form loaded, it's Submit button click event doesn't triger nothing. You have to read about .live() in jQuery here
Here is my solution (that is just simpl example):
$('#myForm2').live("click",function() {
$(this).ajaxSubmit(options);
return false;
});
Maybe this will work for you.
UPD
Also you can try this:
1) replace
$('#myForm2').live("click",function() {
$(this).ajaxSubmit(options);
return false;
});
with
function MyFormSubmit(form) {
$(form).ajaxSubmit(options);
return false;
})
2) Add JS code to you myForm2 Submit button onClick event
<form id="myForm2" action="index.php" method="post"><div>
Name:</td><td><input name="Name" type="text" />
<input type="reset" name="resetButton " value="Reset" />
<input type="submit" name="submitButton" value="Submit1"
onClick="javascript:MyFormSubmit(this);return false;"/>
</div></form>
<h1>Output Div (#output2):</h1>
<div id="output2">AJAX response will replace this content.</div>
</div>
You have to remove action="index.php" method="post" from your form. Then should it work.
because now it is still making the php post to index.php