I have buttons that will be created and destroyed. I have this code below. #showContainer is what is ajax'ing, click is the action, showPrevious is the button that the user interacts with.
$("#showContainer").on( "click", "#showPrevious", function()
{
$.ajax(
{
url: "flip/showprevious.php",
cache: false,
success: function(html)
{
$("#showContainer").html(html);
}
});
});
This is valid JavaScript according to jsHint. When this is added, this and all the lines of code below it do not work. My cPanel and WAMP server is showing no errors. I have read the jQuery documentation on .on() exhaustively.
Troubleshooting I have tried attaching .on() to several different possible parent elements that already exist on page on load. I have tried attached .on() to other buttons to see if it was a problem with the button, but that has also not worked. I thought it might have something to do with the fact I'm recreating something that use to exist and it's confusing my code. I tried changing id to class and # to . accoridingly, but that also did not work. Regardless, none of those should have broken the javascript code anyways. I am sure it is the code I am sharing here. When I comment it out, everything else works as expected.
A note. I was using .click(), and it works for the first click, but after that click, the showPrevious button is recreated, and .click() will no longer work because the new showPrevious was not on the page at load.
Summary Well, that's all the info I have. I can't imagine the rest of the code is relevent, but if it is, tell me what to look for.
It should be like this :
$(document).on("click","#showContainer #showPrevious", function()
{
$.ajax(
{
url: "flip/showprevious.php",
cache: false,
success: function(html)
{
$("#showContainer").html(html);
}
});
});
Related
HTML on the body works, but one coming from PHP doesn't respond at all, why? How do i solve this?
Here's how i'm generating the HTML.
<?php
echo '<div id="TestClick">Click me</div>'
?>
and JavaScript.
$('#TestClick').click(function(e){
alert ('working')
});
But the works.
<body>
<div id="TestClick">Click me</div>
</body>
ok here's how im getting that html from PHP using ajax.
$.ajax({
type:"GET",
url:"../php/feed.php"
}).done(function(feedback){
$('#feed').html(feedback)
});
If your JavaScript is in the HEAD of the page, make sure you wait for document.ready event to bind the DOM events.
$(document).ready(function() {
$('#TestClick').click(function(e){
alert ('working')
});
});
This is a general best practice because the DOM (the HTML code) need to be parsed before JavaScript can interact with it.
Note that there's a shorthand with jQuery $(document).ready:
$(function() {
$('#TestClick').click // etc ...
});
If you're loading this element via AJAX, then you need to handle events once the AJAX request is completed and element added to the DOM. Also, you can use events bubbling to delegate the event listener on a higher level DOM element (for example document).
$(document).on('click', '#TestClick', function() { /* your stuff */ });
Last but not least, make sure you don't have duplicated ID in your DOM. This could cause breakage too.
Probably your element is being created after the click handler is called and as it is not there, the handler is not attached.
Try running that javascript after the php code
EDIT
try
$.ajax({
type:"GET",
url:"../php/feed.php"
}).done(function(feedback){
$('#feed').html(feedback);
$('#TestClick').click(function(e){
alert ('working')
});
});
When you load something using AJAX after the page was loaded, the .click() event has been binded to the existing DOM Elements, but not to the new ones.
You could try this:
$.ajax({
type:"GET",
url:"../php/feed.php"
}).done(function(feedback){
$('#feed').html(feedback).click(function(e){
alert ('working')
)};
});
});
I actually got some problems with my script: indeed it needs 2 clicks to work in a click event. The script is this:
$('td#td_new').live('click', function() {
$.ajax({
type: 'GET',
url: 'add_hobby.php',
data: { hobby: $('#ricerca_interests').val() },
success: function(msg) {
nuovo_hobby="<tr id='hobby' class='checked' selezionato='si' hobby_id='"+msg+"' ><td id='hobby' width='179px'><div id='nome_hobby'>"+$('#ricerca_interests').val()+'</div></td></tr>';
$(nuovo_hobby).appendTo("#interessilista");
$('tr#new_hobby').hide().remove();
},
error: function() {alert("Error. Try later.");}
});
});
As of jQuery 1.7, the .live() method is deprecated. you should Use .on() to attach event handlers.
it doesn't seems that your code generate something that can cause a second click need... but try changing-
$('td#td_new').live('click', function() {
to
$(document).on('click','#td_new', function() {
then open firebug or add a console.log('something') in the success: part - and make sure that the ajax request finishes as wanted and not continuing to run.
other then that we need some more code...
have fun.
EDIT:
I tried to understand what you are trying to do according to the code you upload, but
there is noway to test it, so here are some insights for you:
Include your source scripts (jquery + UI etc) in the head section.
Remove jquery.min... source - you don't need it because you include the full script any way.
I recommend upgrading to jquery 1.9... you are using 1.7.2
When using same identifier over different elements you should use class not id to declare them.
I recommend you to attach the click event to the div add_hobby as a class and not to the td.
Here is a small demo of the usage of on() and appending code to your page:
jsfiddle Demo
Now feel free to direct me to your exact problem.
I am quite new to Jquery and need help trying to get a few events to run on the same page. I have two sections of events, one is a .get which passes data to a file and then displays retrieved data, this happens on page load. The second section is on click events which send and receive data when a button is clicked.
These events all work as needed, but if I have both sections on one page the on click events do not work. Below is the code I have and I hope someone knows how to get them all to work? Thanks
<script type="text/javascript">
$.get("/layout/standard/check.php", { url: "domain"}, function(data){
$("#content-area").html(data)
});
$(".discuss").click( function() {
$.post('/layout/standard/report-action.php', {form: "discuss"},function(data){
$(".message").html(data);
$(".message").show("slow");
});
});
$(".request").click( function() {
$.post('/layout/standard/report-action.php', {form: "request"},function(data){
$(".message").html(data);
$(".message").show("slow");
});
});
$(".report").click( function() {
$.post('/layout/standard/report-action.php', {form: "report"},function(data){
$(".message").html(data);
$(".message").show("slow");
});
});
</script>
I believe that I have found why it's not working, the onclick links are put on the page by the get event. It would appear that the buttons work if they're already on the page but not if they are inserted this way.
This doesn't make sense to me as the buttons are still acting as links with no problem...
Try delegation.. and putting your code inside a document.ready function
$(function() {
$.get("/layout/standard/check.php", {
url: "domain"
}, function(data) {
$("#content-area").html(data)
});
$("body").on('click','.discuss,.request,.report',function() {
$.post('/layout/standard/report-action.php', {
form: $(this).attr('class') //this is assuming you only have 1 class per element
}, function(data) {
$(".message").html(data);
$(".message").show("slow");
});
});
});
You might need to delegate the events if they are attached to content created dynamically. Try replacing:
$(".discuss").click( function() {
With:
$('body').on('click', '.discuss', function() {
And continue for all your events. You can replace the 'body' selector with another selector as long as it is always present in your document.
I working with some ajax at the moment, the result of a successful ajax result is that some more content is add to the page on the fly. My problem is that is added on the fly it looks like I cannot attach any events to the elements that are added.
The flow of what happens is that the user selects an option from a drop-down list, the value of that selection is sent to a PHP function which then returns some more HTML to the page which is appended to a div on the page.
I know there is a problem with the elements not existing on domReady as I run a length() check and it confirms they don't 'exist' on the page.
Is there away around this so that I can run click event on the HTML that gets added after the first ajax request has returned successfully?
$(document).ready(function() {
//customise the select menus
$('#customselector').SelectCustomizer();;
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
$('#grade_choice_options .selectitems').click(function(){
var selectedGrade = $('#grade_choice_customselect').val();
alert(selectedGrade);
})
});
Use live() instead of click() directly:
$('.career_select .selectitems').live('click', function() { ....
live() essentially wires up any new elements that match that are added subsequently.
Try using this plugin :
http://brandonaaron.net/code/livequery/docs : Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
I'm placing content on my page through an ajax (post) request like so:
$("input#ViewMore").click(function() {
var data = { before: oldestDate, threadId: 1 };
$.post("/Message/More", data,function(html) {
$('tbody#posts').prepend(html);
return false;
},
"html");
return false;
});
with the html coming back looking something like:
<div id="comment">Message output Quote</div>
This is all working fine and dandy, everything appears as it should, no problems.
The problem occurs when I have an event hooked into the "quote" anchor that has been added through the ajax call. Specifically, a jQuery event on that anchor does not fire. Why?
For instance:
$("#quote).click(function() { ... });
Does nothing. Acts like there is no event on it. I know it is working on other anchors on the page that were not added through a ajax request, so there is not a code error there, plus if I refresh the page it will then fire correctly. Is there some reason that this is happening, do I need someway to reinitialize that event on the anchor tag somehow? Any ideas?
Working with jQuery 1.3.1 (didn't work with 1.2.6 either) so I believe it is my implementation not code itself.
You can use Events/live of jQuery 1.3, live will bind a handler to an event for all current - and future - matched elements.
When the new content is added to the page with Ajax you have to re-register all the events to those new elements.
Changed to
$('#quote').live("click", function() { ... }
and
$("input#ViewMore").live("click", function() { ... }
Doesn't seem to work
CMS's answer helped, but here's how it ended up:
The view more button event remained the same as it was outside of the AJAH request that added it:
$("input#ViewMore").click( function() { ... }
Elements that had events that were being added in and out of the AJAH request needed to use the live method:
$('#quote').live("click", function() { ... }
Works like a charm!