Executing a script after a form has been submitted - javascript

I found, on this site a way to submit a POST form without leaving the page. In that script, they put instructions on how to have a function take place after the form's been submitted. Here's what the script looked like:
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
},'json');
return false;
});
});​
They said, between function(response){ and },'json'); you can specify other JavaScript to take place like alerts etc. after the form's been submitted. I tried
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
$('form').hide();
},'json');
return false;
});
});
Unfortunately, that does not work, can anybody tell me why? I've set up a jsFiddle. Please help. Thanks.

Using $.post, the "function(response)" is only called AFTER a successful result, so you have been misinformed about doing work within this function while the server is processing the request.
To continue processing after sending the request to the server, place the $('form').hide() after the $.post call:
$form.submit(function(){
$.post(
$(this).attr('action'), $(this).serialize(),
function(response){
}
,'json'
);
$('form').hide();
return false;
});

Problems:
Set JavaScript variable as form, not $form. Then use it in jQuery as $(form).
The context of $(this).attr('action') is the $.post() callback, not the form. Solution: $(form) instead of $(this).
Solution:
$(document).ready(function(){
form = $('form');
$(form).on('submit', function() {
$.post($(form).attr('action'), $(this).serialize(), function(response) {
$('form').hide();
},'json');
return false;
});
});

Your fiddle worked fine when the form is changed to
<form action="#" method="post">
And the documentation at http://api.jquery.com/jQuery.post/ shows that this is a valid syntax and http://www.johnnycode.com/blog/2010/04/08/jquery-form-serialize-doesnt-post-submit-and-button-values-duh/ is also a running sample. If it's not working at all for you then, as silly as this is, do you have a reference to jQuery in your page?

Related

How to submit a form on page reload with GET request?

I want submit a form with GET request on page reload. How can I achiev this with Javascript/JQuery or without Javascript/JQuery in ASP.NET Core MVC web app. Thanks.
here is the code
this will submit on reload
$(window).on('beforeunload', function(){
$("form").submit();
});
or you can use URL to pass GET value
$(window).on('beforeunload', function(){
var v= $("input").val();
$(location).attr('href', 'http://example.com/index.php?value='+val);
// or window.location.href='http://example.com/index.php?value='+val;
});
you can use ajax if above method doesn't work
$(window).unload(function(){
$.ajax({
type: 'GET',
url: 'script.php',
async:false,
data: {value:"username"}
});
});
if async is set to false browser waits for request to complete else it will not.
that is why above first two method may not work.

Ajax success not working for me

follow code is supposed to show alert msg. It is doing nothing. Can anyone tell me where I am wrong. Everything is working nicely execpt alert().
<script>
$(document).ready(function(){
var baseUrl = document.location.origin;
$(".ProductRemove").click(function(){
var row_id = $(this).attr('id');
$.ajax({
type:"POST",
cache:false,
url:baseUrl+"/shop/api/cart",
data:"row_id="+row_id+"&action=remove", // multiple data sent using ajax
success: function () {
alert('success');
},
error: function(){
alert('failure');
}
});
});
});
Thanks to all,
I got the solution. It is calling error function instead of success because I am returning in nothing from the server.
In ajax empty is not considered as JSON data. So to fix that I have to echo "json_encode(NULL);" in my server.

Form not submitting with AJAX

=====UPDATE AGAIN==== (if anyone cares!)
the solution I posted before stopped working for whatever reason. I included a beforeSend in my ajax request and pasted the portion of my js that validates my form into it. Works like a charm now!
$('#form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh
$.ajax({
type: "post",
beforeSend: function(){ // check that form is complete
},
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you'); hide_request();window.location = "#top";
}
});
});
EDIT
See my answer below, using 2 .preventDefault!
I have read through many pages / examples of this, but for some reason I can't get it to work on "my" form.
I'm simply trying to submit my form without refreshing the page or opening a new page / tab for the confirmation message.
The form:
<form id="form" name="Configurator" method="post" action="">
.... //Client configures his product, display an image if they choose, and request a quote.
<button id="submit_button" type="submit" name="Submit" >Request</button>
</form>
The client_config_send2.php works, it simply pulls a bunch of parameters from the form (configuration, contact info) and puts it into an email. This part works fine before I try to integrate the ajax.
The JS:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
The validateForm() function also works, it checks if the configuration is valid, if the email / contact info is complete, etc.
At this point, the validateForm works: if info is missing, the alert pops up. However when validateForm() returns true, the form doesn't submit, nothing happens.
I have tried success instead of done, return false instead of true in the JS, and many other things I found online but I am lost. Never used AJAX before so I'm not 100% confident with the subtleties of the language!
Thanks in advance!
"client_config_send2.php" is a filename. The URL you give to Ajax needs to be, well, a URL like http://example.com/client_config_send2.php.
Change done to success:
success: function(data){
success only fires after your request got response and the response code is OK(http 200).
Update the code below:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
var formdata = $(this).serialize();
$.ajax({
type: "post",
url: "http://www.example.com/client_config_send2.php",
data: formdata,
success: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
Could you try removing/commenting event.preventDefault();
If this method is called, the default action of the event will not be triggered. (http://api.jquery.com/event.preventdefault/)
Try coding in the following format. The logic uses an if/else statement to make the ajax call.
$('form').on('submit', function(e) {
//If form could not be validated
if(!validateForm(this)){
//prevent the form form submitting
alert("Your form is not valid for submission!");
e.preventDefault();
}
//else
else{
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
}
});
});
Here is the final code that does exactly what I want:
- the validateForm() function works as it should. If the form is not complete, it returns false, an alert pops up and the form does not submit
- if validateForm() returns true, the form gets submitted, the confirmation alert pops up and the page does NOT refresh. Users can then build a new configuration and submit a new request without re-entering all the contact info.
The 2 .preventDefault did the trick!
$('form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh when form is submitted
//If form could not be validated
var x = validateForm();
if(x == false){
//prevent the form form submitting
e.preventDefault();
}
//else
else {
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you! we will get back to you within 24 hours. Please check your junk / spam folder if you do not receive a response within that time.');
}
});
}
});
Thanks everyone for your help!

Ajax with Jquery - Callback not executing

I have tried so many things, cannot figure this out, I am using this code, and I know that the start is working, because the script it connects to sticks some info in the db, but the callback never runs.
<script type="text/javascript">
$(document).ready(function() {
$(document.body).on('click', "#reply_submit", function() {
var formData = $('#reply').serialize();
$.post("newpost.php",formData, function(data){
alert("hi");
}, "json");
});
});
My form's id is "reply" and the button I am using to submit it is "reply-submit", just to make sure those things are clear.
It also doesn't work if I remove that last "json" thing btw.
If you read the docs for jQuery.post(), it says this about the callback:
success(data, textStatus, jqXHR)
A callback function that is executed if the request succeeds.
If it's not getting called, it means that request did not succeed. There is probably an error in newpost.php (sometime after the data insert, but before it would normally exit).
You can also catch error conditions by using the long-form jQuery.ajax() instead of the post shorthand:
$.ajax({
url: 'newpost.php',
data: formData,
type: 'post',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error!');
}
});
When you click, the form is also being submitted the standard way. Modify your click handler like this:
$(document).on('click', "#reply_submit", function(e) {
e.preventDefault(); // prevent the default submit event
var formData = $('#reply').serialize();
// ...
});
Although I think document.body should be a valid node to wrap in jQuery, I've also modified it to the more commonly used document.
On that note, if the form is never destroyed by an Ajax event or other DOM modification, you could bind to #reply instead of document (or body).
I'm simply assuming that you want to submit a form without reloading the whole page.
Based on that assumption, following code will serve the purpose.
$(document).ready(function(){
//on form submit event
$('form#reply').submit(function(){
$.post('newpost.php',$(this).serialize(),function(){
alert("Message or do something with the response data if you are expecting one");
});
//prevent default action
return false;
});
});
Please ignore the post if this is not the functionality you are looking for in your project.

Jquery form ajax call trouble

I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?

Categories