Grabing ajax content after its load - javascript

sorry my bad english. I have a function to manipulate ajax like this:
$(document).on("click", ".ajax", function(e){
//dynamic contents here, getting the href value from links.
});
Now I need manipulate the content of the ajax request AFTER IS LOADED, adding some others functions to specific elements (add ajaxForm() to form elements, and others ). The case is: how to bind these functions WITHOUT a specific event? Per example, in the "contact.php" page and I want grab the tag to manipulate this, but the
$("form")
tag is not accessible.
If through a click, I would use
$(document).on("click", "element", function(e){
but no click event
How I can get this? Thks
Aditional information:
I want this:
ajaxLoader(content, "#mainDiv"); //loading a content. ajaxLoader is a .ajax() function
form1 = $("#mainDiv").find('#formOne'); //I need grad form like this
var options = {
beforeSend: function()
{
$("#progress").show(); //inacessible
$("#bar").width('0%'); //inacessible
$("#message").html(""); //inacessible
$("#percent").html("0%"); //inacessible
},
uploadProgress: function(event, position, total, percentComplete)
{
//foo
},
success: function()
{
//bar
},
complete: function(response)
{
//foo
}
};
$(form1).ajaxForm(options); //inacessible

Use the .success callback on your AJAX call. That's is why it is there.

Related

Event delegation not working jquery

So I'm just getting started with event delegation and I'm still fairly confused by it but here goes:
I have a button which adds a rating in ajax, once clicked again I'd like it to remove the rating, here's the code with annotations (and some parts removed to make it look more clear).
$(document).on("click", '.add_rating', function() {
l.start();
var input = $(this).prev().children('.my_rating');
var score = input.val();
var what_do = input.attr('action_type');
var cur_average = $('.current_average').val();
var data = {};
data.score = score;
data.media_id = <?php echo $title_data->media_id; ?>;
data.what_do = what_do;
$.ajax({
dataType: "json",
type: 'post',
url: 'jquery/actions/add_remove_rating',
data: data,
success: function(data) {
if (data.comm === 'success') {
//do some other stuff there, irrelevant
$('.ladda-button').removeClass('btn-primary');
$('.ladda-button').removeClass('btn-sm');
$('.ladda-button').addClass('btn-danger btn-xs');
$('.ladda-label').html('Remove');
$('.ladda-button').addClass('remove_rating'); <-- add the remove rating class I want to call if the button is clicked again
input.attr('action_type', 'remove_rating');
l.stop();
}
}
});
$('.remove_rating').on('click', function() { <-- this doesn't work, why?
alert('remove was clicked');
});
});
I can't seem to trigger this:
$('.remove_rating').on('click', function() { <-- this doesn't work, why?
alert('remove was clicked');
});
Any help appreciated!
Edit: on a side note, I don't actually need this to work as php figures out if we're removing or adding a score based on the action_type attribute. I just wanted to find out why it's not triggering.
change your code to:
$(document).on("click", '.add_rating', function() {
l.start();
var input = $(this).prev().children('.my_rating');
var score = input.val();
var what_do = input.attr('action_type');
var cur_average = $('.current_average').val();
var data = {};
data.score = score;
data.media_id = <?php echo $title_data->media_id; ?>;
data.what_do = what_do;
$.ajax({
dataType: "json",
type: 'post',
url: 'jquery/actions/add_remove_rating',
data: data,
success: function(data) {
if (data.comm === 'success') {
//do some other stuff there, irrelevant
$('.ladda-button').removeClass('btn-primary');
$('.ladda-button').removeClass('btn-sm');
$('.ladda-button').addClass('btn-danger btn-xs');
$('.ladda-label').html('Remove');
$('.ladda-button').addClass('remove_rating'); <-- add the remove rating class I want to call if the button is clicked again
input.attr('action_type', 'remove_rating');
l.stop();
$('.remove_rating').on('click', function() { <-- this doesn't work, why?
alert('remove was clicked');
});
}
}
});
});
EXPLANATION:
first have a look here: Understanding Event Delegation.
event delegation is used when you need to create event handlers for elements that do not exist yet. you add a .remove_rating class to elements dynamically, however you are trying to attach a handler to elements with the above mentioned class before you even attach it.
you are attaching the class when the asynchronous ajax call returns, in the success function, however your event handler block is being processed right after you send the ajax, and not after the ajax returns (ajax is async rememeber?). therefore, you need to wait until the ajax returns and the elements are created, and only then attach the handler to them.
alternatively, using event delegation, you can attach the handler to the document, like you did in the following line:
$(document).on("click", '.add_rating', function() {
it means, that you attach the handler to the document, and whenever any element ON the document is clicked, if that element has the class '.add_rating' then execute the handler.
therefore, you may attach another handler to the document to monitor for clicks on elements with the .remove_rating class as follows:
$(document).on("click", '.remove_rating', function() {
this is called event delegation, because you delegate the event to a parent element.
Because class was added after click event initialised. You need to use live event handlers, like this:
$( document ).on('click', '.remove_rating', function() {
In this case .remove_rating click handler will work on dynamically created elements and on class name changes.

Jquery function doesn't work after Ajax call

I've got this function:
$(document).ready(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
My page loads content with favourite buttons, but after Ajax call and generated additional new content the function doesn't work when you click new content's buttons. What could be not right?
That is because you are using dynamic content.
You need to change your click call to a delegated method like on
$('.post_button, .btn_favorite').on('click', function() {
or
$("body").on( "click", ".post_button, .btn_favorite", function( event ) {
Instead of this:
$('.post_button, .btn_favorite').click(function() {
do this:
$(document).on('click','.post_button, .btn_favorite', function() {
on will work with present elements and future ones that match the selector.
Cheers
class-of-element is the applied class of element. which is selector here.
$(document).on("click", ".class-of-element", function (){
alert("Success");
});
If you know the container for .post_button, .btn_favorite then use
$('#container_id').on('click', '.post_button, .btn_favorite', function () { });
so if '.post_button, .btn_favorite' are not found then it will bubble up to container_id
else if you don't know the container then delegate it to document
$(document).on('click', '.post_button, .btn_favorite', function () { });
Reference
I am not sure if I am getting your question right but you may want to try..
$.ajax({
url: "test.html"
}).done(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
Just try to paste your code inside done function.
Hope it helps :)
EDIT:
I also notice you are missing }); on your question.
The following worked for me
$(document).ready(function(){
$(document).bind('contextmenu', function(e) {
if( e.button == 2 && jQuery(e.target).is('img')) {
alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.');
return false;
}
});
});
You need to bind the jQuery click event once your ajax content is replaced old content
in AJAX success block you need to add code like here new response html content one a tag like
Click Me
So you can bind the new click event after change the content with following code
$("#new-tag").click(function(){
alert("hi");
return false;
});

on jQuery .html() update, other functions stop working

I have certain "pages" on my website that are sortable. They also auto update to a database.
After my li list is sorted, a php page is called that re-orders the "pages" and then I call .html(data) to change the order of the pages that are displayed on the page.
After doing this, however, my auto update functions in my javascript stop working.
There is a #form1 that works before the sort takes place and the .html(data) is called. Once it is called, the previous #form1 get's removed and re-added to the page. This is when it stops working.
Does anyone know the reasoning for this?
My update script
$("#reportNav").sortable({
stop : function(event, ui){
var postData = $(this).sortable('serialize');
var url = "saveOrder.php";
$.ajax({
type: "POST",
url: url,
data: postData,
success: function(data) { $('#reportContainer').html(data); },
error: function(data) { $changesSaved.text("Could not re-order pages."); }
});
}
});
What stops working/stops being called
var timeoutId;
$('#form1').on('input propertychange change', function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
$("#form1").submit();
}, 1000);
});
Probably a case of over-writing your elements that has handlers bound, in which case you need event delegation:
$('#reportContainer').on('input propertychange change', '#form1', function() {

Manipulate json data with jQuery

I am looking to load json data as html as show in this fiddle and below.
(function () {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function (data) {
$.each(data.items, function (i, item) {
$("<img>").attr("src", item.media.m).appendTo("#images");
if (i === 3) {
return false;
}
});
});
})();
jQuery("#images img").on("click", function (event) {
console.log('aaa');
});
I can get the json to load however I can't then get events such as on click to work with data that has been loaded with json, what am I doing wrong here?
You need to delegate your click events. They're being bound to items in the DOM, and then you're adding new items, and the events are not bound to them.
Try replacing your click binder with this:
jQuery(document).on("click", "#images img", function (event) {
console.log('aaa');
});
You'll want to replace document with the lowest-level consistent wrapper to avoid redundant traversal on click.
try this instead:
$("#images").on("click", "img", function (event) {
console.log('aaa');
});
the element with the id images exists when your event binding is attached, but the image elements do not. So using the on method, you can pass the img elements as a second parameter so that all img elements that are added after the page load are properly bound to this event handler.

Jquery doesnot bind events to ajax added dom

I have an ajax function that loads the content of 4 checkboxes as follows:
$.ajax({
url : some url..,
dataType : 'json',
success : function(data) {
buildCheckboxes(data);
},
error : function(data) {
do something...
}
});
build checkboxes methods does something like this:
function updateNotificationMethods(items) {
var html = [];
$.each(items, function(i, item) {
htmlBuilder = [];
htmlBuilder.push("<input type='checkbox' class='checkbox-class' name='somename' value='");
htmlBuilder.push(item.id);
htmlBuilder.push("'");
htmlBuilder.push("/> ");
htmlBuilder.push(item.name);
htmlBuilder.push("<br/><br/>")
html.push(htmlBuilder.join(''));
});
$("#div").html(html.join(''));
}
i have also an event binder that should be triggered when checkbox value changes:
$(".checkbox-class").change(function() {
alert("change");
});
it works if i have the checkboxes html in the source (i.e. static) as opposed to the set up i have here, where i dynamically load the data from server.
is there something i can do so that binding take place timely?
peace!
This is because the element is not present when you bind your handler.
Try this:
$( document ).on( 'change', '.checkbox-class', function() {
alert("change");
});
Or if you are using an older version of jQuery (less than 1.7) ...
$( '.checkbox-class' ).live( function() {
alert("change");
});
Checkboxes are not available while you are binding the events. jsfiddle
Assuming that element with id div is present while binding the event.
$("#div").on("change",".checkbox-class",function() {
alert("change");
});
This code:
$(".checkbox-class").change(function() {
alert("change");
});
do not establishes a continuous and on-going rule, instead, this code attaches an event manager (in this case to the change event) to each matching DOM object that exists at the moment it is executed.
If you want you can re-execute this code (or one similar and narrow) each time you add checkboxes to the DOM.

Categories

Resources