I have created a menu which is simply a series of DIVs and am using the following code
$(".menu_item").click(function(){
window.location = $(this).attr("data-href");
return false;
});
to make the entire DIV for each item clickable. I have a "container" DIV setup with content initially loaded via php-include, but want different content to load when a different menu item is clicked.
I know I can use JQuery.load to target the loading of an external file into a sepcific DIV but it looks that would mean coding separate instances of jquery for each link? I would also rather stick to using php includes if possible. Can I use jquery.load to load via php include?
Any help on how to achieve this would be appreciated.
Here's the rest of the code:
/* Menu Item */
<div class="menu_item" data-href="link1.html">
Link 1
</div>
/* Container to load link into */
<div id="myContentDiv"></div>
You can use the jQuery AJAX shorthand method load() which makes the ajax request and on completion populates the element with response
$(".menu_item").click(function(e){
var url= $(this).data('href')
$('#myContentDiv').load( url);
return false;/* edit to prevent browser following link*/
});
API Reference: http://api.jquery.com/load/
$(".menu_item").click(function(e){
e.preventDefault();
$.ajax({
url: $(this).attr("data-href"),
context: $('#div-to-replace-content')
}).done(function(data){
$(this).append(data);
});
});
Related
I have a simple PHP file with some HTML (got a list in the form of UL>LI>UL>LI, which uses the toggle() function. The function opens the ULs and shows or hides the LIs). The page also has an input form that works correctly (adds data to the database).
Once the AJAX form has been successful, I delete the entire div and reprint it from the database.
My problem: once the new page is printed, the toggle() function stops working until the page is refreshed.
The toggle function (in external JavaScript file):
$(document).ready(function() {
$(".product_category").click(function(event) {
event.preventDefault();
$(this).find("ul > .product").toggle();
});
});
The form:
<form id="addPForm">
<section id="product_input">
<input id="list_add_product" type="text" placeholder="Add a new product" onkeyup="checkProducts()">
<input id="list_add_product_button" type="button">
</section>
</form>
The form sending function:
$("#list_add_product_button").click(function(event){
var txt=$("#list_add_product").val();
$.ajax({
type: "POST",
url: "addproduct2.php",
cache: false,
data: {product: txt},
success: onSuccess,
error: onError
});
// IF THE SUBMIT WAS SUCCESFULL //
function onSuccess(data, status)
{
console.log(data);
clearInput();
$('#main_list').empty();
$('#main_list').html(data);
}
function onError(data,status){
// something
}
});
What I get printed in the console.log(data):
<div class="product_category"><li id="baked" onclick="showBakedList();"><a class="list_text" id="baked_text">Baked [2]</a></li><ul id="ul_baked" class="inner_list"><li class="product" id="bread"><a class="liText">Bread | 0 Unit</a> </li><li class="product" id="croissant"><a class="liText">Croissant | 0 Unit</a> </li></ul>
Now, the toggle() function works great before I add a product. The lists opens and closes without any problems. I do not get any errors in the console and I load jQuery in the page head (first item).
I would like to note that looking at the source code before and after the code print looks exactly the same, except the new additional LI that is printed.
Am I missing something? Do jQuery functions stop working after a div data refresh?
If your element is been removed after click event binding, it will not call the event handler function.
Use $.on() insted of .click():
$(document).on('click', '.product_category', function(event) {
// Your function here
}
Explained:
$(".product_category").click() binda a function to the .product_category elements at that moment. If one or all elements are removed, then the event bind also will be removed.
$(document).on() will bind an event to entire document, and will filter every click to check if the click occurred in a '.product_category' element.
Try this:
$(document).ready(function() {
checkForDOMElements();
});
And a function...
function checkForDOMElements(){
$(".product_category").click(function(event) {
event.preventDefault();
$(this).find("ul > .product").toggle();
});
}
In your AJAX request, after success add:
checkForDOMElements();
Does this work for you?
The main problem is this:
When you load page you have one DOM tree with all elements. Javascript save this DOM. After this you remove all elements from DOM tree and load new. But for javascript the elements are only removed and js can't detect new elements for your toogle() function..
You have to reload javascript function to refresh new DOM tree (new HTML) with new elements.
I found this solution while having the exact same problem. I am building a complex webtool that uses Ajax/JSON that contains HTML with JS events built into the JSON.
To be more fine grained on the calls, I wrapped each specific JS event that had to do with the specific Ajax/JSON HTML replace and call it on load as well as after the AJAX success.
If there is a more "up to date" way of doing this, I would love to hear about it, but this worked GREAT for me.
I am redoing my site and have at any time 80-120 vehicles, all identified in my db by their unique stock number. I'm using jQuery's accordion to list the vehicles:
http://www.login.carcityofdanbury.com/New/?cat=01
How do I embed edit.php?stock=__STOCK__ into the div of the open accordion, once the accordion opens?
I tried just using just an HTML <embed> tag, but it is making the page load extremely slow.
I am new to the whole jQuery, Ajax, coding thing and am completely a self taught "learn as I go" guy, so a demo, tutorial or example would be great.
You could use a combination of jQuery .load function (http://api.jquery.com/load/) and the jQuery UI Accordion change event (http://jqueryui.com/demos/accordion/#event-change) which gets triggered after an accordion slide opens:
$(document).ready(function(){
$("#listVehicles").accordion({
collapsible: true,
active: false,
autoHeight: false,
change: function(event, ui){
ui.newContent.load('edit.php', { stock: __STOCK__ });
}
});
});
When the change event is triggered, the edit.php file is loaded using AJAX and the HTML is dropped into the opened accordion slide.
You could get some help here:
http://api.jquery.com/jQuery.ajax/
Example:
$.ajax({
url: "yourPage.php",
success: function(data){
$("#youarea").text(data);
}
});
I would recommend using the jQuery load() function which is designed for this specifically. You give it an element, and a url and it will load the content into the element.
So, in your Accordion handling code, you'll want to place the following:
$('#elementToLoadInto').load('edit.php?stock='+id');
From there, your PHP page should server up a single (or multiple if needed) <div> element, not a full HTML page. That content will be placed into #elementToLoadInto exactly as it is, just like it was coded there.
jQuery can also load only a piece of the page, so you could also take advantage of that functionality if you need to return a full HTML page for some other reasons.
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.
I have 2 php pages named "personal_info" and "portfolio". I load them via php functions in codeigniter http://www.mysite.com/controller/personal_info and http://www.mysite.com/controller/portfolio.
I have a page with menu tabs linked to personal_info and portfolio and I want to load the pages via ajax when a tab is clicked. If js is turned off in the browser the tabs should just go to the url.
I am using the jquery .load() function to load the pages.
<script type="text/javascript">
$(document).ready(function(){
$('#personal_info').click(function() {
$('#result').load('personal_info #load'); //load fragments from #load div
});
$('#portfolio').click(function() {
$('#result').load('portfolio #load');
});
});
</script>
HTML
<div id="tab">General Info</div>
<div id="tab">Portfolio</div>
<div id="result"></div>
Issue: When I click on a tab it treats it as a link and goes to the URL instead of loading the page via jquery. How can I disable the link if javascript is on? Also, I noticed that javascript is not loaded from fragments in the pages, and if I put the javascript in the page I load data it doesn't pick it up.
What is a good solution for this?
EDIT:
For loading js, I just wrapped the entire page in the result div and am loading the other pages with the js and header, footer.
For the first issue: put return false; at the end of each 'click' function:
$('#personal_info').click(function() {
$('#result').load('personal_info');
return false;
});
Edit: For the second issue, maybe pull out any jquery/javascript and run it from a central application.js file?
You need to prevent the default action of the <a/> element. You can accomplish this by using event.preventDefault()
$('#personal_info').click(function(e) {
$('#result').load('personal_info');
e.preventDefault();
});
$('#portfolio').click(function(e) {
$('#result').load('portfolio');
e.preventDefault();
});
To stop the default action from occurring (following the link) you need to use return false at the end of your jQuery click() functions.
With regard to your second issue ("javascript is not loaded from the [dynamically loaded] pages"), ensure that you are using jQuery's .live functionality to attach handlers.
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.