Doing ajax with Jquery - php

I have been loading content with ajax and all works fine. Here is my code
$(document).ready(function() {
//Load a-z.php
//Timestamp resolves IE caching issue
var tsTimeStamp= new Date().getTime();
$.post('../../includes/categories/a-z.php',
{action: "post", time: tsTimeStamp},
function(data){
$('#moviescontainer').html(data).slideDown('slow');
});
return true;
});
My data inside a-z.php requires Javascript for it's content and when I load a-z.php onto my page the javascript doesn't work.
I am quessing that I need to link the relevant files to a-z.php and then load it via ajax.
Doesn't this kind of defeat the object of ajax?? That means that I will be loading the js files on the main page and then loading them again when I ajax a-z.php
I hope I made some sense.
EDIT: The A-Z.php page references external javascript files that I have already included on my main page (example: the jquery library, That will mean i am loading it twice.
When I mean requires javascript for its content I have a few modal boxes etc that open when content is clicked. These use the Jquery library)

Your problem is most likely that you need to add the defer attribute to the script tag, which defers executing the script until the content is loaded.
see here
you should not have to load the scripts a second time.

EDIT: The A-Z.php page references
external javascript files that I have
already included on my main page
(example: the jquery library, That
will mean i am loading it twice.
Simply omit them from the a-z.php page then. If they're already included on the main page, they'll be available to the a-z.php script when it's loaded in via ajax. However, I suspect any onload or $(document).ready() calls won't work quite right. I'd try to remove as much JS as possible out of the a-z.php page.

Related

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');
});
});

Is there a way to get Joomla module position and functions with jquery .ready function?

I am trying to pass a
{loadposition grabber}
custom module position and module to delay it's operation after the document has loaded. I have loaded my jquery.js file and added this script.
<script type="text/javascript">
$(document).ready(function(){
$.get('{loadposition grabber}',
function(output) {
$('#grabberDiv').html(output).fadeIn(500);
});
});
</script>
With a...
<div id="grabberDiv">Testing grabberDiv</div>
In my body. What I am trying to figure out is if this is a problem in my code here or if it is simply impossible to do without altering my module.
Joomla!'s {loadposition aModulePosition} is meant for use in the body of an article and is replaced during page rendering by the CMS, ie. prior to the page being sent back to the browser.
So the browser (& therefore jQuery/Javascript) never sees an element called {loadposition grabber}.
It might be better to set the default CSS for the grabberDiv to display:none and then update your script to work with the correct element ID.

Is there a way to define a function permanently in jQuery?

I'm working on a site that passes information to my server that returns a page, however I have to re-define the click listener every time I reload the page because jQuery controls all my clicks on every page, so I' m wondering is there a way to permanently define a function?
jQuery code:
$(function(){
$('.lvl1Links').on('click',function(event) {
event.preventDefault();
$('pload').html('<img src="source/image/lbl.gif">');
var page = $(this).attr('id');
var huh = $('input:hidden').val();
var data = 'pop='+huh+'&page='+page;
$.post('source/php/bots/authorize.php',data,function(data){
$('#pager_master_div').html(data).slideDown();
$('pload').html('');
});
});
});
Being a stateless platform, every time the page loads you need to rebind things like this. Here's the pattern I use to make it easier, though:
If this is common across an area of your site, put this type of stuff into an init function in the common file. e.g.
global.js:
function InitSalesPageOrWhatever(){
$(function(){ foo; });
OtherStuffThatRunsOnEverySalesPageLoad();
}
Then in the script block on your pages, e.g. SalesPage:
InitSalesPageOrWhatever();
That's it--just one line in your content pages. Beyond the benefit of the content pages being nice and clean, that big clump of JS can now be cached by the user's browser, making the load on you less and their experience faster.
jQuery (and all Javascript) runs on the client side where permanence is unavailable. There are two ways to approach the permanence you seek.
Write a jQuery plugin and include it in your page.
Write your click handler once, and use your server-side code/scripting language to include it in every HTML page. An example PHP include is here.
This may be a good time to consider HTML templates -- documents that contain standard HTML (header, footer, navigation, etc) that should be included in every page of your site.

dynamic loading content containing javascript

I want to add a progress bar before my web page's content loads, so I thought of loading it dynamically via javascript. This content has embedded javascript in its html. I tried using jquery.load() which works perfectly besides the fact that it does not support the js that doesn''t work on the returned content
just to make it clear, what i'm doing is something like this to load all the content:
$("#contentid").html("progressBar.gif");
$("#contentid").load(script.php #content)
$("#contentid").show();
and inside the content returned from script.php there are js calls such as:
jquery.load (to crawl for data and displaying it when ready)
document.getElementById('some_div') (for chart api)
snippets that load widgets
I've been trying to work around with using jquery.ajax though not sure if\how its possible with it yet. would love for some input on that.should i be able to achieve that with it?
Any other idea that might show a progress bar till the script's content is loaded will be great. I'm trying to reduce changes in the code structure, since this long load happens only sometimes.
Thanks.
You may add a div with the progress bar, covering all the page, and remove it after the page is loaded, using:
$(window).load(function() {
$('#progressbar').remove();
});
JQuery's load method takes a callback function as an argument. That function will get called when the load is completed, so you can hide your progress bar at that point. Here is an example from their API docs:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
In your case, it would be something like:
$("#contentid").load(script.php, function(){
$("#contentid").hide();
});

Why doesn't my <script> tag work from php file? (jQuery involved here too)

Here is what I am trying to accomplish. I have a form that uses jQuery to make an AJAX call to a PHP file. The PHP file interacts with a database, and then creates the page content to return as the AJAX response; i.e. this page content is written to a new window in the success function for the $.ajax call. As part of the page content returned by the PHP file, I have a straightforward HTML script tag that has a JavaScript file. Specifically:
<script type="text/javascript" src="pageControl.js"></script>
This is not echoed in the php (although I have tried that), it is just html. The pageControl.js is in the same directory as my php file that generates the content.
No matter what I try, I can't seem to get the pageControl.js file included or working in the resulting new window created in response to success in the AJAX call. I end up with errors like "Object expected" or variable not defined, leading me to believe the file is not getting included. If I copy the JavaScript directly into the PHPfile, rather than using the script tag with src, I can get it working.
Is there something I am missing here about scope resolution between calling file, php, and the jQuery AJAX? I am going to want to include javascript files this way in the future and would like to understand what I am doing wrong.
Hello again:
I have worked away at this issue, and still no luck. I am going to try and clarify what I am doing, and maybe that will bring something to mind. I am including some code as requested to help clarify things a bit.
Here is the sequence:
User selects some options, and clicks submit button on form.
The form button click is handled by jQuery code that looks like this:
$(document).ready(function() {
$("#runReport").click(function() {
var report = $("#report").val();
var program = $("#program").val();
var session = $("#session").val();
var students = $("#students").val();
var dataString = 'report=' +report+
'&program=' +program+
'&session=' +session+
'&students=' +students;
$.ajax({
type: "POST",
url: "process_report_request.php",
cache: false,
data: dataString,
success: function(pageContent) {
if (pageContent) {
$("#result_msg").addClass("successMsg")
.text("Report created.");
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
// open a new report window
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// add the report data itself returned from the AJAX call
reportWindow.document.write(pageContent);
reportWindow.document.close();
}
else {
$("#result_msg").addClass("failedMsg")
.text("Report creation failed.");
}
}
}); // end ajax call
// return false from click function to prevent normal submit handling
return false;
}); // end click call
}); // end ready call
This code performs an AJAX call to a PHP file (process_report_request.php) that creates the page content for the new window. This content is taken from a database and HTML. In the PHP file I want to include another javascript file in the head with javascript used in the new window. I am trying to include it as follows
<script src="/folder1/folder2/folder3/pageControl.js" type="text/javascript"></script>
Changed path folder names to protect the innocent :)
The pageControl.js file is actually in the same folder as the jQuery code file and the php file, but I am trying the full path just to be safe. I am also able to access the js file using the URL in the browser, and I can successfully include it in a static html test page using the script src tag.
After the javascript file is included in the php file, I have a call to one of its functions as follows (echo from php):
echo '<script type="text/javascript" language="javascript">writePageControls();</script>';
So, once the php file sends all the page content back to the AJAX call, then the new window is opened, and the returned content is written to it by the jQuery code above.
The writePageControls line is where I get the error "Error: Object expected" when I run the page. However, since the JavaScript works fine in both the static HTML page and when included "inline" in the PHP file, it is leading me to think this is a path issue of some kind.
Again, no matter what I try, my calls to the functions in the pageControls.js file do not work. If I put the contents of the pageControl.js file in the php file between script tags and change nothing else, it works as expected.
Based on what some of you have already said, I am wondering if the path resolution to the newly opened window is not correct. But I don't understand why because I am using the full path. Also to confuse matters even more, my linked stylesheet works just fine from the PHP file.
Apologies for how long this is, but if anyone has the time to look at this further, I would greatly appreciate it. I am stumped. I am a novice when it comes to a lot of this, so if there is just a better way to do this and avoid this problem, I am all ears (or eyes I suppose...)
I have also had problems with a similar issue to this, and this was a real headache. The following approach may not be elegant, but it worked for me.
Make sure that your php file, just outputs what you want in your
body
Add jquery to the window head dynamically
Add any external script files to the window head dynamically
use jQuery html on the window's document to call html() with your loaded content on the body, so that scripts are evaluated.
For example, in your ajax success:
success: function(pageContent) {
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// boilerplate
var boilerplate = "<html><head></head><body></body></html>";
reportWindow.document.write(boilerplate);
var head = reportWindow.document.getElementsByTagName("head")[0];
var jquery = reportWindow.document.createElement("script");
jquery.type = "text/javascript";
jquery.src = "http://code.jquery.com/jquery-1.7.min.js";
head.appendChild(jquery);
var js = reportWindow.document.createElement("script");
js.type = "text/javascript";
js.src = "/folder1/folder2/folder3/pageControl.js";
js.onload= function() {
reportWindow.$("body").html(pageContent);
};
head.appendChild(js);
reportWindow.document.close();
}
Good luck!
It probably isn't looking where you think it is looking to grab your javascript file.
Try a server-relative format like this:
<script src="/some/path/to/pageControl.js"></script>
If that still isn't working, verify that you can type the url to your script file into your browser and get it to download.
Make sure that you have that within either <head> or <body> of the HTML page. Also, I'd double check the path to the .js file. You could do that by pasting "pageControl.js" at the root of your web address.
Things to look for:
Use Firebug (NET tab) to check if the js file is loaded with status 200. Also check in the Console tab for any javascript errors.
Are you using HTML5 offline. If you do, maybe it serves a cached version that doesn't include your <script> tag.
View the page source and make sure it includes the script tag.
Change the source attribute to absolute path: <script src="http://www.example.com/js/pageControl.js" type="text/javascript"></script>
Visit http://www.example.com/js/pageControl.js and make sure it shows correctly.
Try to place the <script> right after the <head> so that it loads first.
This is all I could think of.
You can dynamically load script by creating the element and then append it to head or other element:
reportWindow.document.write(pageContent);
var script = document.createElement('script');
script.src = 'pageControl.js';
script.type = 'text/javascript';
reportWindow.document.getElementsByTagName('head')[0].appendChild(script);
reportWindow.document.close();
Have you tried using the jquery $("#target_div").load(...)
This also executes JS inside the output...
Read this doc to find out how to use it :
http://api.jquery.com/load/
To me it sounds like you're expecting an unloaded script to work.
Try taking a look here: http://ensure.codeplex.com/SourceControl/changeset/view/9070#201379
This is a bit of javascript that ensures that the script is loaded properly before access is attempted. You can use this either as lazy loading (loading javascript files only when required), or, as I interpret your problem, loading a script based on the result of ajax calls.
What's probably happening is, you're echoing a string via an ajax callback, not inserting an element. External scripts require a second GET call to load their contents, which isn't happening - only the first call happened. So, when the first call includes the inline code, the DOM doesn't have to make an additional GET request to fetch the contents. If the DOM doesn't see the script, the DOM won't execute it, which means it's just some random tag.
There's a very fast way to find out. In Chrome (or Firefox with the Firebug plugin installed), check the console > scripts dropdown to see all the loaded scripts. If it's not listed, it's not loaded and the script tag you see in the markup is otherwise inert.
Since it's probably just a string as far as PHP cares, you could create it as PHP DOM object and insert it properly (although this could be laborious). Instead, maybe place it at the very end of the page, just before the closing body tags. (This is the preferred position for js anyway - dead last, after all the other elements on the page have loaded and are available to the DOM.)
HTH :)

Categories