jquery load function for a div not working - php

I just want to alert 'OK' when a div with id="Box" loads. But load function is not working. Here is my code in wordpress. I have included the jquery library and other jquery is working fine.
jQuery(function(){
jQuery( '#Box' ).load(function() {
alert('ok');
});
});

It does not work with DIV elements:
See: https://api.jquery.com/load-event/
"The load event is sent to an element when it and all sub-elements
have been completely loaded. This event can be sent to any element
associated with a URL: images, scripts, frames, iframes, and the
window object."

Question:
I just want to alert 'OK' when a div with id="Box" loads. But load function is not working.
You are using .load().
Answer A : This method will not work with a div.
Answer B : This method was deprecated in jQuery 1.8. Stop using it!
This method is a shortcut for .on( "load", handler ).
The load event is sent to an element when it and all sub-elements have
been completely loaded. This event can be sent to any element
associated with a URL: images, scripts, frames, iframes, and the
window object.
https://api.jquery.com/load-event/
Possible solution:
Use the shorthand method .ajax(), .load(), .get to load content and trigger your stuff in the callback function or success handler.
.load() Load data from the server and place the returned HTML into the
matched element.
http://api.jquery.com/load/
Example 1
Specify what to load in the first parameter and act in the callback function. The content of test.html is loaded, after that it's inserted into #box and the alert is fired.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
Example 2
Ajax Example with load alert:
$.get("ajax/test.html", function(data) {
$("#box").html(data);
alert("Ok. Load.");
});
You are loading test.html the content is returned as data. It is assigned as new html content to the dom element #box. Then you fire the alert.
Example 3
The alternative is using the .ajax method and define a success handler:
function getData() {
$.ajax({
url : 'test.html',
type: 'GET',
success : alert('Ok.Loaded')
});
}

Related

jQuery toggle function stops working after AJAX HTML data load

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.

Jquery load Php file

Am currently using a Jquery load function to load php content into Div. But when I use my php e-mail form it turns all white an the index page is lost(the main layout I mean). Is there anyway I can use Jquery to load Insch.php back into the div even when it needs to be executed?
<form id="contactform" method="POST" action="insch.php"> <--- this is my Form
$('.menut').click(function () {
var phpFile = $(this).attr('id') + '.php';
/* alert(phpFile)*/
$.get(phpFile, function (data) {
$('#box1').html(data);
});
return false;
}); <---- my Jquery load function(on index)
I see you add returning data directly into $("#box1"). If your php file returns Html you should set dataType:'html' in the ajax request.
Sorry, your question is kinda hard to understand. I'm kinda guessing, but it sounds like you're asking how to submit the form without the page refreshing. If so, you could do something like this:
$('.menut').click(function() {
var phpFile = $(this).attr('id') +'.php';
$('#box1').load(phpFile, function() { // <-- this is your ready function
// once the form has been added to the page,
// add the 'submit' event listener
$('#contactForm').submit(function(e) {
// prevent the form from submitting regularly (causing a page refresh)
e.preventDefault();
// get the data from the form
var data = $(this).serialize();
// submit the form via AJAX and put the response in #box1
$('#box1').load($(this).attr('action'), data);
});
});
});
UPDATE:
Your ready function is the function you create in your AJAX call to be executed when the content is done loading (when the content is ready). It may also be called a callback function, complete function, or a success function.
Take a look at the comment I added on the fourth line of code above. I have pointed out what I'm referring to as your ready function.
In your question, you used this:
$.get(phpFile, function (data) {
$('#box1').html(data);
});
Which is equivalent to:
$('#box1').load(phpFile);
This loads the response (your form) from phpFile into #box1. The function (data) { ... } is your ready function. That is where you should bind the submit event to the form.
If you switch to the load() method as I am suggesting, then you would just pass a new function (which will be your ready function) as the second parameter to the load() method, which is the solution I've given in my original answer.

Why does my JQuery script seems to only works before beginning to browse my tabs if the content of my tabs is the same everywhere?

Why does the JQuery script I use in all my pages seems to only works before beginning to browse my tabs if the content of my tabs is the same everywhere ?
I have a tab view web page built with JQuery and AJAX.
This is my JQuery functions:
$(document).ready(function(){
$(".box .more").click(function(event){
alert('test');
});
$("a.linkTab").click(function(event){
var tabID = $('.linkTab')[0].toString().split('#')[1];
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
}
});
});
});
This is my body web page:
<div id="header">...</div>
<div id="body">
<div class="box">
<p class="more">LinkLike</p>
</div>
</div>
<div id="footer">9</div>
loadPage.php only include needed page that Ajax script sent.
My tab system works perfectly, I can navigate in the page I want. Before navigating, When I click on the LinkLike, the alert appears. But, when I browse tabs, When I click, there is nothing.
Why does the JQuery script seems to only works before beginning to browse.
Important, the file I imports from php contains exactly the same body than the first one. The file contains:
<div class="box">
<p class="more">LinkLike</p>
</div>
try
$(document).delegate(".box .more","click",function(event){
alert('test');
});
the reason probably is you can generating the link dynamically, and event handlers do not attach themselves to the dynamically inserted elements to the DOM. Previously .live was used but that now is deprecated, if you are using jquery version 1.7+ you can use the .on method or else you can use the delegate method to attach the event handler to the dynamic content. However you can also re-bind the events in the success callback of ajax request
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
$(".box").bind("click");
}
});
jQuery.on version1.7+
jQuery.delegate
You are replacing the entire body of the page when your click event fires; therefore, you will need to re-bind your click events once the new content is loaded.
$(document).ready blocks will only fire when the initial document loads, so the AJAX-ed in content will not cause the click events to be bound again, you'll have to do this in the success callback of the click event that replaces the body content.
function init() {
$("a.linkTab").click(function(event){
var tabID = $('.linkTab')[0].toString().split('#')[1];
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
init(); // re-bind events again
}
});
});
}
NOTE: This method will work, but it's probably a bit naive. Check out this jQuery page for more details on how to use the "delegate" jQuery method. The delegate method will bind click events both now as well as in the future.
Here is an example using "on", which supersedes "delegate" as of jQuery 1.7+:
// I'm not sure if you're referring to "body" the body tag or "body" the id of your div.
// Please adjust accordingly.
$("body").on("click", "a.linkTab", function() {
var tabID = $('.linkTab')[0].toString().split('#')[1];
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
}
});
});

How to Make a Ajax Call from inside an Div That Has Been Called By Ajax?

I Have a PHP page that is like this:
Here is the Schematics:
http://img233.imageshack.us/img233/4895/13423274.jpg
In DIV 1 And DIV 2 i made Ajax calls for Content. The Ajax Calls Are made from the main Page.
If i want to make a call From DIV 1 to change DIV 2 it doesnt Work =/
I Tried:
document.getElementById('div2').innerHTML = data;
Can Anyone Help Me? Thankyou!
An id cannot start with a number, so that could lead to problems.
Apart from that it depends on where your javascript is located and how and when you attach it to your event handler.
If the javascript is included in the code that is loaded in DIV 1, there shouldn´t be a problem, but if it already is on the page, you need to attach it to the newly loaded DIV 1 as soon as it´s loaded.
See for example the jQuery .live() function documentation for a detailed explaination of what I mean.
So in DIV1's content you have some links that, say, want to load content in to DIV2? What you'd need to do then is add event listeners to the links in DIV1 so that when they're clicked they'll created AJAX calls that load content into DIV2.
I'd recommend using jQuery (http://jquery.com/) and you can do something like this:
// getting the content into DIV1
$( '#div1' ).load( '/path/to/backend.php', function()
{
// the ajax request is complete, so let's add listeners to the a tags in DIV1
$( '#div1 a' ).click( function()
{
// this clears DIV2's content
$( '#div2' ).empty();
// and now we load some ajax by getting the href of the a tag and passing that to our backend
$( '#div2' ).load( '/path/to/backend.php', { page: $( this ).attr( 'href' ) };
});
});
You can read more here: http://api.jquery.com/load/

Using jQuery 'click' function that was loaded with Ajax content?

I have the contents of a php file loaded via Ajax that contains HTML and JavaScript. I have a button:
<button class="search_button">Search</button>
And I have a script underneath that will update the documents hash from a jQuery function
<script type="text/javascript">
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
</script>
This code works when I run the php file separately, but when loading this page from an Ajax call, the function no longer runs. In firebug the script is not present so I am assuming I cannot load a script in using this method. I tried also putting the JavaScript snippet instead a header for the whole website, but this failed also.
I was also thinking perhaps the function has to be declared when there is a search_button class already present, but it was structured in this way when I previously had them in one file (that was retrieved via Ajax) to no avail so I'm confused as to the problem.
You can include it globally with a live event:
$(".search_button").live('click', function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
jQuery will automatically evaluate script blocks, you cannot see the function in the HTML because it has been stripped out. However it should have already run. The problem is most likely timing. You could do something like
setTimeout(function(){
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
}, 500);
So that when the script is loaded it waits to be executed (hopefully giving jquery time to update the DOM with the new element).
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.
Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:
$(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+
Example usage of .on() to bind click event
$(document).on("click", "#post a", function(){
alert("1");
})
Try to add the script inside a function
function name(){
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
}
and call this function just after the end of the ajax call.
$(document).ready(function() {
name();
});

Categories