I have a website with some AJAX on it, basically the users clicks on a link, and some AJAX goes and fires a method that returns some HTML as show below, as the title says the data that is returned does not seem to be going into the HTML, is this why my accordions are not being made? It is strange becuase results are being returned because they out put onto my screen.
$(document).ready(function() {
// hides the main_menu as soon as the DOM is ready
// (a little sooner than page load)
$('#main_menu').hide();
// shows the slickbox on clicking the noted link
$('h3#show-menu a').click(function() {
$('#main_menu').toggle('slow');
return false;
});
//try and hide the left content when it is null
$("#left-content:empty").hide();
//style up the scroll bar
$('#left-content').jScrollPane();
//do some AJAX to call the method instead of the browser
$("a.navlink").click(function (ev) {
$(this).toggleClass("active");
ev.preventDefault();
var id = $(this).attr("id")
if ($(this).hasClass("active")) {
$("."+id).remove();
}
else {
//$(this).toggleClass("active");
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "GET",
success : function (html) {
$("#accordion").append(html);
$('#accordion').accordion({
active: 0,
header:'h2'
});
//alert(accordion())
}
});
}
});
});
As I am sure you can gather from the code, the returned HTML is appended to the <div id="accordion> and then it is 'turned' into an accordion, however this is not happening, all I get are the classes getting added to the div that would give accordion functionality but I get no real functionality.
I noticed that when I view source whether or not the AJAX has fired there is no content in <div id="accordion> even though I can see the returned data, how can I get the accordion to work?
=======What gets returned by the AJAX======
?php
if(isset($content)) {
// var_dump($content);
foreach($content as $row) {
print "<h2 class='$row[category_name]'><a href='#'>$row[category_name]</a></h2>";
print "<div class='$row[category_name]'>$row[content_title]</div>";
}
}
?>
=========Where the AJAX html goes=========
<div id="right-content">
<div id="accordion"></div>
</div>
View source shows the source code of the file your machine downloaded, ie. the file BEFORE any AJAX changes. No matter what you do in Javascript, nothing will ever change in view source (unless of course you go to a new page).
If you want to see how the current DOM looks for your page, you need to use a tool like Firebug or the IE Developer toolbar.
Actually you don't need Firebug from Firefox but firebug is a fantastic tool.. Select the field you think should change, right click and select "View Selection Source" (Firefox only).
Related
My menu links uses a jQuery script to load various HTML scripts into a div on an index.php page. Menu item 'Info' puts in sectionInfo.html into the index.php page. This script contains a short form and can bring up an alert() to the user if they misuse the form. But when the alert is accepted the page reloads to the default index.php and then the user has to select Info from the menu again to return to where the form is. How can I re-load the correct div again from the alert?
jQuery script for the menu links:
$('.trigger').click(function(){
var url = $(this).attr('href');
$('#target').load(url)
The menu link:
<ul>
<li>
Info
</li>
</ul>
The Alert:
function validateMyForm1() {
alert("Alert goes here ");
window.location = 'href="sectionInfo.html" class="trigger"';
}
The div in the body of the index.php
<div id="target"></div>
I have checked other posts and tried various alternatives. Please help and if you down click me please tell me why as I have been down clicked often and don't know why. Thank you.
https://codereview.stackexchange.com/questions/64192/loading-div-sections-from-separate-files
calling jquery from a javascript function
Go to URL after OK button in alert is pressed
The jQuery script is part of longer script which I include in this edit: The lower part of which slide down text the html files.
$('.trigger').click(function(){
var url = $(this).attr('href');
$('#target').load(url, function() {
$('#faqs h1').each(function() {
var tis = $(this), state = false, answer = tis.next('div').hide().css('height','auto').slideUp();
tis.click(function() {
state = !state;
answer.slideToggle(state);
tis.toggleClass('active',state);
});
});
});
return false;
});
A couple of issues in your JS, in your first example you need to call preventDefault() on the event to stop the link being followed:
$('.trigger').click(function(e) {
e.preventDefault();
$('#target').load($(this).attr('href'))
});
In the second code sample your string location is entirely wrong, you just need to set the URL to go to as a string. Personally I prefer to do this using the assign() method, like this:
function validateMyForm1() {
alert("Alert goes here");
window.location.assign('sectionInfo.html');
}
I'm trying to have a single page that can show the same type of data (lets say fruits). Then I want to load this page anywhere in my website hierarchy but each time with different parameters.
I have my main page like the following with two links to the same page show.html:
<div data-role="navbar" data-iconpos="top" data-theme="a" class="nav-ecommera">
<ul >
<li>
Apples
</li>
<li>
Oranges
</li>
</ul>
</div>
A click on each of the two buttons will create a new instance of the page show.html in the DOM. All of the items in show.html therefore will have duplicate ID's in the DOM.
In my javascript I want to dynamically fill the show.html page:
$('div[id="show"]').live("pagebeforeshow", function(e, data) {
var p = getUrlParameter("p");
show(p);
});
var show = function(p) {
$.ajax({
url:'http://show.com/?p='+p,
success: function(data) {
// Refresh 'show' page with new data
// First time: It's fine.
// Second time: 'show' page is duplicated in the DOM so it's messy.
}
});
}
Now the first time show.html loads everything is fine. However the second time everything in show.html is loaded twice and the DOM includes many duplicate ID's.
Is there a way to remove the first page from DOM before loading the new one?
Or:
Is there a better approach that will do what I'm trying to achieve here?
UPDATE:
I already tried removing previous instances of show pages when loading a new one. It works as far as showing the second page is concerned. But there is a problem when the first page needs to be shown for the second time, after being manually removed.
I think the reason is jQuery mobile seems to think the first page is already loaded, despite the fact that we manually removed it. So it doesn't fully reload the first page when accessed again. I'm talking about this sequence of navigation: Home -> Apples -> Back to home -> Oranges -> Back to home -> Apples (Here you get a defected page).
1) You could change ID`s to classes.
2) You can have wrapper that encloses the show.html and when you try to load it second time find the one you loaded previous and delete it.
Your show.html:
<div class='previous-load'>
... enclosed show.html HTML ...
</div>
JavaScript:
$('div[id="show"]').live("pagebeforeshow", function(e, data) {
var p = getUrlParameter("p");
show(p);
});
var show = function(p) {
$(".previous-load").remove();
$.ajax({
url:'http://show.com/?p='+p,
success: function(data) {
// Refresh 'show' page with new data
// First time: It's fine.
// Second time: 'show' page is duplicated in the DOM so it's messy.
}
});
}
You can load the show.php page via $.mobile.changePage() which has the reloadPage option:
//bind to all links that have an HREF attribute that starts with "show.html"
$('a[href^="show.html"]').bind('click', function () {
//set a default query-string for the page-load
var query = '';
//if this link's HREF attribute has a query-string, use it
if (this.href.indexOf('?') > -1) {
query = this.href.split('?')[1];
}
//forward the user to the page, telling jQuery Mobile to reload the page
//which will use the new query-string sent
$.mobile.changePage('show.html', { reloadPage : true, data : query });
//prevent the default behavior of the click
return false;
});
reloadPage (boolean, default: false)
Forces a reload of a page, even if it is already in the DOM of the
page container. Used only when the 'to' argument of changePage() is a
URL. Here is the documentation for $.mobile.changePage():
Source: http://jquerymobile.com/demos/1.1.0/docs/api/methods.html
When jQuery Mobile loads the same page twice it's because the URL in the HREF attribute does not match the data-url attribute on the pseudo-page elements. For debugging this issue, make sure to check what data-url attribute is being added to your show.html page as it's inserted in to the DOM. If it doesn't seem to match-up, then you can set a data-url attribute on the element like:
<div data-url="/show.html" data-role="page" id="show-page">
...
</div>
Then you would always link to the page using the URL: /show.html
I have an element containing data from an AJAX request. The AJAX data is returned from another page. The returned data in the element contains a link, which when clicked, opens a jQuery overlay. The onclick event is attached to the link (a onclick="...") from the external data, and the overlay function is on my main page.
This all works fine until the user clicks the link which opens the overlay. When the overlay is closed, the link becomes disabled, losing its onclick event, and the overlay cannot then be reopened.
Is this a focusing problem or do I somehow have to rebind the event to that link? I'm not sure what is going on here, or how to fix it, I hope some kind person can help me out.
This is what loads the external data in to the element:
function load_upload_queue() {
$.ajax({ type : 'GET', url : myDomain,
dataType : 'html',
success : function(data) { $('#myElement').html(data); },
error : function() { // do something }
});
}
This is the link inside of the element, which comes from AJAX call above:
<a onclick="show_error_overlay(id)">Show Errors</a>
This is my open overlay function, sitting on the main page:
function show_error_overlay(token) {
$("#show_error_overlay").overlay({
mask: '#111111',
close: "a.closeOverlayBtn",
closeOnClick: false,
closeOnEsc: false,
load: true,
onLoad: function() { // do something },
onClose: function() { // do something }
});
}
Any help gratefully received, any questions please do not hesitate to ask :)
I would use Firefox+Firebug to monitor whether that A tag is being touched (moved, changed) by anything as the overlay opens and closes. See if it maintains the same position; most importantly, check if it still has the onclick value after the overlay goes away. Inspect your "do somethings" in onLoad and onClose for any code that may be doing something to that link. Also, check for JS errors, especially during/after closing the overlay - sometimes errors interrupt the process, leaving unrelated things in unexpected state, causing unrelated problems.
I have an issue on a website where a page content (results) are updated via AJAX. Contained within this AJAX returned content is a script tag which renders the LinkedIN "share" button.
When the page first loads with the initial resultset the layout looks like this:
Each of these buttons is within a left-floated div, and the HTML looks like this in Chrome developer tools:
As you can see the script tag is appearing where it is supposed to be, in the div, and the dynamically generated span containing the button is just above.
Now, when i append more results via an AJAX request, things go a bit haywire, and look like this:
As you can see the LinkedIN button is way out of place, and the reason is apparent when looking at the HTML in developer tools:
The script tag is not within the div where it appears in the code file, instead appearing after the closing tr tag - and the span with the button is just above.
So, why is this, and more importantly what can be done to ensure that the script tag is where it belongs so that the layout is correct?
FYI - At the foot of the body is javascript which loads the LinkedIn .js file and after the AJAX request for more results completes there is an invocation of the LinkedIn .parse() method which is supposed to parse the full document and render the buttons.
EDIT
The application is built using ASP.NET MVC and the response returned uses the same .ascx control to format the results as the initial page load does.
EDIT - AJAX request used to retrieve extra data
function LoadMore(uri, last, loader, end)
{
isLoading = true;
$(loader).show();
$.post(uri, function(data)
{
if (data != "")
{
$(last).after(data);
isLoading = false;
// re-do social media share initialisation on the new AJAX-added content
gapi.plusone.go('container');
twttr.widgets.load();
FB.XFBML.parse();
IN.parse(document.body);
}
else
{
$(end).show();;
}
$(loader).hide();
});
}
EDIT
The actual HTML returned from the server is correct. Viewing the source shows the script tag in the correct location, but viewing the page in Chrome developer tools, as shown in the images above, shows the script in the wrong place in the DOM. This occurs in both IE9 and Chrome.
Are you building the html dynamically ? Maybe it has something to do with misconfigured callbacks. If you are using $.ajax({...}), make sure that the next iteration is specified into the "success:" property to prevent unordered render.
Use ajax call like this
$.ajax({ url: 'url',
type: 'POST',
data: json,
dataType: 'json',
contentType: 'text/html',
success: function (data) {
//you response will be data
}
});
I'm trying to replace all the HTML (including the HTML tags) with another page. What I'm trying to do is having a website acting as an app even when navigating the another page.
Here is the code :
(function($) {
Drupal.behaviors.loadingPage = {
attach: function(context,settings) {
$('a').click(function(event) {
event.preventDefault();
// Create the loading icon
// ...
$.ajax({
url: $(this).attr('href'),
success: function(data) {
$('html').replaceWith(data);
}
});
});
}
};
})(jQuery);
I've tried several things. replaceWith() causes a jQuery error in jquery.js after deleting the HTML tag, I guess it is because it can't find the parent anymore to add the replacement.
The best result I got was with document.write(data). The problem is, the javascript code on the loaded page is not executed.
Anyone got a better idea ?
A better idea? Yeah, just load the new page normally by setting window.location instead of using AJAX. Or submit a form.
Otherwise, if you want to load something to replace all of the visible content of the current page but keep the current page's script going, put all the visible content in a frame sized to fill the browser window - which, again, you wouldn't populate using AJAX.
(I like AJAX, but I don't see why you'd use it to replace a whole page.)