page fetched by AJAX cannot execute any javascript - javascript

I have been with that a whole day..
I have a home page(index.php) and i have a small menu in it(made up of buttons) and a <div id=tab_contents></div>
i have used AJAX in such a way that whenever i click on any of these buttons, another page is loaded in the tab_contents-div.ie:home_tab0.php, home_tab1.php, home_tab2.php for each button respectively.
The page that i want to fetch with ajax should contain a <body onload=initialize()> ...</body> function.or it can contain a javascript code snippet to trigger the initilization() function.
that is when the button is clicked,the page lets say home_tab0.php is loaded, codes inside the home_tab0.php should trigger the initialization() frunction.
i have tried every possible way in my knowledge to make it work but without success...:(
please if i can get any help for this i would be so grateful.

With jQuery it's easy to call any function after the ajax call has returned, and data is loaded. I guess that's what you want to do. There are a few examples here:
http://api.jquery.com/jQuery.get/
E.g:
$.get('home_tab0.php', function(data) {
$('#tab_contents').html(data);
initialize();
});

This is a common problem. I recommend using jQuery and letting it take care of this for you. Reimplementing what they've done would be a waste of your time.
http://api.jquery.com/load/
$("#tab_contents").load("http://www.foo.com/loadContent");

Related

Commenting System - Showing posted comment without page reload

working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)

Using jQuery to bind an event to AJAX content

I have a menu that is AJAXed in, thus loads later than the actual page. I would like to know if there is a way to bind an event to the surrounding div (the container div of logged in information).
Basically the container is empty when jQuery(document).ready() runs and gets populated 1-2 seconds after. I would like to run some scripts when this happens - and I'd rather not put the script into the AJAXed content itself.
In short, I want to execute some Javascript when a certain element shows on screen.
you can write your script inside success function of ajax... success is called whn the ajax request succeeds...
$.ajax{(
url:....
...
success:function(result){
//do your stuff like appeding..
//your script here
}
})
it would be easier if you provide us with codes to help you out..

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

Alternative of this script in jQuery?

I use the following script to get the content of the remaining.php.
The drawback is that sometimes it doesn't work or it is kinda slow to display the text. Is there any other way of doing this ?
Thank you
$(document).ready(function(){
$("#SubmitButton").click(function (){
$('#remaining').load('remaining.php');
});
});
You could directly include the contents of remaining.php into the initial markup but make it hidden by applying display:none; style to the #remaining element. Then when the button is clicked simply show it:
$(function() {
$('#SubmitButton').click(function () {
$('#remaining').show();
});
});
Of course if you need to pass some parameters to the script which will depend on some javascript variables that are known only at the moment the button is clicked you will need to use AJAX as you are currently doing.
If "sometimes it doesn't work or it is kinda slow", the problem is probably the server you are using, not your javascript code.
The javascript code you're showing us here doesn't really do anything that could be slow, it only binds an event on a submit button. However, what could be slow is waiting for the answer from your web server when sending a request for remaining.php
From there, there is a thousand of reasons why your web server could be slow. Maybe you could post the content of your remaining.php file so we can see what is going on in there.
This isn't really a fault of jQuery, but the speed of return from your server. Perhaps there's a better way to handle it instead of fetching a full page?
For example, if your content request was only retrieving a message, you could return JSON from your server and have jQuery handle the data:
$(document).ready(function(){
$("#SubmitButton").click(function (){
$.post('remaining.php',
null,
function(data) {
// do stuff with your JSON result
});
});
});
When you're using .load(), you're sending a request to the server to get your content, which is why it can seem slow. I'm not sure why it sometimes won't work , but I would venture to guess that you may be clicking $("#SubmitButton") before $(document).ready fires.
Depending on your implementation, you may be able to refactor your application so that the text you want to display is pre-loaded on the page.

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources