jQuery click event first then follow url - javascript

I want to call a click event and then follow the href url.
HTML Link:
<a class="autoSave" href="?year=2013&week=42">←</a>
JS:
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('.submitForm').click(); //HTML Form that I'm wanting a submit to happen
window.location = $(this).attr('href');
});
});
The code above will just follow the url and not submit the form. If I omit the window.location call, the submit works.

You don't wait for the .click() event to be fully handled to call window.location.
You should serialize your form, post it by ajax (with .post() for instance), and then, in the callback of the .post(), change your page :
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
var serializedData = $('#yourForm').serialize(); //For example
$.post('your/path/to/form/validator', serializedData, function(){
window.location = $(this).attr('href');
});
});
});

You can't do a form submit without the browser trying to follow the form action. You need to use ajax to post your autosave data to your submit form and then do the window redirect when the ajax return successfully.
$('.autoSave').click(function(event){
event.preventDefault();
$.ajax({
url: "whatever your submitForm.click() file is",
type: "POST",
data: {
formField: theValue
anotherFormField: theValue,
},
success: function( data ) {
window.location = $(this).attr('href');
}
});
}

The problem is that the browser doesn't wait until the for m submission is done before it unloads the page and follows the link.
I'd recommend moving the location redirection to the end of your form submission:
$('.autoSave').on('click', function(event){
event.preventDefault();
$('.submitForm').triggerHandler('submit', [$(this).attr('href')]);
});
$('.submitForm').on('submit', function(event, url) {
// Do the thing
window.location = url;
})

Give your form an id and use the submit() function to submit it. Use a jQuery selector on the ID instead of a class, especially if you recycle the class you gave it.
HTML
<form id="submitForm">...</form>
Javascript
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('#submitForm').submit();
window.location = $(this).attr('href');
});
});

If your form is a standard form, the easiest thing to do is set a hidden input field value to the followup url:
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('#redirectUrl').val($(this).attr('href'));
$('.submitForm').click(); //HTML Form that I'm wanting a submit to happen
});
});
In this scenario, you will have to have full control of the server side and you will be able to test for that value and do a 301.
This is far from ideal. There are a lot of options, but almost all of them are hackish in order to double-post from a single event.

Related

Why won't this form submit with AJAX?

I'm trying to submit a form to Campaign Monitor. They offer this code example to POST via Ajax.
This is my code for my multi-step modal.
var next_step = false;
var final_step = false;
$('.next').on('click', function(e){
e.preventDefault();
if (next_step) {
$('#step-1').slideUp(function(){
$('#step-2').slideDown();
$('.next').html('Submit');// Change button text to submit
final_step = true;
});
}
next_step = true;
if (final_step) {
$('#myform').submit(function (e){
alert('submit started'); //This never fires unless I remove the preventDefault();
e.preventDefault();//But if I remove this, the page will refresh
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert('error');
} else {
alert('success');
}
})
});
}
});
On the last step of the form, I check whether final_step is true, if so, go ahead and submit the form via ajax.
The problem is that it just doesn't do anything? But if I remove the e.preventDefault(); from the $('#myform') it will post the form as normal and re-direct you to the form URL.
How can I fix this?
What you are doing currently is wiring up an onsubmit handler. Not invoking submit.
$('#myform').submit(function (e){ });
...is the same thing as...
<form action="#" method="post" onsubmit="return someFunction()">
... which is the same as ...
$('#myForm').on('submit', function(e){});
You are never submitting the form.
What you are looking for is to use Ajax to post the data to the server and not submit the form.
You can do that like this:
$.ajax({
type: "POST",
url: "SomeUrl.aspx",
data: dataString,
success: function() {
//display message back to user here
}
});
dataString would be replaced with the values you posting.
$('#myform').submit(function (e){
just registers an event handler and attaches it to the "submit" event of "myform", it doesn't actually cause a submit. It means you're saying you'd like this function to be run every time the form is submitted. This handler function should be outside your $('.next').on('click', function(e){ block. Just below it will do.
If, within the $('.next').on('click', function(e){ block you wish to cause the form to be submitted, write:
$('#myform').submit();
This will actually trigger the form submission.
See https://api.jquery.com/submit/ for more info on what the different method signatures of "submit" actually do.
This line: $('#myform').submit(function (e) { registers the function you pass as an argument as a handler to the submit event of the form, and does not invoke a submit action. I'm not sure whether or not this is the problem, though I would recommend preventDefault() outside of the wizard flow
(e.g.
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
}
});
)
Then inside the if(final_step) just do the post without worrying about the form.
Also, you'd do good in not setting a submit button inside the form if you do not wish to use it's functionality. Just create an element with a click event that sends the data rather than registering to the submit event of the form.
I'm not sure but I always do $('#form').submit() after click in element and catch this event (e.g. by $('#form').on('submit', function () { .. });) in other place.

I have successfully loaded a form into a <div> element using jQuery $.Ajax. I need to know how to submit that form using jQuery Ajax

I have used .on() of jQuery for event delegation and to set up a 'submit' event handler for the dynamically the loaded form e.g.
<script>
$(document).on('submit','#my_form_id',function(e){
e.preventDefault();
e.stopPropagation();
$.ajax({
url:$this.href,
type:"POST",
data: $('#my_form_id').serialize(),
dataType: "html"
}).done(function(update_result){
$('#id_of_div_that_will_hold_the result').html(update_result);
});
return false;
});
</script>
But it is not working as the form gets submitted directly not asynchronously.
Also where should the above script be put in the main page or in the page that contains the HTML code for dynamically loaded form? I ask this as it seems the script is not being called
Any general short example will help and be highly appreciated. I cannot provide the code here as it is too long in MVC architecture using codeigniter.
You can do something like this to POST the form:
$("#my_form_id").submit(function (e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function (data) {
// put any code handling return values here
});
});
The $.submit works the same as $.on('submit') but easier to read and type. The $(this).serialize() function will convert all the form data into a string to be submitted to the server.
You should stop the default event handler (submit) from firing.
$(document).on('submit', '#my_form_id', function(e){
e.preventDefault();
ajax form submision code goes here....
});

using ajax to display a different php page

<script>
//jQuery('#frmSearch').click(function() {
jQuery(function(){
jQuery('#frmSearch').on('click', function(e){
e.preventDefault();
jQuery.ajax({
type: 'POST',
url: 'mutualfundsprices/do_price_archive.php',
data: jQuery('#frmSearch').serialize(),
success: function(data) {
jQuery('#DisplayResult').html(data);
}
});
return false;
});
});
</script>
the above is my JavaScript to display a different PHP page but after loading the result, the result disappears.
What is wrong with my code?
I guess #frmSearch is a form on your DOM, right?
My guess is that the form is being submitted twice, once using your onclick function (ajax), and then the second may reload the page so that your AJAX-loaded HTML disappears. But I may be out of line here.
You are assigning an onclick, which is quite uncommon for forms. But still, e.preventDefault and return false; on an onclick event won't prevent the form to submitting if you ever click on the submit button. You might want to use the onsubmit event of the form instead, or, better yet, avoid having a submit button but rather have a normal button if you want to handle form submissions always using AJAX in your callback function.

.submit doesn't work if the bind object was refreshed by ajax

I AJAXified commenting system so when Post Comment button is clicked ajax call is made instead of the original form submission. It works fine till I refresh the page with the comment submit button by ajax. Let's say that I only refresh the div that contains the post and comments and the button. After that the ajax is not triggered rather the original way of submitting is used.
The javascript to submit the form looks like
jQuery('document').ready(function($){
var commentform=$('#commentform'); // find the comment form
commentform.submit(function(){
// $('#commentform').submit(function(){
I tried to use $('#commentform') instead of the variable which didn't help.
I tried to assign the commentform variable again after the successful ajax that loads new post. That didn't help either.
Part of the javascript that loads post via ajax
var $ = jQuery.noConflict();
$(document).ready(function() {
$(".mhomepage_item").bind("click", function(){ //bind a click event on a class with name = mhomepage_item
$.ajax({
type: "POST",
url: mhomepage.ajax_url,
data: {
action: "get_post",
type: $(this).attr('type'),
current_post_id: $('#post_container').attr('current_post_id')
},
success: function(response) {
response_from_json = JSON.parse(response);
$('#content_container').html(response_from_json['html']);
commentform=$('#commentform');
}
});
// }
});
Could someone suggest how to make the bind to form submit button permanent even after the button is reloaded via ajax?
Try event delegate:
$(document).on("submit","#commentform",function(){
// action to perform after submit intent
});
By using delegated event handler, you can handle dynamically created elements easily without having to do something like rebinding event handler.
You could also bind the event to the body or the closest container that's available when you call the function to avoid bubbling more levels to document. You could also try this in your case:
jQuery(document).ready(function($){
$('#content_container').on("submit","#commentform",function(){
// action to perform after submit intent
});
});
Documentation
Accordingly with: jQuery binding click to a link after AJAX call
You must bind a button to click/submit event in success callback.
you can to do:
success: function(response) {
response_from_json = JSON.parse(response);
$('#content_container').html(response_from_json['html']);
commentform=$('#commentform');
$('#commentform').bind("submit", function() { ... } );
}

Why does the html disappear?

I would like to insert <div><p>Test</p></div> in another DIV at the top. So I try
$(document).ready(function(){
$('form').live('submit', function(){
var aform = $(this);
$('#w').append('<div><p>Test</p></div>');
});
});
HTML looks like
<div id="w">
<div><p>Test</p></div>
</div>
When I do that, it gets inserted, but goes away right after.
Try click on the Save button in this example.
http://jsfiddle.net/Rv2w7/
Use prepend() and cancel the submit:
$(document).ready(function(){
$('form').live('submit', function(){
var aform = $(this);
$('#w').prepend('<div><p>Test</p></div>');
return false; //cancel `real` submit
});
});
The page gets reloaded on submit. That's why the dynamically inserted tag disappears.
You need to cancel the default action to prevent the form from submitting:
$(document).ready(function() {
$('form').live('submit', function() {
var aform = $(this);
$('#w').append('<div><p>Test</p></div>');
return false;
});
});
Updated example: http://jsfiddle.net/Rv2w7/2/
return false; or event.preventDefault() is required to prevent the default action with live().
Because your form gets submitted each time, you need to prevent the default action:
$(document).ready(function(){
$('form').live('submit', function(event){
var aform = $(this);
$('#w').append('<div><p>Test</p></div>');
event.preventDefault();
});
});
After you click the save button the page submits, that's why its 'going away'. That happens because modifications on the current HTML only last until the page changes or refreshes, because a new GET will be issued to the server and the unchanged version of the HTML will be retrieved, overwriting your changes.
To save something permanently to your HTML you will need to use a server-side programming language; make your program retrieve previously saved strings to a cookie or session; make your program load data from a database, etc.

Categories