jQuery ajax attaching events to elements - javascript

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.

Related

On click event not firing the first time on dynamically added elements via AJAX

I have a ul element that gets populated with li elements via AJAX.
Then I need to do something when clicking on those li elements.
The funny thing is that it works the second time I click on the li element it but not the first time.
I've read every possible related question I could find on StackOverflow but I can't find the answer to my problem.
Here is an example of the AJAX code:
$('#university').on('keyup', function(){
$.ajax({
url: ajaxUrl,
data: {
"search": searchVal,
"action": 'autoComplete',
},
type: "POST",
dataType: 'json',
success: function(data) {
$(".univers-name-list").html("");
var dataItem=[];
dataItem=data.data.items;
if(dataItem){
dataItem.forEach(function(element,key) {
$(".univers-name-list").append('<li>'+element.name+'</li>')
});
}
}
});
});
And here is the on click function (in the same file):
$('.univers-name-list').on('click', 'li', function(e){
// Code here
console.log('Helo'); // Doesn't run the first time.
});
Any idea what I'm doing wrong? Why does it only work when I click it for the second time?
Some more info:
When I checked the event target, the first time I click on any li element, the target is UL (populated with the dynamically added LI elements), but the second time is the correct LI element.
It was a custom validation rule on the input field that messed up everything.
After fixing that rule, it now works as expected.
Event listeners will not work fFor elements created dynamically via javascript.
You have to use delegate functions for these kind of elements
This code should work fine on you element created dynamically.
$(document).on('click', '.univers-name-list li', function(e){
// Code here
console.log('Helo');
});
You have to call addEventListener to the new created elements.
check this Attach event to dynamic elements in javascript

Why doesn't HTML generated dynamically with PHP respond to JavaScript?

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')
)};
});
});

Update div id in jquery so script can only run once

I currently have a script that I am using in my website. The goal of the script is when the user clicks the link, the javascript function will fire. This function is based off of the div id. At the end of the function I use jquery to change said div id. However, when the user clicks the link again the function still fires, even though the id has changed. What am I doing wrong? How can I get the script to only execute the first time the link is clicked?
$("#down").click(function(){
var id = $("#down").attr("class");
$.ajax({
type: "POST",
url: "vote.php",
data: "side=down&id=" + id,
success: function(){ alert("lul worked"); }
});
$('.' + id + '#down').attr('id', 'down_stay');
});
Now that you all have answered, what is the better choice, using "one" or using "unbind"?
Don't use click, use on. Or in your case, one:
$('#down').one('click', function() {
// function only fires once and then is unbound.
});
Use $("#down").one("click", function(){}); instead to make it fire only once.
Use unbind() instead.
replace
$('.' + id + '#down').attr('id', 'down_stay');
with
$( this ).unbind( 'click' );
Try using one
$("#down").one('click', function(){
The DOM events are attached to the elements and not to the attributes.
So even if you change the attributes of the element it does not mean it is a different element.
The event will only be removed if that particular element will be removed from the DOM..

Reload Ajax/Javascripts afer .html() data load

So I have a page that loads the data into the page through the following ajax function.
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: "POST",
url: "inc/load_data.php",
data: "p="+page+"XXXXXXXXXXX",
success: function(msg)
{
//alert(msg);
$("#container").ajaxComplete(function(event, request, settings)
{
$("#container").html(msg);
//**MODIFIED CODE
$(document).delegate('a.vote_up','click', f_vote_up);
});
}
});
}
});
//Loaded Message
$msg.='<span class="vote_buttons" id="vote_buttons'.$row['id'].'">
</span>';
The message that is loaded has some links that need to work with a another Ajax function(given below), which is apparently not working. The second function(below) is loaded before the data is loaded into the page. I suspect, may be since this function is loaded way before the data is loaded, the second function is not recognizing the click on vote_up. Is there any way to fix it??? I'm not too familiar with AJAX, I would really appreciate some help.. Thank you
$(function(){
$("a.vote_up").click(function(){
//get the id
alert("Hi");
//REST OF THE CODE
}
//***NEW FUNCTION
function f_vote_up(){
//get the id
the_id = $(this).attr('id');
//REST OF THE CODE
$("span#vote_buttons"+the_id).html("Hello, Testing Response!");
alert("End of Func!"); // <
}
When you call that second function, it's only grabbing all the a.vote_up elements that currently exist on the page. When you add more links to the page later on, they don't know to listen for the click.
You can do one of two things to fix this:
Add the click listener to each new link when you add it to the DOM. But this is a bit of work, because you'd have to change how your AJAX function builds the links, and you'd have to turn that click-listener-assigning function into something standalone that you could use at any time.
Instead of doing using the click method, use the delegate method instead:
$(document).delegate('a.vote_up', 'click', function () { ... });
More info on event delegation with jQuery.
you should bind your click event after you load the html
$.ajax
({
type: "POST",
url: "inc/load_data.php",
data: "p="+page+"XXXXXXXXXXX",
success: function(msg)
{
//alert(msg);
$("#container").ajaxComplete(function(event, request, settings)
{
$("#container").html(msg);
$("a.vote_up").click(function(){
//get the id
alert("Hi");
//REST OF THE CODE
});
});
}
});
You can use the live function to bind an event to dynamically created elements, i.e.:
$("a.vote_up").live('click', function(){
//get the id
alert("Hi");
});
http://api.jquery.com/live/
This will effectively bind this click event to all elements which match the a.vote_up selector, now and in the future.

change event doesn't fire on ajax loaded forms

I have an HTML document, with the jquery code
$(function(){
[...]
$("#newNotice").click(function(){
$("#properties").load("testDiagramm.html #NoticeForm");
return false;
});
function showFormValues(){
var s = $("form").serialize();
[... Do things ...]
}
$("input, textarea").change(showFormValues);
});
At the beginning there is no form in the HTML document. But i load diffrent forms into the document. One of those request you can see here
$("#properties").load("testDiagramm.html #NoticeForm");
The problem is. that the codeline
$("input, textarea").change(showFormValues);
only fire, when the form was loaded at the beginning. What must I do, if i want to execute the function showFormValues(), when I changed something in the formular, which i load later?
Thanks a lot for your answers.
Lara
Your form loses its binding to the DOM after it is reloaded via ajax, so event handlers previously bound to the elements that get injected into the page are lost.
I would normally suggest using event delegation with live, but it does not support the change event, so a safe bet would be to rebind using a callback as a second parameter to your $.load function:
$(function(){
[...]
$("#newNotice").click(function(){
$("#properties").load("testDiagramm.html #NoticeForm", function() {
$("input, textarea").change(showFormValues);
});
return false;
});
function showFormValues(){
var s = $("form").serialize();
[... Do things ...]
}
$("input, textarea").change(showFormValues);
});

Categories