Limited with JavaScript onCLick() when making AJAX call - javascript

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().

Related

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/

How to load a page dynamically using Ajax & History?

I am confused with the following problems in using Ajax and History:
Specifications:
I have a page that calls another page using Ajax.
Now the loaded page has datatables which inturn uses Ajax to get data(As of now 2 ajax calls)
I have used history.js for page navigation, which uses common ajax call for loading the content in page div
Now, I face with the following problem:
For first datatable page call, I get one ajaxcall.
Surprisingly, when I navigate to another page using history and call the datatable page, the ajax call now doubles. It goes on in a linear manner.
This is a new problem I have been facing while loading a page using ajax which inturns contain Ajax call. What can be the major cause of this problem? Also, what is the solution of this problem?
My common code looks like this:
<script>
var index=function(url,update_id,state){
$.ajax({
url: url,
}).done(function(data) {
$("#"+update_id).html('');
$("#"+update_id).html(data);
if(state == 1){
history.pushState({url: url,id:update_id},"name",url);
}
});
}
jQuery(document).ready(function($) {
$(document.body).on('click','.link_click',function(){
var url = $(this).attr('href');
var update_id = $(this).attr('update_id');
index(url,update_id,1);
})
});
window.addEventListener('popstate', function(event) {
if(event.state.url != null){
index(event.state.url,event.state.id);
}
});
</script>
My link looks like this:
My Contact
I am using this common code for linking every page using Ajax and history
Are you using a framework for your project? I've noticed similar behaviour before using the Yii Framework. What I noticed is that if you create your objects with a static Id, it will cause a multiplication in the number of ajax calls.
Try giving your objects unique ids so that the events don't get clogged.
Just an idea: Does the page loaded with Ajax by any chance attach the click-event on the "link_click"-links again?

How to make AJAX loaded content affected by parent page?

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

Callback when web page download completes

When the user click on a tab in a web page, the tab opens and its corresponding page downloads from the server.
I want to add some UI in this page through JavaScript or jQuery. I know how I can add this but problem is if I execute my JavaScript function for adding UI on click of the tab, it does not work because the corresponding page has not been downloaded yet.
Basically, what I want to know such function that is called when the page completely downloads.
Have you used JQuery success ?? success handler will be called only after your response is ready.
Try this :
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//Do the stuff here, hence downloading has been completed and response from server is ready
$(this).addUI("done");
}
});
add this in the body of your page..
<body onload="init()">
</body>
Basically your calling your init function -- which initiates all the other functions which you want only after the body of the webpage is loaded..
I have face this problem too.. Problem here is your content is not yet available before you could work on it.
any reference you give will result in returning Null
The solution can be .bind() & .live()
suppose this is your dynamic content
$('body').append('<div class="clickme">Another element</div>');
you can bind the element by,
$('.clickme').bind('click', function() {
// Bound handler called.
});
or register it for live content, by
$('.clickme').live('click', function() {
// Live handler called.
});
when no longer needed, you may unsubscribe the event on dynamic content by .die()
you may also find .delegate() & undelegate() useful as there are little issues with .live() & .die().
Check http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/ for choosing the one you need for your application.
Remember not to forget you ensure that content is loaded by ajax success as programmer_1 here, mentioned.
Good luck :)
Any further clarifications pls comment.

Link in one div, trying to load content in a seperate div

I am using jQuery to make a website, and I want to be able to have my navigation in a separate div from my content. Also, I want to be able to have a sort of tabbed navigation system such that I can click a link in the navigation and it will load the content into the main content div. Basically, I want to do this so that I can just maintain one page with all the content, rather than a bunch of pages for each section. I have included a picture that will hopefully make my question much more clear (right click and "viw image", it's too small on this page):
example http://img402.imageshack.us/img402/1733/examplew.jpg
$('#navlink').click(function() {
$("#maindiv").load("/url.html");
return false;
});
I would encourage you to use event delegation. For instance we can use the .on method to attach a single event to the navigation pane that will listen for clicks on links:
$("#navigation").on("click", "a", function(e){
e.preventDefault();
$("#content").load( $(this).prop("href") );
});
Which works with the following markup:
<div id="navigation">
Home
Gallery
</div>
<div id="content"><!-- content will load here --></div>
Considering that you want one page with all of the content, you could simple hide all but one main div with css, and then use javascript/jQuery to show one div when a tab is clicked, and hide all of the other (main divs).
Have your navigation links change the html of your center div
<a href="#" onclick="$('#centerDiv').html('your content');">Click me<a>
if you want it to be more dynamic use ajax to load it.
and if you want to get a bit more fancy try out the Tab widget
This calls for the jQuery load() function! Go to http://remysharp.com/jquery-api/ and search for 'load' -- you just need to target the div.
By the way, this is sort of an alternative to frames or server-side includes. The only bad thing about this approach is that Search Engines won't be able to follow your links.
Using ajax with jQuery its pretty simple and totally controllable:
$('#navlink').click(function() {
$.ajax({
type: "GET",
url: 'URL_OF_THE_RESOURCE',
//(maybe you can hold this in the href attr of the anchor tag)
//in that case you can use $(this).attr('href');
dataType: "text/html", //spectating HTML back from the server
timeout: 8000, //Wait 8 second for the response
error: function() {
alert('ERROR');//case of server error or timeout give a feedback to the user
}, //end error
success: function(html) {
$('#mainDiv').html(html); //Replace the content with the new HTML
} //end succes
}); //end ajax
return false;
}); //end click
Instead of usign an ID, you could use a dummy class (like "navlink") on all those navlinks, so instead of referencing the selector to the ID, reference it to the class like:
$('.navlink').click(function(){
...
and the url parameter will be:
url: $(this).attr('href'),
That way you just set this once and all the links will get the functionality and still give support to users that don't have JS active.

Categories

Resources