jquery $.post explain - javascript

I wrote the following code to post data with jQuery, It's working fine, but without return false;, the code didn't work, I found this return statement after 1 full day of searching...
Could somebody please tell me, what is the use of return false; after the end of $.post?
I am a newbie in jQuery and would like to get a better understanding of this.
$("#formid").submit( function () {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#result").html(data);
$("#result").fadeIn('slow');
}
);
return false;
});

The return false; here is not used for $.post method of AJAX instead it is used to prevent the form(#formid) submission which can cancel your AJAX request

If you remove the return false;, you will see that the browser continues to submit the form (not using AJAX). Returning false will prevent the browser from doing the default action, resulting in only the AJAX call occurring.
A similar result can be gotten by calling preventDefault() on the event object passed into the submit event.
For example:
$("#formid").submit( function (event) {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#result").html(data);
$("#result").fadeIn('slow');
}
);
event.preventDefault();
});

Return false stops the default form action from being executed whenever a user clicks the submit button. Only the jQuery part is executed. Else, the whole page would have been reloaded upon form submission.
You can read about that on the.submit() page on jQuery API.
There's the following paragraph:
when the form is submitted, the message is alerted. This happens prior
to the actual submission, so we can cancel the submit action by
calling .preventDefault() on the event object or by returning false
from our handler. We can trigger the event manually when another
element is clicked:

The return false is actually preventing the default action that is form submit. If you don't write that statement, your form is getting submitted.

Related

get respond after submit with jQuery and do something

i have an event that submits automatically,
i already put url and method: POST on <form> tag, so i just called $('#myform').submit()
and after that submit, it will redirect to another page for that respond,
what I asked here, i want to do something after it submitted successfully, I was using setTimeout but we don't know when the page redirect, right? it because of the internet connection as well, so how do u handle this ??
$('#myform').submit() will auto submit the form.
What you need to do is :-
$('#myform').submit(function() {
// DO STUFF HERE...
return true; // return false to cancel form submission
});
Now perform the action and return true.

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.

What does "return false;" do?

I wrote a webpage where a user can enter a log entry that is stored on a database and then retrieved and printed on the page using ajax. I am still quite new to ajax and was wondering if somebody could please explain to me what does return false; do at the end of my code? and is it even necessary?
If I put the second ajax code after the return false the code does not work! can you please explain to me why?
//handles submitting the form without reloading page
$('#FormSubmit').submit(function(e) {
//stores the input of today's data
var log_entry = $("#LogEntry").val();
// prevent the form from submitting normally
e.preventDefault();
$.ajax({
type: 'POST',
url: 'behind_curtains.php',
data: {
logentry: log_entry
},
success: function() {
alert(log_entry);
//clears textbox after submission
$('#LogEntry').val("");
//presents successs text and then fades it out
$("#entered-log-success").html("Your Entry has been entered.");
$("#entered-log-success").show().fadeOut(3000);
}
});
//prints new log entries on page upon submittion
$.ajax({
type: 'POST',
url: '/wp-content/themes/childOfFanwood/traininglog_behind_curtains.php',
data: {
log_entries_loop: "true"
},
success: function(data) {
alert(data);
$("#log-entry-container").html("");
$("#log-entry-container").html(data);
}
});
return false;
});
​
What I'll write here is true for jQuery events,
For vanilla javascript events read #T.J. Crowder comment at the bottom of the answer
return false inside a callback prevents the default behaviour. For example, in a submit event, it doesn't submit the form.
return false also stops bubbling, so the parents of the element won't know the event occurred.
return false is equivalent to event.preventDefault() + event.stopPropagation()
And of course, all code that exists after the return xxx line won't be executed. (as with all programming languages I know)
Maybe you find this helpful:
Stop event bubbling - increases performance?
A "real" demo to explain the difference between return false and event.preventDefault():
Markup:
<div id="theDiv">
<form id="theForm" >
<input type="submit" value="submit"/>
</form>
</div>​
JavaScript:
$('#theDiv').submit(function() {
alert('DIV!');
});
$('#theForm').submit(function(e) {
alert('FORM!');
e.preventDefault();
});​
Now... when the user submit the form, the first handler is the form submit, which preventDefault() -> the form won't be submitted, but the event bubbles to the div, triggering it's submit handler.
Live DEMO
Now, if the form submit's handler would cancel the bubbling with return false:
$('#theDiv').submit(function() {
alert('DIV!');
});
$('#theForm').submit(function(event) {
alert('FORM!');
return false;
// Or:
event.preventDefault();
event.stopPropagation();
});​
The div wouldn't even know there was a form submission.
Live DEMO
What does return false do in vanilla javascript events
return false from a DOM2 handler (addEventListener) does nothing at all (neither prevents the default nor stops bubbling; from a Microsoft DOM2-ish handler (attachEvent), it prevents the default but not bubbling; from a DOM0 handler (onclick="return ..."), it prevents the default (provided you include the return in the attribute) but not bubbling; from a jQuery event handler, it does both, because that's a jQuery thing. Details and live tests here – T.J. Crowder
Any code after return statement in a function will never be executed. It stops executing of function and make this function return value passed (false in this case). Your function is "submit" event callback. If this callback returns false, form will not be submitted actually. Otherwise, it will be submitted as it would do without JavaScript.
In this instance, return false; prevents the default action (which is the form submitting).
Although it's probably better to use e.preventDefault();
because of ajax you do not want your form to be submitted with the normal way. So you have to return false in order to prevent the default behavior of the form.
The return statement ends function execution
This is important. Using return causes your code to short-circuit and stop executing immediately, preventing the next line of code from executing

Categories