How to make AJAX loaded content affected by parent page? - javascript

This problem has bugged me for some time.. If I load something in through AJAX, I have to have the javascript inside the AJAX loaded file (or call an external JS).
How can I make AJAX loaded content be controlled by the master or parent page??
I'd like to take control of all links to pass them through javascript (jquery) and do some fun stuff, but I don't really want to make it an external JS and use $.getScript. I just want my main javascript to be able to work with ajax loaded content.
(Here's an example)
$('a').click(function(e){
e.preventDefault();
// Fun stuff
})

Bind your method, using .on(), to the closest parent container that isn't replaced. For example:
$(function(){
$('body').on('click', 'a', function(e){
e.preventDefault();
// Fun stuff
})
});
See: http://api.jquery.com/on/

Can you show your full example? After you load the content you want trough AJAX you can control the content by Javascript after you have appended it to the DOM.
For example:
success: function(data) {
$('#newContent').hide().html(data)
.find('a').click(function(e) {
e.preventDefault();
});
}

Related

The current window does not have permission to navigate the target frame (cannont get the value of iframe element ) [duplicate]

I have a page we can call parent.php. In this page I have an iframe with a submit form and outside of that I have a div with the id "target". Is it possible to submit the form in the iframe and when success refresh the target div. Say load a new page into it or something?
Edit:
The target div is in the parent page, so my question is basically if you can make for an example a jQuery call outside the iframe to the parent. And how that would look?
Edit 2:
So this is how my jquery code looks like now. It is in the of the iframe page. the div #target is in the parent.php
$(;"form[name=my_form]").submit(function(e){
e.preventDefault;
window.parent.document.getElementById('#target');
$("#target").load("mypage.php", function() {
$('form[name=my_form]').submit();
});
})
I don't know if the script is active cause the form submits successfully but nothing happens to target.
Edit 3:
Now I'm trying to call the parent page from a link within the iframe. And no success there either:
Link
I think the problem may be that you are not finding your element because of the "#" in your call to get it:
window.parent.document.getElementById('#target');
You only need the # if you are using jquery. Here it should be:
window.parent.document.getElementById('target');
You can access elements of parent window from within an iframe by using window.parent like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
Have the below js inside the iframe and use ajax to submit the form.
$(function(){
$("form").submit(e){
e.preventDefault();
//Use ajax to submit the form
$.ajax({
url: this.action,
data: $(this).serialize(),
success: function(){
window.parent.$("#target").load("urlOfThePageToLoad");
});
});
});
});
I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:
window.parent.document.getElementById('yourdiv');
Then do whatever you want with that div.

jQuery calling div element that has been loaded by ajax, or inserted via html() method

It's my first post on stackoverflow. I've searched similiar questions here and found a couple of answers but couldn't really find a solution to this particular problem that would help me.
I have a webpage which loads main contents by ajax. Simply like this:
function loadContent(content) {
if(localStorage.content != content) {
$("#content #content_loading").css("display", "block");
}
var userID = Cookies.get("UserID");
$.ajax({
url: '../game/data/load_content.php',
type: 'post',
data : { ID : userID, Content : content },
success: function(response) {
$("#content #content_loading").css("display", "none");
$("#content #import").html(response);
localStorage.content = content;
$("#header").html("<div class='header_text'>"+content+"</div>");
}
}); }
It loads other ajax functions, html and css. Since I have thousands and thousands lines of code simple things get trickier. Now I simply want to create an universal 'close' button for popup windows. All of the popup windows are in a box, and the close button is inside the box header. Now I want to close all popup windows with a single function:
$('.close').click(function() {
$(this).parent().parent().fadeOut();
});
This simply selects the parent of the close element, which is header and then parent of that parent which is the whole box. One of the popup functions looks like this:
function showPopup(header, content) {
$("#popup_header").html(header+"<div class='close'></div>");
$("#popup_content").html(content);
$("#popup").fadeIn(300);
}
This function is included in the main document (<script src="script"></script>).
Then the other popup is directly loaded upon loadContent(content) function, so it's loaded with ajax call. And it's simply HTML that looks like this:
<div id="nearby_players">
<div class="header">PLAYERS NEARBY <div class="close"></div></div>
<ul> </ul>
</div>
Now if I insert the 'close' function upon click in the document that ajax is loading it will work. And if I change the loadPopup() function to this:
function showPopup(header, content) {
$("#popup_header").html(header+"<div class='close'></div>");
$("#popup_content").html(content);
$("#popup").fadeIn(300);
$(".close").click(function() {
$(this).parent().parent().fadeOut();
});
}
It works too. But what I want to do is to create a single click function attached to the main document that will close all the possible popups that are being loaded on the webpage or already are on the webpage. I thought it was a problem since 'close' element was an ID not a class. And since it should be unique I've changed it to class. So my question is. How do I refer to all of the elements with class 'close' whether they are being loaded with ajax, and then within that ajax they get loaded again with another ajax and so on. And also the popups that are already inserted into document when the webpage gets loaded?
How do I add these elements to the DOM so jQuery actually finds it?
Regards,
Hazes!
You create elements dynamically, which means that events are not attached to them.
Please read how to attach events to dynamically created elements: http://api.jquery.com/live/

Limited with JavaScript onCLick() when making AJAX call

I am working on an existing project and heavily using jQuery AJAX calls. Existing pages have three different sections header, left menu and main content. Implemented with Spring MVC it is updating whole page whenever view is returned from Spring controller.
Now since I am working with one of the menu item but having tab content I am using jQuery to manipulate data within tabs using jQuery. While doing so whenever I have to work with hyperlink I can't use <a> tag since return from link will replace whole page . So I am always limited to use onClick() even ton the link and do AJAX call then put response back in window using jQuery.
Details
<script>
$.ajax({
type: ...,
url: ...,
success: function(response) {
$('#tab1-content').empty().html(response);
}
});
</script>
So my question is - Is there any other way so that I can use href properties of <a> tag and update window with response view?
I am not sure if I understood you correctly. Could you try something like this:
Details
<script>
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
loadDetail(href);
});
function loadDetail(url) {
alert("Load from: " + url);
// Ajax call
}
</script>
Fiddle
You can prevent default behaviour of tag just return false from your function.
See this fiddle http://jsfiddle.net/s8mpwokt/
Or just like in Michael answer attach event from javascript so you'll get event instance in your callback function with preventDefault() and stopPropagation().

How to insert javascript into an AJAX Django app?

I have a Django app where the main content changes frequently via AJAX loads. Since I need to run a lot of javascript on the newly loaded content, what I do now is include a javascript block with several document.ready and other functions at the end of the loaded HTML template.
Is this the proper way to load javascript on AJAX loaded content? If I replace the content block with new (AJAX loaded) HTML + scripts, will the old scripts be removed cleanly?
Are there monitoring tools to detect javascript / memory usage? I am running into some page crashes so I suspect there are some leaks occurring.
Thanks!
You should definitely look into using .live() rather than including new javascript blocks within the loaded html content:
http://api.jquery.com/live/
From the docs:
The .live() method is able to affect elements that have not yet been
added to the DOM through the use of event delegation: a handler bound
to an ancestor element is responsible for events that are triggered on
its descendants.
IMHO you should avoid inserting javascript code into AJAX loading page elements. It's not he best way to do that.
Why cant you make a javascript function and activate it after AJAX finishes load? Or put it on click or hover event...
JavaScript Onclick:
<a class="orange"
onclick="return voteClick(this, '{{ item.pk }}', '1', '{% url ajaxvote %}')"
href=''>Button text</a>
and then in your script:
function voteClick(self, pk, multiplier, url){
//some actions function makes
//for e.g. making POST or changing DOM
// you can use vars that are generated by django template system
return false;
};
jQuery Way:
$.post(url, { param1: value1, param2: value2 }, function(data){
//some function actions upon your AJAX complete
//call your function with code here
// you can load some 'data' for this script from django
// and not the whole script
voteClick(self, value1, value2, data);
return false;
} //end function
);//end POST
ou can read more on this: jQuery POST
So main idea here is that you must load script as a static content from your MEDIA_ROOT and pass it some needed parameters. It's hard way to load your scripts with live() functions. You must take care of tracing lot's of functions and params.
Of course if you're using jQuery it's easy to trace code events with it's selectors. But again... Why do you need to load code with AJAX request? It's definitely static file to be used here, as your scripts file...

jquery on load function

Question
I want to play a loader when any page is loading and it work stop when complete page is loaded. Any idea?
i am new in jquery or javascript.
Just put a DIV on your page immediately with the loading graphic. Put this script anywhere on your page or at the top of an external script file:
$('BODY').append('<div id="loading"><img src="images/loading.gif" /></div>');
Obviously you'll need to style it to position it wherever you want. We do it this way rather than just hard-coding it into the page content so that anyone with JavaScript disabled won't see it.
Then attach to the load event to hide the loading DIV once the page is done. Put this script at the bottom of your page or inside a $(document).ready().
$(window).load(function() {
$('#loading').hide();
});
You need to listen the event onload
window.onload = function() {
// do something
}
or in jquery
$(window).load(function() {
// do something
});
but with jquery a think is better to use :
$(document).ready(function() {
// do something
});
You can use ajaxStart and ajaxStop methods.
Demo:
http://www.balam.in/personal/triponetDemo/pre-loader.html
Click on view source to see the CSS and javascript.
Have a div with id as loading and style the div to show the ajax spinner. Whenever an ajax method is triggered it will show the loading div and when the ajax request is completed, it hides the loading div.
Note that you need to have the loading div in all the pages where ever you want to show it.
Well in case you want to show the ajax spinner on refresh,
check the link below:
http://www.balam.in/personal/triponetDemo/pre-loader-refresh.html
View source to see the implementation
Everytime you refresh it will show the ajax spinner and when the DOM is ready it hides the ajax spinner.

Categories

Resources