Trouble with ajax script using onClick to submit form - javascript

I have several forms on a page that submit values from radio buttons using jquery/ajax. All works fine when a Submit button is used, but I would like to eliminate the Submit button. I tried using onClick to submit. However, trying it this way causes the forms to get submitted prior to the processing script picking them up. I would very much appreciate advice (and example if possible). Thank you, Brian
Script:
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
var formData = $(this).serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
if (data.success) {
// success.
// hide form container
$("#"+data.message).hide();
$("#"+data.message+"hr").hide();
}
// log data to the console so we can see
//console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
Form:
<method="post" action="process.php" enctype="multipart/form-data">
<input type="radio" name="answer" value="yes" onClick="onClick="this.form.submit()">

Your syntax for onclick is wrong, but putting onclick attributes on elements is an outdated way of doing things in any case.
You probably want to handle the change event rather than click, since the selection of the radiobutton happens after the click, so if you submit the form right away the radiobutton might not be selected yet (I'm not sure, I'd have to experiment, but change is probably more foolproof).
$(document).ready(function() {
$('input[type=radio]').change(function(event) {
//the rest of your code goes here
//you don't need event.preventDefault() anymore
});
});
Edit: $(this) won't refer to the form anymore of course, just replacing it with $('form') should do the trick.

Related

Ajax-loaded form always send first value entered even if reloaded

I have to admit that I don't really know how to explain this "problem" that I have nor was I able to find a good title for this thread. Anyway, I will try to be clear because I'm not sure if I could add a JSFiddle or code snippet.
Let's start with the project. I'm working on some kind of DVD Library to be used on a local network only. There's a page that allow a user to add new films to the database. To do this, I use the Allocine API (A French equivalent to IMDB) to gather films informations. The user can enter a film title (Or part of it) and perform a search. All the corresponding films from Allocine will then appear.
If the user click on one of them, a modal window opens embedding a form that will allow the user to add the needed informations before sending the form. The form is then sent using AJAX and the result appear in the same modal window.
The problem come when I want to add a second film. If I don't reload the page before trying to submit the form another time, the value from the first film will be sent instead of them from the second one and that is driving me crazy.
Here's the javascript code used to send the form.
$("body").on( "click", "#AddFilmButton", function() {
var formDatas = $('#FormAjoutFilm').serialize();
$.ajax({
url : 'Functions.php',
type : 'POST',
data : 'Action=AddFilm&' + formDatas,
cache: false,
dataType : 'html',
success : function(result, statut){
$(result).modal();
},
});
});
You may notice that I'm watching a button click event instead of a form submit event. That's because when I used the form submit event, the page was refreshed all the time, no matter if I was using preventDefault or not.
I'm starting to wonder if the sent value are not reset exactly because I have used this workaround. Could it be just that ?
What other piece of code would be useful to help you understand my problem ?
EDIT : just like #intale suggested, I have multiple form in the DOM because of this modal system. I made some progress with it. First, I can now use a proper event handler and I'm watching the form submit event as preventDefault now works.
In the success function, I have added this line : $('#FormAjoutFilm').remove();
It works almost as intended in that the datas are submitted only every other time. :p
Still, it's better than the previous behavior and I need to fix it now.
Thanks for anyone who contributed so far. If you know why I need to send the form two times to get it work, let me know. This is what I have now. :)
$("body").on( "submit", "#FormAjoutFilm", function(e) {
e.preventDefault();
var formDatas = $('#FormAjoutFilm').serialize();
alert(formDatas);
$.ajax({
url : 'Functions.php',
type : 'POST',
data : 'Action=AddFilm&' + formDatas,
cache: false,
dataType : 'html',
success : function(result, statut){
$('#FormAjoutFilm').remove();
$(result).modal();
},
});
});
Second Edit : It looks like it's finally solved after a cache clearing. Thanks for everyone who contributed. :)
Try reseting the form after the data is sent:
success : function(result, statut){
$('#FormAjoutFilm')[0].reset();
$(result).modal();
}
This will prevent your serialize function from getting the first submit data

After validating & submitting form, reset form + change some css styles

I have a simple html contact form with validation check.
I would like to have some commands executed after a successful form submission. But the way I've set this whole thing up... I can't make it work.
HTML contact form:
<form id="mycontact_form" name="form_name" method="post" onsubmit="return validateForm();" action="https://domain.tld/cgi-bin/sendformmail.pl">
validateForm.js:
function validateForm() {
//validating input fields
if (!valid){
return false;
} else {
if(condition1 == true)
{
document.form_name.submit(); return;
}
else {
// doing stuff to form content
document.form_name.submit(); return;
}
}
}
When the submit button is pressed, the form is validated and will be submitted to the perl script sendformmail.pl which return a HTML Status 204 so the user stays on this page and is not redirected (that's the only way I got this part to work).
Now what I would like to have after a successful submission is:
clear/reset the form and
some minor UI stuff: change background of 2 elements + placeholder/inner text of 2 input fields for thank you message.
But for example if I put document.form_name.reset() after the document.form_name.submit(), it's too fast. It resets the form before submissions. I also tried to call another (independent) function after the validateForm() in the onsubmit but that seems to be wrong (well, at least it's not working).
So I guess I need to put these 2 things (reset + CSS changes) in a separate function and call it after a successful form submission.
But how, where and when?
I'm very interested to learn a simple yet effective solution. (but jQuery is also available)
Thank you for your help.
If your email script is on the same domain as your contact form, try submitting it via ajax. Here's a simple jQuery example, which would be in your onsubmit handler:
if (valid) {
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
})
.done(function() { // this happens after the form submit
$("#mycontact_form")[0].reset();
});
}
return false; // don't submit the form again non-ajax!
Otherwise, if on different domains, try setting the target of your form to the id of a hidden iframe on your page. Since this is cross-domain, you have no real way of knowing the result of the form submit due to the same origin policy. You can simply hope for the best and reset the form after X number of seconds:
if (valid) {
$("#mycontact_form").submit();
// clear form 3 seconds after submit
window.setTimeout(function() {
$("#mycontact_form")[0].reset();
}, 3000);
}
Both of these approaches keep the user on the same page without a refresh.
I ended up using beforeSend with ajax instead of done. And instead of resetting the form I chose to clear the value of the input fields/textarea (there are only 3). I also included the preferred 'post-submission' style of the input fields/textarea in beforeSend to leave nothing to chance.
Anyway, thank you for helping me & pointing me in the ajax direction.
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
beforeSend : function (){
// clear value of input fields/textarea & disable them
// use placeholders for "Thank you." etc.
}
});

Set the Form action after the form has been submit jQuery

How do i "SET" the action(not changing) AFTER the form has been submit?
<form id="serialize" action="newjob.php?serialize=newjob" method="post">
<button id="jobsearch" name="jobsearch">GET FROM DB</button>
</form>
AFTER the form has been submit and showing the value i need from db, SET the new action for the form, example after submit how do i get like this one so i can add the value to db?
<form id="serialize" action="newjob.php?faulty=newjob" method="post">
<button id="jobsearch" name="jobsearch">ADD TO DB</button>
</form>
as far as i know by search on the net this jquery only CHANGING(onsubmit) and not after submit
$(function(){
$('#serialize').submit(function (event)
{
var newaction = 'newjob.php?faulty=newjob';
$(this).attr('action', newaction);
});
});
it is possible to had AFTER form has been submit then set the new form action for the same form? the only thing i need to accomplish this is because i cant have a form inside a form(nested)
You can't modify form attributes inside .submit() event handler since it has been submitted using a typical submit method.After the from has been submitted, the new document is loaded and any submit event set for the form is not catched yet.
You have two options to solve the problem.
AJAX request instead of traditional form submition (recommended);
You should handle server response (data sent back from PHP) on the original page, like so (without modifying your HTML):
$('#serialize').submit(function (event){
// prevent typical submit method:
event.preventDefault();
var that = $(this), newaction;
$.ajax({
url : that.attr('action'),
method : 'GET',
data : that.serialize(),
// dataType : set accordingly to the type of data received from PHP,
success : function(data_received_from_php){
if(that.attr('action') === 'newjob.php?faulty=newjob'){
newaction = 'newjob.php?serialize=newjob';
// do something with "data_received_from_php" for that specific "action" ...
}else{
newaction = 'newjob.php?faulty=newjob';
// do something with "data_received_from_php" for that specific "action" ...
}
// set the new action attribute:
that.attr('action', newaction);
},
error : function(){
// handle errors ...
}
});
});
Simply check whether url contains specific string, and based on that modify the action attr of the form (I'd treat it as a workaround since these days, AJAX is much more "user friendly" in submitting forms):
if (window.location.href.indexOf("?serialize=newjob") > -1) {
$('#serialize').attr('action', 'newjob.php?faulty=newjob');
}
From what i see you are using jQuery and i've done something similar before.
The trick is to change your Submit button by a regular button that trigger a function to do what you have to do and finally submit the form using .sumbit()
Something like this:
<form id='changingForm' .... >
<button onclick='changingFunction()' ...>
</form>
function changingFunction(){
var newaction = 'newjob.php?faulty=newjob#tabs-2';
$('#changingForm').attr('action', newaction);
$('#changingForm).submit();
}
This code probally won't work AS IS for your case scenario but i'm sure you can fingure the logic behind it. jQuery is too far behind me to give you an absolute answer.
Hope it helps.

form within AJAX jQuery toggle, submits at parent onClick not from submit button

Basically mysimplewebform.php form submits when the toggle is clicked, as opposed to after the form is loaded, used by user and SUBMITTED via submit button at form. Obviously I need to have form operate functionally; user fills it out, and clicks submit. I simply used AJAX to bring in the form on the template page. Now everytime toggle button is clicked 'Form is submitted with empty values' and then appears in the toggle. Making it pretty useless at this point, I have been struggling with this forever. I think this is a matter of toggling the data: below --
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(), // This was a recent suggestion
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
Branched out from: How to send external form POST data through AJAX
Ok, so you want to display an html form when a user clicks a button? In that case you can use the simplified jquery load method:
$('#yourbutton').click(function(){
$('#somediv').load('/mysimplewebform.php');
});
I know this doesnt handle your toggle requirement, but i dont think that is where you are having issues.
Now onto the php. I dont know exactly what should be in mysimplewebform so heres an example
if(isset($_POST['fname'])){
//we have a post request, lets process it
echo 'hello'.$_POST['fname'];
}?>
<form action="absolute/path/to/mysimplewebform.php" method="post" id="mysimplewebform">
<input type="text" name="fname" placeholder="Enter Name">
<input type="submit" value="submit">
</form>
Notice the action is an absolute path to the file, because a relative path will be wrong if the form is loaded into another page via ajax.
Now when this form is submitted, the browser will be redirected to mysimplewebform.php.
I expect you want to stay on the same page, in which case you could submit the form via ajax:
$('#mysimplewebform').submit(function(ev){
ev.preventDefault();//stop normal redirecting submit
$.post( $(this).attr('action'), $(this).serialize(), function(data){
$('#somediv').html(data)
});
This replaces the whole form in the dom with the output, so the hello message would be displayed.
All of the above is an attempt to help you understand where you have been going wrong in your attempts. It is not the best solution to your overall problem - i would separate the html form and processing into seperate files for a start, but it should be familiar to you.

Getting some problem with apply event to dynamic added form in Jquery

I am loading the form in dialog box via jQuery
The code is like
<form class ="form1" action="" method="post" enctype="multipart/form-data" >
...
</form>
I am using jQuery form plugin to submit form like this
$(".form1").live('submit', function(e) {
var options = {
target: '.ajaxMessage',
beforeSubmit: showRequest,
success: showResponse,
type: 'POST'
};
alert('test');
$(this).ajaxSubmit(options);
return false;
});
Now
If i load the form directly without AJAX and then i submit the form then form gets submiited successfuly without any problem. It works 10 out of 10 times
In second case I load the form dynamically. When i click on form link then i load the form dynamically in a jquery dialog box then if i click on submit form then i can see the alert but form is not submitted. But it works sometimes but sometimes not. I would say it work 2 times out of 10.
Firebug console is also not showing any error
Is there any way i can find whats problem
Firebug will usually (I actually think not at all) won't show any errors for a ajax call, instead the error will be in the ajax request(still in firebug). Click the request and then response.
My guess is that there is a problem with the params you are sending or there is something wrong with what you a returning(i.e. you return html when ajax is expecting json, this will cause success never to be fired)
Also, try to pass an error:function(jqXHR, textStatus, errorThrown){} to the ` ajaxSubmit params and see what happens.

Categories