<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.
Related
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....
});
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() { ... } );
}
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.
I did a jQuery form (form1) which bring another form(form2) in that page through ajax.
Now I want to submit the form2 data through ajax.
But whenever I click the button, it submit the whole page. I mean the whole page reloads.
$(document).ready(function() {
$("#form2").submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.loading_result').html('Loading...');
},
success: function(dd) {
$('.loading_result').html(dd);
}
});
return false;
});
});
All the JavaScript codes in the parent page. I don't have any JavaScript codes in ajax pages
//
page.php
* There is a form (form1) in this page.
* All the jQuery functions are inside the page.php
When the form1 is submitted, it brings data from page2.php // It works good.
** page2.php gives form2.
Now when i submit the from2 (which is also in page.php after the ajax request) it does not trigger the jquery function inside page.php
Instead of binding the form submit on $(document).ready, I usually just include an "onclick" event to the form's button:
<button type='submit' onclick='MyAjaxFunction();return false;'>Submit</button>
The return false; portion of the onclick will prevent the form from submitting.
This is because the form is being submitted in the traditional sense. This is the default action of the submit event. You need to suppress this:
$("#form2").submit(function(evt) {
evt.preventDefault(); //<-- prevent the event's default action
//code here...
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