I am currently trying to run an action in my grails controller upon a page load in my application that will start a thread an continue with a task. I still have yet been able to successfully implement this in. This is my code:
$(document).ready(function(){
var $form = $("#background_thread");
$form.submit(function(e){
e.preventDefault();
$.post($(this).attr("background"), $(this).serialize(), function(data){
alert("should work" + data)
});
return false;
});
});
I cannot for the life of me figure out why it's not working. Is there some simple syntax I'm overlooking or a different way I should be doing this?
Update:
My form id is #background_thread and I am trying to do it asynchronously so that the page will still stay the same and my action will be run.
My script is run but fails on $form.submit(function(e){ and will not pass through.
You need to prevent the default behaviour on the event that has been generated.
$form.submit(function(e){
e.preventDefault();
// your code
}
Update:
You will certainly need to add the above regardless, once you get the overall script working. Also, please add your markup to the question. A few basic questions to make sure:
Is #background_thread the id of your form?
In your network tab in Chrome Inspector (or similar) is the request being fired off?
Is the markup being delivered asynchronously, as if it is, you will need to use .on to attach the event permanently, rather than just a basic selector?
Update 2:
Your form is being delivered asynchronously itself, therefore your event attaqchement must change to:
$(document).ready(function(){
$("body").on("submit", "#background_thread", function(e){
e.preventDefault();
$.post($(this).attr("background"), $(this).serialize(), function(data){
alert("should work" + data)
});
return false;
});
});
So, to explain, your event attachment was happening during document ready. Document ready fires, but the form hasn't been delivered to the DOM yet, so it doesn't have an attachment to it. Therefore, you use on() to permanently attach that event to that element for the lifetime of the entire page's rendering to the browser.
N.B. I attached it to body, to begin listening for submit at that point, in practice you would not do this for many reasons, you would attach it to the outermost point of AJAX replacement for the form, essentially, the nearest parent to the form that will be known on initial page load.
I hope that this has been of some use and good luck with your application.
Related
I am using following code on my page which I am loading in ajax.
$(document).ready(function() {
$('#button_id').click(function() {
//Do Something
});
});
Now When I click on the button action happens multiple times. I know that its happening because I am loading the ajax page multiple times.
Please help me solve this.
You can use .off() to remove existing listeners:
$(function() {
$('#button_id').off('click').click(function() {
//Do Something
});
});
If I am wrong about your implementation I apologize. Your problem may exist because the binding is created on first page load and then on subsequent ajax loads with new scripts being inserted and creating duplicate bindings. You should prevent any bindings from being generated on ajax loads to prevent duplicate bindings unless you are good with cleanup.
If the button you are clicking on exists in the ajax loaded area then you should use delegation to ensure that the click handlers still work.
For example:
$( "body" ).on( "click", "#button_id", function() {
//do something
});
This will add a binding to the body element, but more specifically to the id #button_id. A click event on the button will propagate and bubble up to the body element (or whatever parent element you choose).
This makes it so that dynamic elements can be inserted in the DOM and only one event handler is needed to listen for it.
No need for .on() or .off() calls for individual ajax loads. This allows your bindings to be much cleaner.
Of course, if your button is not likely to exist on the page all the time then it would not be a good idea to keep extra bindings. Only create these types of binding if they are always needed to prevent optimization issues.
A cleaner solution would be to remove that code from the ajax loaded HTML and use one single event handler in the master page
I guess your problem is the event is firing many times.
To fire only once try this:
$(document).ready(function() {
$('#button_id').on("click",function(e) {
e.preventDefault(); // This prevents the default non-js action (very used for anchors without links or hashes)
e.stopPropagation(); // Prevent the bubling of the event and spread more times
//Do Something
});
});
If doesn't work with e.stopPropagation(); try with e.stopInmediatePropagation();
Adding documentation for the last method I suggested. It could solve your problem.
http://api.jquery.com/event.stopimmediatepropagation/
I'm using jQuery for a small project I have and it's one of my first times using it. Is it safe to put all my UI code in $(document).ready() ? I'm basically creating a form that pops up when a button is pressed, and the form is processed via AJAX. Basically, when I separate my AJAX function from the functions controlling the UI, the AJAX doesn't work. However, when I put both of them in $(document).ready(), everything works fine. Here's my code. Please ignore my comments, as they were for learning purposes.
$(document).ready(function(){ //ready for DOM manipulation
/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');
/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object
var that = $(this), //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
var that=$(this), //legal attribute
name=that.attr('name'); //name of the legal attribute
value=that.val(); //value of text field in legal attribute
data[name]=value; //data object is filled with text inputs
});
$.ajax({
url: url, //url of form
type: type, //type of form
data: data, //data object generated in previous
success: function(response){ //reponse handler for php
if(!response){
console.log("Error");
}
console.log(response);
}
});
return false; //Stops submission from going to external php page.
});
});
});
Generally any selectors such as $('form.ajax')., $('#container_form'), $('.addButton') needs to be in doc.ready to ensure that the DOM is ready before you try to select an element from it, since it may not find the element if the DOM hasn't finished processing. So that pretty much applies to all of your code. If you had a function such as this:
//defines a function
function addThem(first,second)
{
return first + second;
}
You could declare it outside of doc ready, and call it from within doc ready.
$(document).ready(function(){
$('#someInput').val(
addThem( $('#anotherInput').val() , $('#thirdInput').val() )
);
});
The way I think about this, is doc ready is an event, so you should be doing things in response to the "document is now ready for your to query event", not declaring things. Declaring function just says what that function does, but doesn't actually do anything, so it can go outside of the document ready. It'd be pretty silly to declare this function inside of doc.ready since it can be defined at anytime (although it certainly is possible to put it inside doc ready, it just generally clutters things up). Even if it were selecting an element, that code isn't actually running until it is called:
function hideContainer()
{
//this code never runs until the function is called
//we're just defining a function that says what will happen when it is called
return $('#container').hide();
}
$(document).ready(function(){
//here we are calling the function after the doc.ready, so the selector should run fine
hideContainer();
});
Note that the act of wiring up to other events is an action in itself, such as when you subscribed to the click events and form submit events. You are saying, "find the form element with class .ajax, and subscribe to its submit event". You wouldn't want to try and wire up to events of DOM elements until the DOM is done processing. They might not "exist" yet as far as the browser is concerned if it is in the middle of processing the DOM, and thus your attempt to wire up to the click/form submit events may fail. I say may because depending on timing/processing lag it may sometimes work and sometimes not.
There's not only nothing wrong with putting all your code into one $(document).ready(), but there's nothing wrong with putting it into multiple $(document).ready() functions either so that you can separate repeated functionality into individual JS files.
For example, I use $(document).ready() in a script included on all my site's webpages to set up UI elements, prevent clickjacking, etc. At the same time, each page regularly has its own $(document).ready() which sets up page specific user interactions.
It is absolutely OK. If you find yourself needing to abstract your code into multiple function or multiple files, then by all means, but there's nothing wrong with throwing everything in $(document).ready().
I am trying to call google analytics event tracking method before submitting a form on this page
This is the code that I have now:
$(function() {
$('#findbooking input').each(function(){
$(this).blur(function() {
if (!$(this).val()) {
_gaq.push(['_trackEvent', 'Rebooking', 'completed', $(this).parent().parent().text()]);
dcsMultiTrack('WT.ac', 'See_and_Change_my_booking_completed');
} else {
_gaq.push(['_trackEvent', 'Rebooking', 'skipped', $(this).parent().parent().text()]);
}
});
});
});
The problem is that the dcsMultiTrack request is fired twice when the user blur from each input field. It is supposed to only send the request once.
Note: We don't have access/modify the source code and the code will be placed on the same page as a workaround. Any help is highly appropriated
You could use submit handler to track the form submission event. The callback is invoked prior to the actual form submission, so you can place your tracking logic there. This approach guarantees that the tracking events are fired only once, not every time a user moves focus from one form field to another.
If I undestood your note correctly, the function you gave is an external script you don't have access to, and you are going to override it placing script directly on the page. In this case you need to remove the handlers previously attached to blur events. $('#findbooking input').unbind('blur'); will do the trick.
Tried to bind submit event (or click or whatever) to an element within a jQuery mobile page. What I wanted to do is get the value from an input within an form element within a jQuery page and store it in cookies/localStorage. Every time I come back to this page I want to restore the input field.
Currently I ended up in using this script:
$('.pageClassSelector').live('pageinit', function (e) {
$('.classSelector').submit(function () {
var q = $('.inputClassSelector').val();
// store to localStorage ...
});
// load from localStorage ...
$('.q').val(lastSearchString);
});
This approach is documented there http://jquerymobile.com/test/docs/api/events.html
Since it seems possible that identical pages are hold in the DOM, ID selectors are not quite useful. My problem now is that everytime I navigate to this page the submit event is bound again and thus results in storing DIFFERENT (!) values. The submit event seems to be fired multiple times and much more interesting with the value before last.
Am I doing anything completly wrong? Any hints how to do scripting in jquery mobile properly?
TRY1:
I placed now the submit event binding within the pagebeforeshow event like so:
$('#PageId').on('pagebeforeshow', function (e) {
$('.classSelector').on('submit', function () {
var q = $('.q').val();
alert('stored: ' + q);
}
$('.q').val(lastSearchString);
}
But the value going to be stored is still the value before last, when I was navigating the page before. The first time it works as it should.
TRY2:
This is what I have now and it looks like it does that what I want. I select now the current page and select only the form which is a child of this page.
Is this good practice?
$('div:jqmData(id="PageId")').on('pagebeforeshow', function (e) {
$(this).find('#form').on('submit', function () {
var q = $(this).find('#input').val();
localStorage.setItem("key", q);
return true;
});
lastSearchString = localStorage.getItem("key");
$(this).find('#input').val(lastSearchString);
});
Your requirement to load from local storage and store on the page needs to be done by binding to the pagebeforeshow event (look at the section "Page transition events") and not the pageinit event like you are currently doing.
$('.pageClassSelector').on('pagebeforeshow', function (e) {
// load from localStorage ...
$('.q').val(lastSearchString);
});
Furthermore generally each page element (where you have data-role='page') should have a unique ID so you can use that instead of the CSS selector.
Multiple events firing when navigating pages sounds like multiple bindings to me, which is a known problem with jQuery Mobile. Bindings are not unbound when navigating pages, because everything is loaded through AJAX. See for example this StackOverflow Question: Jquery mobile .click firing multiple times on new page visit or my solution.
$('.classSelector').on('submit', function(){})
Try to use the constraction to bind your event to element.
Look likes some data was loaded through ajax request
I have an ASP.NET Web Form application developed by another developer.
This developer made extensive use of ASP.NET controls therefore there are many automatically generated Javascript functions wired to HTML elements' event.
Now I have been asked to add a functionality: disable the submit button upon first stroke, in order to avoid the users to click several times on the button.
Here is the jQuery code that I use http://jsfiddle.net/2hgnZ/80/ and the HTML DOM is identical to the one I use:
$('#form1').submit(function(e) {
$(this).find('input[type=submit]').attr('disabled', 'disabled');
// this is to prevent the actual submit
e.preventDefault();
return false;
});
This script in my code does not work and after many attempts I am sure it depends on the JavaScript event wired to the onSubmit event of the button.
How can I postpone the execution of this Javascript on favour of the jQuery unobtrusive function?
hmm. Can you confirm that your event is firing? I cheked the submit docs, and it is bound rather than live, which is good.
How about wiring to the button, instead? It would not be perfect, because the enter key doesn't use the button, but if it works that way you'll learn something
Have you tried calling e.stopImmediatePropagation(); http://api.jquery.com/event.stopImmediatePropagation/
This piece of code delays the execution of function amount you want.
// delay code for one second
$(document).ready(function()
{
window.setTimeout(function()
{
// delayed code goes here
}, 1000);
});
This piece of code should help you get the original event and then trigger it after your desired code.
$(function(){
var $button = $('#actionButton'),
clickEvent = $button.data("events")['click'][0].handler; //saves the original click event handler
$button.unbind('click'); //and removes it from the button
//create a new click event.
$button.click(function(e){
// doWhatever we need to do
$.ajax({
url: url,
data: data,
success: function(){
$.proxy(clickEvent,$button)(e);//attach the original event to the button
}
});
});
});