How to initiate javascript in jQuery ajax-loaded content in IE8 - php

I'm facing a trouble with jquery ajax under IE8. I have a form which at the base level displays a list of few items, each with buttons to edit and remove. The list, along with those two buttons, is loaded via jquery ajax call. Although it works fine on Firefox and Chrome, on IE8 it won't trigger functions behind edit or remove buttons.
So basically, on a base page, jquery works and loads the list. Within that list tho, jQuery doesn't work as it won't trigger edit or remove functions
I have a similar problem with the modal window call. IE8 is able to open the modal window (content is loaded with jquery ajax) but won't trigger any function within the content of the modal
Example of a simple call
$('#form-modal').load('/form/' + path + '?id=' + id).modal();
This works on IE8 from the base page, but doesn't when triggered within ajax-loaded content
All js scripts definitions are being loaded in the <head> of the main base page. I tried adding definition to the ajax-loaded file header, but didn't help so it must be something else
Any ideas? If you need more details, will gladly provide
Let me show you the easiest example. Each item on the list loaded with ajax has a 'remove' button.
Remove
DeleteItem definition is in external lib.js file
function deleteItem(id){
$.ajax({
type: "POST",
url: "/ajax/deleteitem.php",
data: "id=" + id,
success: function(msg){
loadItemsList();
}
});
}
This is it... That simply doesn't work on IE8... Nothing happens, not even javascript error. Same thing works no problem on Firefox and Chrome

It would be nice if you show the event handlers for those buttons, since if you're using bind(); for example, it loads when the dom is ready, and your ajax call is made. That means that the dom elements loaded through the ajax call wasn't there when bind was called to bind the buttons.
The solution to this is to use live();
$(".button").live("click", function () {
// do stuff
});
I don't know what event binder you're using, but if you're using anything other than live, you could try live and it should work.
EDIT
Read my comment first on the alert(id), if your function doesn't run at all in IE8, try doing this instead. Give the link element the id instead like this
<a id="item_10" href="#">Remove</a>
Then somewhere in your javascript
$("document").ready( function () {
$("a").live("click", deleteItem);
});
function deleteItem (event) {
event.preventDefault();
var id;
id = $(this).attr("id").replace("item_", "");
//this will now provide you with the current id
console.log(id);
your ajax-stuff here..
}
This should work in IE8, no problem. You might wanna specify the selector though for the click event by giving all the delete links some class or something.

Related

Javascript not executing after Ajax call

I know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I'm working on a Wordpress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think - if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won't work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being 'connected' to the JS anymore but I'm not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you're probably going to ask what I've already tried, but if I'm honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn't currently work after the Ajax call). The script is started by the standard $(document).ready(function() { statement.
Thanks for any help :)
First, you need to accept the event object as an argument.
$(".page-feed").on('click', '.post-nav>a', function(event) {
Next, by using the jQuery event object, you can simplify the next line because event is normalized by jQuery to work cross-browser.
event.preventDefault();
Now, as far as it working on the first click but not after, that's likely because .page-feed is a dynamic element. You'll need to instead select an element that is an ancestor of .post-content. document is a decent replacement, but it would be better if you picked one more local.
$(document).on('click', '.post-nav>a', function(event) {

jQuery scrollbar plugin not working on Ajax loaded content

The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.

Can't do anything with .load()-ed content in jQuery?

I'm facing an interesting problem where everything works flawlessly. I console.log every step and it plays out just the way it should. But! I have a #div into what I .load(a-file.php). Now that "a-file.php" includes HTML mark-up as well, more specifically certain links that I'd like to make "active" onload.
Scenario; page load happens, Javascript loads and loads a file into the div. That div now has tabs and I'd like the first tab to be in an "active" state which requires me to addClass('active');. But the following seems to have no effect
$('#content').load('file.php'); // works.
$('#content a[rel="weird-page"]').addClass('active'); // does not work.
Any kind of help, even remotely nailing it, is appreciated.
change to:
$('#content').load('file.php', function() {
$('#content a[rel="weird-page"]').addClass('active');
});
jQuery load() works asynchronously and therefore your addClass() method is being called before load() has completed.
Using the load() callback function it will ensure your content has loaded:
$('#content').load('file.php', function() {
$(this).find('a[rel="weird-page"]').addClass('active');
});
shameless-plug-warning: I wrote a blog post about jQuery callback functions which you might find useful.

Loading pages into a div with JQuery, existing Javascript not working

I have a page I'm working on where a user clicks a link and it loads a new php file into an existing div. It works but the page that loads into the div will not function with existing Javascript stuff in the page.
I can include the
<script type="text/javascript" src="js/admin.js"></script>
into the loaded pages but when you flick back and forth between the pages I notice that RAM usage starts to go up and up, so I don't think this is the best way of doing it.
Any ideas how the loaded page can function with the already-loaded javascript from the index page?
Thanks!
bind your events like this :
$(document).on({
"event" : function(e) {},
...
}, "selector");
If you are using bind or click type events change to using something like on (or live or delegate if you are required to use jquery version less than 1.9)
OR/AND
In your function that loads in the page via ajax provide a call back that initiates only what is needed. Example:
$('#myDiv').load('ajax/page.php', function(){
$('#myDiv a').customPlugin('whatever');
$('#myDiv button').bind('click', function(){
window.open('http://www.google.com/', 'some-window');
});
});

php javascript partial page reload

I have a page set-up, with several divs.
For now all we need is
<div id="main">...</div> & <div id="sidebar">...</div>
Each div has code such as:
<?php include("page.php") ?>
The main div does all the work, and includes a JavaScript function. E.g. at the moment the user can click a button to remember an item displayed in a table.
Am I able to only reload the sidebar instead of the whole page when the user calls this function?
I am posting the function here, and all I need now is to be able to refresh the sidepanel and its included php files if that is possible? I assume something along the lines of this could do the job? or am I wrong? load("#sidebar")
function saveToFavorites(code)
{
$.ajax({
async:false,
type: "POST",
url: 'formPostsUser.php?reqtype=addToFavorite',
data:'coursecode='+ code,
success: function(data)
{
$('.result').html(data);
if(data != "")
{
alert(data);
load("#sidebar")
}
}
});
}
Kind regards
Alex
Happy about any and every reply and hint ;)
First thing
<div="sidebar">..</div>
The above markup is wrong HTML. You should give the sidebar as the value of your properties such as id or class
<div id="sidebar">..</div>
Loading the Sidebar content
You can use jQuery ajax to load content of this div using jQuery load method like this
$(function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
Assuming yourPHPPageToReturnSideBarContent.php is the PHP page which renders the HTML Markkup for the sidebar. Note that this will load the content on the document ready event.
Loading the side bar content on an event
If you want to load it on a purticular event like a button click you can do it like this
$(function(){
$(document).on("click","yourButtonId",function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
});
The above script will load the side bar content on a button click. The button's id is e "yourButtonId" in this example.
Note that i used jQuery on here to bind the function because it will take care of current element and future element in case if you want to load the markup which contains the button dynamically.

Categories