When I make an AJAX call to replace a div, the response contains a script tag pointing to an external .js file. However, I can't get the returned JS to execute. I've tried to eval() the response but that didn't work. I also tried to call a function inside the external .js file from within the onComplete callback, but this also does not work. Not sure what else to do. I'm using mootools core 1.4.5
Main page's JS
window.addEvent('domready', function(){
function ajaxfunc(i)
{
return function(e){
e.stop();
var requestData = new Request({
url: 'blah.php?cat=' + i,
evalScripts: true,
evalResponse: true,
onComplete: function(response){
$('rt-main').set('html', response);
}
});
requestData.send();
};
}
var total = $('cat_table').getChildren('div').length;
for(var i=1; i<=total; i++)
{
$('catClick'+i).addEvent('click', ajaxfunc(i));
}
});
The returned HTML
<script src="listings.js" type="text/javascript"></script>
...(other markup, etc)
And inside that listings.js file
window.addEvent('domready', function(){
function gotoItem(i)
{
return function(e){
e.stop();
var id= i;
var requestData = new Request ({
url: 'blah.php?id='+id,
onComplete: function(response){
$('rt-main').set('html', response);
}
});
requestData.send();
};
}
$$('.itemBox').each(function(el){
el.getElement('a.itemClick').addEvent('click', gotoItem(el.id));
});
});
The environment I'm working in is Joomla 3.1 in case that affects anything.
No domready will fire a second time for you as per listings.js, your DOM is already ready.
You could manually do window.removeEvents('domready') beforehand, then load via XHR and do window.fireEvent('domready') to run it.
If you use event delegation you can avoid having to run any js after initial ajax requests, all you'd need is something like this.
window.addEvent('domready', function () {
var ct = document.id('cat_table'),
divs = ct.getChildren('div'), //need a more qualified selector
rtMain = document.id('rt-main');
divs.each(function(el, i){
// store the index, if you don't have it as an attribute like id, rel or data-id
el.store('index', i);
});
ct.addEvent('click:relay(div)', function(e){ // needs more qualified also.
e && e.stop();
new Request({
method: 'get', // not post, check - faster
url: 'blah.php?cat=' + this.retrieve('index'),
evalResponse: true,
onComplete: function(){
rtMain.set('html', this.response.text);
}
}).send();
});
// delegation, assumes .itemBox are children of rtMain - just delegate to other parent otherwise.
rtMain.addEvent('click:relay(.itemBox)', function(e){
// reliance on index in collection is bad, try to change response above to contain data-id.
e.stop();
new Request({
method: 'get',
url: 'blah.php?id=' + this.get('data-id'),
onComplete: function(){
rtMain.set('html', this.response.text);
}
}).send();
});
});
keep in mind you had a reliance on the index of the item in the Elements collection, which is less than safe. use a hard db id, provided by the backend. this is insecure, ppl can mod their DOM, delete elements and get to ids they should not see. Not that they can't do so otherwise but...
Bringing in scripts via XHR and evaling responses is an anti-pattern and gives a vector of attack on your page for XSS, don't forget that.
It looks like the script in the linked .js is wrapped in a 'domready' event, but (I'm assuming a little here) the dom would already have fired the ready event. Try removing the window.addEvent('domready', function(){ ...} wrapper.
EDIT since you say that is not the case could it work for you if instead of returning the script tag, you simply returned the script and appended it to the page like this:
onComplete: function (response) {
//
var script = document.createElement('script');
script.innerHTML = response;
document.getElementById('rt-main').appendChild(script);
}
EDIT I've just played with this a little, and it seems I have an inelegant solution fiddle.
Related
When I use this code it bind my $.post() to a form and prevent a page reload for submitting it:
$("#analyze_audio").submit(function (e) {
debugger;
e.preventDefault();
var url = "/analyze_audio";
var dataToSend = {"analyze_audio": "analyze_audio"};
var callback = function (data) {
debugger;
document.getElementById("audioresponse").innerHTML = (data);
};
$.post(url, dataToSend, callback, 'html');
});
But it doesn't trigger the debuggers I used in it, so it doesn't bind the event to my function correctly, but when I use this code fragment, it works perfectly:
$(function() {
$("#analyze_audio").submit(function (e) {
debugger;
e.preventDefault();
var url = "/analyze_audio";
var dataToSend = {"analyze_audio": "analyze_audio"};
var callback = function (data) {
debugger;
document.getElementById("audioresponse").innerHTML = (data);
};
$.post(url, dataToSend, callback, 'html');
});
});
I really don't understand why?
When you're working with jQuery (which you clearly are), wrapping a function in $( ) makes it a function that's called by the library when the "DOM ready" event is received from the browser. It thereby defers execution of your code until the DOM is fully built. That makes your code work because it ensures that the element with id "analyze_audio" is present.
There's nothing syntactically special about $( ) — it's just a simple function call, to a function named $ (which is the main entry point to the jQuery library).
You may see code that does something similar:
$(document).ready(function() { ... });
That does precisely the same thing (and is also a jQuery idiom). There's no reason to use that form unless you enjoy typing in extra characters.
$(function() {}); is just a shortcut for document.ready. It would work the same like this:
<script type="text/javascript">
$(document).ready(function() {
$("#analyze_audio").submit(function (e) {
debugger;
e.preventDefault();
var url = "/analyze_audio";
var dataToSend = {"analyze_audio": "analyze_audio"};
var callback = function (data) {
debugger;
document.getElementById("audioresponse").innerHTML = (data);
};
$.post(url, dataToSend, callback, 'html');
});
});
</script>
When you bind event to the form #analyze_audio it not present in DOM yet. If you put your script after the html with form, then it will work. Or you can use $(document).ready() to add your binding or just $(function(){}) both this functions will be executed when whole page will be loaded.
i have some links in a web page ,what i want to do :
Trigger click event on every link
When the page of every link is loaded , do something with page's DOM(fillProducts here)
What i have tried :
function start(){
$('.category a').each(function(i){
$.when($(this).trigger('click')).done(function() {
fillProducts() ;
});
})
}
Thanks
What you want to do is much more complicated than you seem to be giving it credit for. If you could scrape webpages, including AJAX content, in 7 lines of js in the console of a web browser you'd put Google out of business.
I'm guessing at what you want a bit, but I think you want to look at using a headless browser, e.g. PhantomJs. You'll then be able to scrape the target pages and write the results to a JSON file (other formats exist) and use that to fillProducts - whatever that does.
Also, are you stealing data from someone else's website? Cause that isn't cool.
Here's a solution that may work for you if they are sending their ajax requests using jQuery. If they aren't you're going to need to get devilishly hacky to accomplish what you're asking (eg overriding the XMLHttpRequest object and creating a global observer queue for ajax requests). As you haven't specified how they're sending the ajax request I hope this approach works for you.
$.ajaxSetup({
complete: function(jQXHR) {
if(interested)
//do your work
}
});
The code below will click a link, wait for the ajax request to be sent and be completed, run you fillProducts function and then click the next link. Adapting it to run all the clicks wouldn't be difficult
function start(){
var links = $('.category a');
var i = 0;
var done = function() {
$.ajaxSetup({
complete: $.noop//remove your handler
});
}
var clickNext = function() {
$(links.get(i++)).click();//click current link then increment i
}
$.ajaxSetup({
complete: function(jQXHR) {
if(i < links.length) {
fillProducts();
clickNext();
} else {
done();
}
}
});
clickNext();
}
If this doesn't work for you try hooking into the other jqXHR events before hacking up the site too much.
Edit here's a more reliable method in case they override the complete setting
(function() {
var $ajax = $.ajax;
var $observer = $({});
//observer pattern from addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjquery
var obs = window.ajaxObserver = {
subscribe: function() {
$observer.on.apply($observer, arguments);
},
unsubscribe: function() {
$observer.off.apply($observer, arguments);
},
once: function() {
$observer.one.apply($observer, arguments);
},
publish: function() {
$observer.trigger.apply($observer, arguments);
}
};
$.ajax = function() {
var $promise = $ajax.apply(null, arguments);
obs.publish("start", $promise);
return $promise;
};
})();
Now you can hook into $.ajax calls via
ajaxObserver.on("start", function($xhr) {//whenever a $.ajax call is started
$xhr.done(function(data) {
//do stuff
})
});
So you can adapt the other snippet like
function start(){
var links = $('.category a');
var i = 0;
var clickNextLink = function() {
ajaxObserver.one("start", function($xhr) {
$xhr.done(function(data) {
if(i < links.length) {
fillProducts();
clickNextLink();
} else {
done();
}
});
})
$(links.get(i++)).click();//click current link then increment i
}
clickNextLink();
}
try this:
function start(){
$('.category a').each(function(i){
$(this).click();
fillProducts() ;
})
}
I get ya now. This is like say:
when facebook loads, I want to remove the adverts by targeting specific class, and then alter the view that i actually see.
https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/
Is a plugin for firefox, this will allow you to create a javascript file, will then allow you to target a specific element or elements within the html rendered content.
IN order to catch the ajax request traffic, you just need to catcher that within your console.
I can not give you a tutorial on greasemonkey, but you can get the greasemonkey script for facebook, and use that as a guide.
http://mashable.com/2008/12/25/facebook-greasemonkey-scripts/
hope this is it
I am trying to do an ajax pagination with the following code:
// AJAX pagination
$(".pages .prev").live('click', function(event) {
event.preventDefault()
var current_page = parseInt(getParameterByName('page'))-1;
$.get('/ajax/financial_page/', {'page': current_page}, function(response) {
$(".content table").replaceWith(response)
});
})
And in my view function:
def financial_page(request):
"""
Returns a single financials page, without extra HTML (used in AJAX calls).
"""
page = int(request.GET.get('page', 1))
if request.user.is_superuser:
fs = FinancialStatements.objects.order_by('-date', 'statement_id')
else:
up = request.user.get_profile()
providers = up.provider.all()
fs = FinancialStatements.objects.filter(provider__in=providers).order_by('-date', 'statement_id')
fs_objects, current_page_object, page_range = paginator(request, objects=fs, page=page, number_per_page=30)
data = { 'fs':fs_objects,
'page_range': page_range,
'current_page': current_page_object,
}
page = render_to_string('financial_section.html', data, RequestContext(request))
return HttpResponse(simplejson.dumps([page]))
However, there are two problems I'm running into. The first is that the response is not really HTML, and has a bunch of n\t\t\n\t\t\n\t\n\t\n\t\n\t\t\n\t\, etc. Also, I'm having trouble keeping track of the current page/changing the url as needed. How would I build a functional ajax pagination here?
Update: I figured out the first one, by doing response = $.parseJSON(response);. How would I keep track of which page I am on though?
To keep track of the page, you can increment/decrement a variable on click with your AJAX function. Try this:
var counter="0";
$(document.body).on('click', ".pages .prev, .pages .next", function(event) {
if($(this).hasClass('prev')
counter--;// <--decrement for clicking previous button
else if($(this).hasClass('next')
counter++; // <--increment for clicking next button
event.preventDefault()
$.get('/ajax/financial_page/', {'page': counter}, function(response) {
$(".content table").replaceWith(response)
});
})
I would also not use live method as it is deprecated as of jQuery 1.7. It has been replace by the on method. See the jQuery on() API here: http://api.jquery.com/on/
Check this tutorial about "Ajax Scroll Paging Using jQuery, PHP and MySQL", it may simplify your job:
http://www.bewebdeveloper.com/tutorial-about-ajax-scroll-paging-using-jquery-php-and-mysql
Here is the essential from:
var is_loading = false; // initialize is_loading by false to accept new loading
var limit = 4; // limit items per page
$(function() {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (is_loading == false) { // stop loading many times for the same page
// set is_loading to true to refuse new loading
is_loading = true;
// display the waiting loader
$('#loader').show();
// execute an ajax query to load more statments
$.ajax({
url: 'load_more.php',
type: 'POST',
data: {last_id:last_id, limit:limit},
success:function(data){
// now we have the response, so hide the loader
$('#loader').hide();
// append: add the new statments to the existing data
$('#items').append(data);
// set is_loading to false to accept new loading
is_loading = false;
}
});
}
}
});
});
Try using the javascript String.replace() method:
// AJAX pagination
$(".pages .prev").live('click', function(event) {
event.preventDefault()
var current_page = parseInt(getParameterByName('page'))-1;
$.post('/ajax/financial_page/', {'page': current_page}, function(response) {
response = response.replace(/\n/g,'<br>').replace(/\t/,' ');
$(".content table").replaceWith(response)
});
})
jQuery.get(url, [data], [callback], [type])
type :xml, html, script, json, text, _default。
how about trying to define the last parameter as "html" ?
Hello I am trying to simulate the fade method provided in mootools 1.2 in 1.1.
Due to development restrictions I have to use 1.1. I basically update my div after an ajax response and I want this div to get cleared after some time
var resp = Json.evaluate( response );
$(elem).setHTML('Thanks!'); //Show the message for a while and then clear the div
Thanks for your responses I'm trying to use Dimitar's approach but since I'm not a MooTools expert at all I will need some help
window.addEvent('domready', function(){
$(link_id).addEvent('click', function(){
var a = new Ajax( '{$url}'+this.id, {
method: 'get',
onComplete: function(response) {
var resp = Json.evaluate( response );
$(resp.id).setHTML('Thank you');
//My stupid approach //setTimeout('$("'+divname+'").setHTML("")',3000);
}
}).request();
});
}
So in the context of my code where should I define the Element.extend you propose?
I just tried to add it inside the domready function but couldn't recognise the fade method
to define element prototypes in 1.1x you need Element.extend
Element.extend({
fade: function(from, to, remove) {
new Fx.Style(el, "opacity", {
duration: 500,
onComplete: function() {
if (remove)
this.element.remove();
}
}).start(from, to);
}
});
var el = $("elem");
el.setHTML('Thanks!');
(function() {
el.fade(1,0, true);
}).delay(2000);
in this example I have created a simple element.fade() which DOES need start and end value and can optionally remove the element from the dom etc if you dont plan on needing it again.
here's a working example: http://jsfiddle.net/dimitar/cgtAN/
edit as per your request to empty the html:
window.addEvent('domready', function() {
$(link_id).addEvent('click', function() {
new Ajax('{$url}' + this.id, {
method: 'get',
onComplete: function(response) {
var resp = Json.evaluate(response), target = $(resp.id);
target.setHTML('Thank you');
(function() {
target.empty();
}).delay(3000);
}
}).request();
});
});
Never used Mootools much, but after a bit of jsfiddle, it seems like something along these lines would work:
function fadeAfter(id, msec)
{
setTimeout(function(){
new Fx.Styles(id).start({'opacity': ['1', '0']});
}, msec);
}
Ok I found a solution using setTimeout
setTimeout('$("'+divname+'").setHTML("")',3000);
where 3000 the waiting time in milliseconds
I am using Rails and jQuery, making an ajax call initiated by clicking a link. I setup my application.js file to look like the one proposed here and it works great. The problem I'm having is how can I use $(this) in my say.. update.js.erb file to represent the link I clicked? I don't want to have to assign an ID to every one, then recompile that id in the callback script..
EDIT
To give a simple example of something similar to what I'm trying to do (and much easier to explain): If a user clicks on a link, that deletes that element from a list, the controller would handle the callback, and the callback (which is in question here) would delete the element I clicked on, so in the callback delete.js.erb would just say $(this).fadeOut(); This is why I want to use $(this) so that I dont have to assign an ID to every element (which would be the end of the world, just more verbose markup)
application.js
jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript,application/javascript,text/html")} })
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
jQuery.extend({
put: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'PUT');
},
delete_: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'DELETE');
}
});
jQuery.fn.submitWithAjax = function() {
this.unbind('submit', false);
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
// Send data via get if <acronym title="JavaScript">JS</acronym> enabled
jQuery.fn.getWithAjax = function() {
this.unbind('click', false);
this.click(function() {
$.get($(this).attr("href"), $(this).serialize(), null, "script");
return false;
})
return this;
};
// Send data via Post if <acronym title="JavaScript">JS</acronym> enabled
jQuery.fn.postWithAjax = function() {
this.unbind('click', false);
this.click(function() {
$.post($(this).attr("href"), $(this).serialize(), null, "script");
return false;
})
return this;
};
jQuery.fn.putWithAjax = function() {
this.unbind('click', false);
this.click(function() {
$.put($(this).attr("href"), $(this).serialize(), null, "script");
return false;
})
return this;
};
jQuery.fn.deleteWithAjax = function() {
this.removeAttr('onclick');
this.unbind('click', false);
this.click(function() {
$.delete_($(this).attr("href"), $(this).serialize(), null, "script");
return false;
})
return this;
};
// This will "ajaxify" the links
function ajaxLinks(){
$('.ajaxForm').submitWithAjax();
$('a.get').getWithAjax();
$('a.post').postWithAjax();
$('a.put').putWithAjax();
$('a.delete').deleteWithAjax();
}
show.html.erb
<%= link_to 'Link Title', article_path(a, :sentiment => Article::Sentiment['Neutral']), :class => 'put' %>
The combination of the two things will call update.js.erb in rails, the code in that file is used as the callback of the ajax ($.put in this case)
update.js.erb
// user feedback
$("#notice").html('<%= flash[:notice] %>');
// update the background color
$(this OR e.target).attr("color", "red");
jQuery already handles the this issue for you with the event properties:
$("a").click(function(e){
e.preventDefault();
$("#foo").fadeIn(3000, function(){
$(e.target).text("Foo loaded");
});
});
Note how I can refer back to the main link via its event. This is the case with any events that are handled within as well. Just give them unique names, such as e2, e3, etc. No more need to constantly write yet another var item = $(this) line to keep track of this three events back.
Online Demo: http://jsbin.com/egelu3/edit
If your JS is coming from the server, there is really no way that $(this) can operate in the same context. The closest you could get would be to load some script from the server and eval it in the context of your client-side function.
I basically have an id for each of the DOM elements I need to manipulate, and refer to them within my scripts. It is occasionally ugly, but the alternatives are worse.
If your JS is coming from the server,
there is really no way that $(this)
can operate in the same context. The
closest you could get would be to load
some script from the server and eval
it in the context of your client-side
function.
Not true
I basically have an id for each of the
DOM elements I need to manipulate, and
refer to them within my scripts. It is
occasionally ugly, but the
alternatives are worse.
I don't think this is ugly.
The key to this problem is functional scoping. Let me show you what I mean. You need to create a function that is called before you send your XHR call. In your case, you're doing it with a click event, so let me show you an example tailored for you:
$( '#somelink' ).click( function( )
{
// this stores the location of the current "this" value
// into this function, and will available even after we
// end this function (and will still live while the XHR's
// callback is being executed
var theLink = this;
// fire the AJAX call
$.post
(
'some/url',
{ 'some':'data' }, // optional
function( )
{
// use theLink however you want
// it'll still be there
// also, if you're sending in callbacks
// as variables, you can safely say
hideAndStore.call( theLink, data );
// which executes callback( ), overriding
// "this" with theLink (your DOM node)
// and sending in the responseText as the
// first argument
}
);
} );
and then you could make your callback something like:
function hideAndStore( response )
{
// you can safely use "this" as the DOM node
$( this ).css( { 'display':'none' } );
// and you can do whatever you wish with the response
window.globalData = response;
}
where you'd make it do whatever you actually want it to do, haha.
For more info about functions in JavaScript that change the "this" value, check out .apply and .call at MDC
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Call
What are you doing in the javascript you are sending back? Maybe you can send back some html or json and operate on it in a callback.
$('a:clickable').bind('click', function() {
var elem = $(this);
$.ajax({
url: ...,
dataType: 'json',
success: function(data) {
// elem is still in scope
elem.addClass(data.class_to_add_to_link);
}
});
});
This cannot be accomplished, The method in which i am trying to do this makes it impossible, i cannot pass references to javascript objects through views.
Solution was to assign IDs to each item, and refer to them by that.