How to bind events to element generated by ajax - ajax

I am using RenderPartial to generate CListView and all the contents generated properly and good pagination is working fine too. But when I added my custom JS to elements generated by the CListview it works fine for the the fist page content but when i use pagination and click to page 2 then the JS binding fails.
Is there any other way to bind custom event to elements generated in YII CListview I had tried using live, and on nothing work for me here is my js file.
I think I have to call my function on every ajax load in but how can I achieve in yii
This is the script I am using to update ratings on server with button click and this the element for which these forms and buttons are defined are generated by CListview in yii
$(document).ready(function(){
$('form[id^="rating_formup_"]').each(function() {
$(this).live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
});

You can also try CGridView.afterAjaxUpdate:
'afterAjaxUpdate' => 'js:applyEventHandlers'

The $.each method will loop only on existing elements, so the live binder will never see the ajax-generated content.
Why don't you try it like this:
$(document).ready(function(){
$('form[id^="rating_formup_"]').live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});

This problem can be solved by two ways:
Use 'onclick' html definitions for every item that is going to receive that event, and when generating the element, pass the id of the $data to the js function. For example, inside the 'view' page:
echo CHtml::htmlButton('click me', array('onclick'=>'myFunction('.$data->id.')');
Bind event handlers to 'body' as the framework does. They'll survive after ajax updates:
$('body').on('click','#myUniqueId',funcion(){...});

Related

Ajaxinate Endless scolling has stopped product Quick View from working

I am using Shopify "Streamline Theme" with quick product view and I recently added infinite scroll to products on each collection using Ajaxinate.js.
When I open a collection page it loads with some products which is supposed to do, The products already there work fine with quick view and quick add to cart and also.
The Infinite scroll works fine and it loads new product fine but the problem is raised when the new products loaded through AJAX call doesn't have work with the quick view function.
I have tried to create a callback function to activate the quick view with no success, using the theme initialisation code with no success.
function callBack(){
theme.init();
theme.initQuickShop();
};
document.addEventListener("DOMContentLoaded", function() {
var endlessClick = new Ajaxinate({
method: "scroll",
loadingText: 'Loading...',
callback: callBack
});
});
Edit -------
My problem, is that when the page is loaded only the initial loaded products quickview elements are loaded in the DOM. When the scroll more button is clicked, the newly loaded products are loaded without their respective quickview elements. Hence why the quickview does't work for them. The theme.js file comes with this initialisation code:
theme.reinitProductGridItem = function($scope) {
if (AOS) {
AOS.refreshHard();
}
if (theme.settings.currenciesEnabled) {
theme.currencySwitcher.ajaxrefresh();
}
// Reload quick shop buttons
theme.initQuickShop(true);
// Refresh reviews app
if (window.SPR) {
SPR.initDomEls();SPR.loadBadges();
}
// Re-register product templates in quick view modals.
// Will not double-register.
sections.register('product-template', theme.Product, $scope);
// Re-hook up collapsible box triggers
theme.collapsibles.init();
};
I have tried to integrate this into a callback but no success, the quickview modal doesn't seem to load for the newly loaded products:
function callBack(){
ReloadSmartWishlist();
var $container = $('#CollectionSection');
theme.reinitProductGridItem($container);
// I have tried the following init qith no success:
// theme.init();
// theme.initQuickShop(true);
// theme.initQuickShop();
// sections.register('product-template', theme.Product, $container);
// AOS.refreshHard();
};
document.addEventListener("DOMContentLoaded", function() {
var endlessClick = new Ajaxinate({
method: "click",
loadingText: 'Loading...',
offset: 0,
callback: callBack
});
});
I am missing something but what? :/
Note for other things like loading products images with the callback and the wishlist app, it works as intended...
When you load elements via AJAX and if the events are not attached to a parent element that is not removed from the DOM, those elements will not have an attached event to them.
The term used here is event delegation.
Here is an example of non-delegated event:
document.querySelectorAll('a').addEventListener('click', function(){
// Do something
})
Since you are attaching the event to the existing "a" elements if you add new 'a' via AJAX those elements will not have the event since Javascript already attached all the events and it will not reattach them if you don't specifically recall them again.
Here is an example of a delegated event:
document.querySelector('body').addEventListener('click', function(target){
let target = event.target;
if (target.tagName === 'A'){
// Do something here
}
})
Where we attach the event to the body tag ( where it's a better idea to attach it to a closer none-modified parent element of the ajax items ) and once we click we check if our target tag is an "a" and do something then.
So long story short, you will need to delegate the quick cart link so that it works after you load the items via AJAX.
Drip is correct you need to delegate your event, but for people like me it's hard to completely understand how to do that.
I'm not sure how your quickview is structured, but if you open it with a .click function and can use jquery use the [.on() function][1].
For example: I use a quickview that opens on a button click. My button is attached to my product-grid-item.liquid with this bit of code:
<div class="quick-view-button">
<a class="quick-view" data-handle="{{ product.handle }}" href="javascript:void(0);">Quick View</a>
</div>
My quickview function originally looked like this:
function quickView() {
$(".quick-view").click(function () {
//all of the quickview code
What happens is exactly like you described. The event listeners only loaded on the first product load but nothing after an AJAX load.
Using jquery's .on() binds the event listener to the element meaning when it's loaded in later it'll still have the event. Here's an example of what my code looks like after using .on()
function quickView() {
$('body').on('click','.quick-view',function(){
I really hope this helps you or someone else with this problem.
[1]: http://api.jquery.com/on/

Update HTML Element Associated with Click Event Triggering JQuery AJAX Request

I have several HTML elements (buttons) that fire the same JQuery AJAX request. When the AJAX request returns successfully, I need to make some updates to the HTML element that triggered the AJAX request. I understand how to do this if I were to hardcode the id of the element to update, such as an item with an id of myDiv as shown in the code below, but I am unsure of how to handle a dynamic id that corresponds to the element that triggered the event.
$('body').on(
'click',
'#yt25',
function(){
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$('#myDiv').html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
I figure one option is to send the id of the HTML element that triggered the event as a key-value pair in the ajax request 'data' option and then have it passed back to the client as part of the AJAX response. I could then grab the id and know which HTML element to update. Is that the best way to handle this or am I missing something more obvious? Thanks.
$('body').on(
'click',
'#yt25',
function(){
var _this = this;
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$(_this).html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
You don't need to sent it along with the ajax request.
This is one variation. You can also do this be assinging some classes to the element and get those elements by that class will do.

Running a javascript after ajax load

I'm using jQuery UI. I'm loading some content in a dialog box over AJAX. After inserting the content from the server, I need to make modifications to the document. I am using the .live() function on my link; I thought this would enable me to use Js after loading the content over ajax, but it's like the content I just loaded isn't a part of the document. Any help very much appreciated.
Are you adding the bindings (lives) in the success function of the ajax call?
If so I had the same issue, I'll try to explain what I figured out:
$.post('callURL', function(data){
// Let's say data returned from server is an ID of a div I have to hide
// by clicking on some_link
$('#some_link').live('click',function(){
$('#'+data).hide();
});
});
This won't work because the code inside the 'live' function is executed on click and at that time the 'data' value is gone.
To make it work I made a global variable 'ID' which I set in the success function and then called in the 'live' function again like this:
var ID;
$.post('callURL', function(data){
// Let's say data returned from server is an ID of a div I have to hide
// by clicking on some_link
ID = data
$('#some_link').live('click',function(){
$('#'+ID).hide();
});
});

MVC2 - Submit form with AJAX and non-AJAX

Using MVC2 I have created a form using the Ajax helper in a view. The form posts to a controller which binds to a model object. A PartialViewResult is returned by the controller and the HTML gets updated into a div. So far, so good.
I now need to submit the same form and return the results in a generated file for the user to download. Obviously I don't want the file contents going into my div.
Is there an elegant way to handle this situation without having to hack it to bits? I'm fairly new to MVC / AJAX and it's still a point of confusion for me.
You may not use ajax call to download files. Following links may help you to do what you are trying to do
JQuery Ajax call for PDF file download
http://forums.asp.net/t/1683990.aspx/1
OK, so I couldn't find any simple solutions anywhere so I came up with my own. I remove the Ajax event handlers from the form when I want the download, put them back when I want the Ajax. I'm guessing there's a more elegant way to do this, as this feels like a 'clever trick'. I'm open to better suggestions but so far this is my preferred method.
Reference ToggleAjax.js on my page:
var ToggleAjax = function ($, form) {
var onclick = form.onclick,
onsubmit = form.onsubmit;
$('input[class*="ajax-enabled"]').click(function () {
form.onclick = onclick;
form.onsubmit = onsubmit;
});
$('input[class*="ajax-disabled"]').click(function () {
form.onclick = function () { };
form.onsubmit = function () { };
});
};
Then I call ToggleAjax on my page and pass in the form:
$(function () {
ToggleAjax($, $('form')[0]);
});
And of course I add the class ajax-enabled or ajax-disabled to the input controls.

jquery mobile ajax sends both GET and POST requests

Here is the problem:
By default jQuery Mobile is using GET requests for all links in the application, so I got this small script to remove it from each link.
$('a').each(function () {
$(this).attr("data-ajax", "false");
});
But I have a pager in which I actually want to use AJAX. The pager link uses HttpPost request for a controller action. So I commented the above jQuery code so that I can actually use AJAX.
The problem is that when I click on the link there are two requests sent out, one is HttpGet - which is the jQuery Mobile AJAX default (which I don't want), and the second one is the HttpPost that I actually want to work. When I have the above jQuery code working, AJAX is turned off completely and it just goes to the URL and reloads the window.
I am using asp.net MVC 3. Thank you
Instead of disabling AJAX-linking, you can hijack clicks on the links and decide whether or not to use $.post():
$(document).delegate('a', 'click', function (event) {
//prevent the default click behavior from occuring
event.preventDefault();
//cache this link and it's href attribute
var $this = $(this),
href = $this.attr('href');
//check to see if this link has the `ajax-post` class
if ($this.hasClass('ajax-post')) {
//split the href attribute by the question mark to get just the query string, then iterate over all the key => value pairs and add them to an object to be added to the `$.post` request
var data = {};
if (href.indexOf('?') > -1) {
var tmp = href.split('?')[1].split('&'),
itmp = [];
for (var i = 0, len = tmp.length; i < len; i++) {
itmp = tmp[i].split('=');
data.[itmp[0]] = itmp[1];
}
}
//send POST request and show loading message
$.mobile.showPageLoadingMsg();
$.post(href, data, function (serverResponse) {
//append the server response to the `body` element (assuming your server-side script is outputting the proper HTML to append to the `body` element)
$('body').append(serverResponse);
//now change to the newly added page and remove the loading message
$.mobile.changePage($('#page-id'));
$.mobile.hidePageLoadingMsg();
});
} else {
$.mobile.changePage(href);
}
});
The above code expects you to add the ajax-post class to any link you want to use the $.post() method.
On a general note, event.preventDefault() is useful to stop any other handling of an event so you can do what you want with the event. If you use event.preventDefault() you must declare event as an argument for the function it's in.
Also .each() isn't necessary in your code:
$('a').attr("data-ajax", "false");
will work just fine.
You can also turn off AJAX-linking globally by binding to the mobileinit event like this:
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Source: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html

Resources