How to use ajax within another ajax in jquery? - php

I made a jquery code like :
$('button').click(function(event) {
});
In it; I put $.post and sent data to a php file and return table rows. In every rows, there is an 'add' button.
Then I made another jquery code for these buttons like :
$('.row_button').click(function(event) {
});
Again, I put $.post and tried to send data about that row and wanted to fetch information via ajax request. But it didn't work. Nothing happend. I looked code and there is no error.
Isn't it possible to use ajax within another ajax? Or is there another way? Thank you.

That is because those newly injected elements don't know about the click event binding you already have.
Solution : use jquery on function.
Change
$('.row_button').click(function(event) {
});
to
$(document).on("click",".row_button'",function(event) {
});
jQuery on works for current and future elements (newly injected elements via ajax/dynamically adding new elements using javascript) . It is available from jQuery 1.7+ version. If you are using an earlier version of jQuery, consider using jquery live
(As of jQuery 1.7, the .live() method is deprecated)

Try to use this instead second code:
$('.row_button').live('click',function(event) {
...
});
Jquery .live attach an event handler for all elements which match the current selector, now and in the future.
Edit
.live is now deprected so use .on insted:
$(document).on("click",".row_button'",function(event) {
});
From Jquery documentation:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+

Related

Click event on button type input is not working

I am designing webpage using jquery and php. My page has side menu, and clicking one of the option it send a request to server to read some information from file and it will create a form out of it, with submit and other button edit(in case anybody wants to change the information in that form) and send this html back to client. I am able to do this successfully. But when I click on the edit button it actually not calling the click handler I registered for the all the buttons.
$('button').click(function(){
alert("click event");
});
I included this in the
jQuery(document).ready(function() {
But because all the jquery/js code in ready() and it gets executed at the page load time, its not able to find these buttons in form because its something which i get from server after loading and replacing it to existing 'div' and hence its not able to invoke the event handler. If I define click handler for the parent div of this form, it receives the click event if I click 'edit' button because that 'div' was present when initial page got loaded. I might not be doing it correctly, may be getting the whole form from server is not a good idea, if you have to do some operation on the form at client side. But is it doable? if yes then whats the possible way out?. Thanks!
Your event isn't firing because you define it prior to the element existing on the page. Using the .on() method should fix this. Something along the lines of:
$('body').on('click','button', function(){
alert("click event");
});
should work.
If I understand you correctly you adding the buttons dynamic to the form. You should try to use jQuery.on() insteed, see http://api.jquery.com/on/
And in your example this might work for you
$("body").on("button","click", function(event){
alert("Hello world");
});
Use on (jQuery 1.7 and up). Previously was delegate (1.4.2+), before that live...
$('*your_form*').on('click', 'button', function(){
alert("click event");
});
You may simply need to use this instead:
$(document).on('click','button',function(){
alert("click event");
});
(jQuery 1.7 or higher)
you have to call using button id
$('#buttonid').click(function(){
alert("click event");
});
or button class
$('.buttonclassname').click(function(){
alert("click event");
});

jquery append with checkbox, if checked, it wont return anything?

I have dynamically generated a list of wine types from the database using AJAx and PHP
here is the function
function wineTypeHandler(data){
var Type = data.Type;
var countType = data.countType;
for(var i = 0; i < countType; i++){
$("#selectType").append(
$("<input />").attr({
type: 'checkbox',
name: 'Type',
class: 'wineTypeCheck',
value: Type[i]
}), Type[i] + "<br />"
);
}
}
As you can see I have "appended" the results to some div with id selectType, this whole thing works fine, my only problem is when I want to update another list based on what has been checked from this list, it doesnt respond to anything!. When i try this one and many other ways
$(document).ready(function(){
$(':checkbox').click(function(){
alert('started');
// other code
return true;
});
});
It doesnt alert anything!! Can anybody help me with this problem.
thank you in advance.
.click() attaches itself to elements that exist when the DOM is created. Your elements are being dynamically generated, so .click() doesn't actually get applied to them.
You should use .live() to target dynamically generated elements, as it attaches itself to any element that is created after the DOM is initially loaded. I also suggest using the change event instead of a click:
$(':checkbox').live('change', function(){
// No need to return true;
});
This is because you are assigning the click function once your page has loaded but before your checkboxes have been dynamically created.
Depending on what version of jQuery you are using you can use the on() (for jQuery version 1.7 or above), delegate() (for older versions of jquery) or live() (simple but inefficient) functions to register an event to dynamically created elements.
Just try this
$(':checkbox').live('change', function(){
});
You need to bind the click event after the element has been added to the DOM. This is a popular problem for JavaScript development. I'd recommend creating a function that sets the bind event, and calling it after your append call (as well as on jQuery(document).ready()).
Edit: I see a lot of recommendations for jQuery.live() It's important to note that the live() method of jQuery is deprecated and should not be used.
The event is bound only to the existing elements. You need to use live
$(':checkbox').live("click", function(){
alert('started');
});
EDIT:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
jQuery 1.4.3+ use delegate
$(#selectType).delegate(':checkbox', "click", function(){
alert('started');
});
jQuery 1.7+ use on
$(#selectType).on("click", ':checkbox', function(){
alert('started');
});

jquery ui lost after jQuery load

I have a problem with jQuery being lost after .load() function.
I have a element built up with jQuery UI. The problem is that when I load it from separate page like this:
$("#mydiv").load("getgroup.php?group=" + selectedGroup).html();
The getgroup.php generates something like this, depending on the GET parameter:
<select>
<option>something</option>
<option>something</option>
</select>
When loading it with load() (or post, ajax, get) the element returns unformatted... I have tried including jquery and jquery-ui plugin also in the getgroup.php file but with no luck...
Thank you
The problem is, your jquery code isn't executed automatically on dynamically loaded elements.
What you should do is, put all your jquery ui code in a function. For instance, let's say you want to call the button() jQuery UI function on the newly loaded submit elements:
function launchUiWidgets(target) {
$(target).find('input:submit').button();
}
Then, you use this function as a success callback when you load new elements - giving it target as an argument to avoid rerunning the code on all of your DOM. Let's suppose you're loading the data in a div of id "container":
$.get(
"whatever.html?name=val",
function(data){
$('#container').html(data);
launchUiWidgets('#container');
},
"html");
If my understanding is correct and the element is being inserted, but with no CSS, you may need to run .addClass after the element is loaded to apply your chosen CSS class once the element is present. However, if in your CSS you have default values for the element type predefined, e.g. select{color:#000000;width:... these should also be loaded automatically.
Per the comment below- if you are looking at your predefined handlers still being relevant for content injected by AJAX/load() calls, you can use the .live() method:
http://api.jquery.com/live/

Jquery Event on a Ajax response

How can I run jquery function for a .click() event on a element created by an ajax request ?
For a normal element it works, but I want to do this for an element created by the ajax request. And it's not working ...
$(".links").click(function(){alert("aaaa");})
a class="links" >1</a;
I've also tried with "links" as id.
I need it for a pagination system.
Please help :(
You need to run the code again to bind the click event handler, after the new element is inserted into the DOM. Alternatively, you may want to use .live().
use jquery live
use jquery live,
$(".links").live('click', function(){
//user code here
});
to deal with dynamically loaded doms, you should use live function.
jquery do not load page doms automatically after page loaded.
You should use live() like this:
$(".links").live('click', function(){alert("aaaa");})
This also works with elements added to document
for an onclick to every <a> element you must do like this (if this is what you mean:
$("a").live('click', function(){
alert($(this).attr("id"));
})
This attaches event to all <a> elements and also to those added afterwards.
EDIT - now the alert shows the id of the link: 'this' in this case refers to the <a> that has been clicked

Using jQuery 'click' function that was loaded with Ajax content?

I have the contents of a php file loaded via Ajax that contains HTML and JavaScript. I have a button:
<button class="search_button">Search</button>
And I have a script underneath that will update the documents hash from a jQuery function
<script type="text/javascript">
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
</script>
This code works when I run the php file separately, but when loading this page from an Ajax call, the function no longer runs. In firebug the script is not present so I am assuming I cannot load a script in using this method. I tried also putting the JavaScript snippet instead a header for the whole website, but this failed also.
I was also thinking perhaps the function has to be declared when there is a search_button class already present, but it was structured in this way when I previously had them in one file (that was retrieved via Ajax) to no avail so I'm confused as to the problem.
You can include it globally with a live event:
$(".search_button").live('click', function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
jQuery will automatically evaluate script blocks, you cannot see the function in the HTML because it has been stripped out. However it should have already run. The problem is most likely timing. You could do something like
setTimeout(function(){
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
}, 500);
So that when the script is loaded it waits to be executed (hopefully giving jquery time to update the DOM with the new element).
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.
Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Example usage of .on() to bind click event
$(document).on("click", "#post a", function(){
alert("1");
})
Try to add the script inside a function
function name(){
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
}
and call this function just after the end of the ajax call.
$(document).ready(function() {
name();
});

Categories