Javascript within AJAX loaded pages - php

I have a main (index) page which loads pages dynamically and places them inside it's div but the Javascript within those pages doesn't execute. Specifically this part
<script type="text/javascript">
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
</script>

You will have to use getScript like this:
$('#foo').load('bar.html', function(){
$.getScript("js/fileName.js");
// call a function from fileName.js
});
You will have to put your JS code in that file and call that via getScript and then you can call functions from it as shown above.

Write your javascript in the index.php or write at the bottom of loaded page without document.ready

This is in reality a cross-browser issue: When <div>s are dynamically filled with HTML containing <script> tags, these scripts may or may not run - and this behaviour is different not only between browsers, but also between browser versions.
The only workaround I know of is to extract your JS, send it seperately and execute it after the <div> content has been set.

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

Injecting HTML into the DOM using script tag

We allow users to place a
<script language="javascript" src="oursite/script.php"></script>
tag on their page which should then embed some content from our site into their site. Currently script.php contains document.write("some content loaded from the database"), however there are some limitations.
Is there anyway I can have the same thing achieved using jQuery ? How do i tell jQuery to put a certain piece of HTML code EXACTLY where the script tag is ? document.write() can do this, but i'm not sure how to do this using jquery. (we are already providing the jquery js code to the client through script.php.
You don't need jQuery to do a document.write(). As long as it is executed inline (ie, not in an event handler such as $(document).ready()), it will work. Just make sure you escape the end script tag (like this: <\/script>), so that the HTML parser doesn't mistake it for an actual end script tag:
<script type="text/javascript">
document.write("<script language=\"javascript\" " +
"src=\"oursite/script.php\"><\/script>");
</script>
Alternatively, you could add the script using DOM manipulations. If you want to add the script after the page has loaded, this is your only option. To position it after the script tag that is calling it, give your script tag an id and use $("#myScript").after("<script>"):
<script type="text/javascript" id="myScript">
$(function () {
$("#myScript").after("<script>").attr({
language: "javascript",
src: "oursite/script.php"
});
});
</script>
You don't necessarily need to use jQuery, but you can.
The basic problem here is finding the script node as the page is loading.
You can give it an id and hope there are no duplicate ids on the other user's page.
But if you know the script will be evaluated as the page is loading, you can also do this:
(function(){ // this is just so you don't run into name collisions with the user's page
// Get all script elements
var scripts = document.getElementsByTagName('script');
// we know the last script element will be *this* one
var script = scripts[scripts.length-1];
var newp = document.createElement('p');
newp.textContent = 'inserted paragraph';
// now insert our new nodes after the current script
script.parentNode.insertBefore(newp, script.nextSibling);
})();
You can of course use jQuery as well with var $script = $('script:last');, but if you don't need it for anything else you can save some loading time by not using it.

jquery not working when i'm not putting it inside a jQuery(document).ready

jQuery(document).ready(function(){
jQuery(".test").click(function() {
alert(1);
});
});
When I try not to put :
jQuery(".test").click(function() {
alert(1);
});
inside a jQuery(document).ready() it won't work.
What do you think is the cause of that one? I already loaded the custom script that has that function.
<script type="text/javascript" src="/scripts/js/jquery.js"></script>
<script type="text/javascript" src="/scripts/js/customScript.js"></script>
Any answer would be appreciated and rewarded.
Thanks!
If you're loading it in <head>, then your .test hasn't loaded yet at the time when your code executes. Thus, jQuery(".test") returns [], so the click event gets attached to nothing. If you move your <script> to the last thing in <body>, it should work.
The behaviour you are seeing is normal and correct.
When you say:
jQuery(".test").click(function() {
alert(1);
});
It means "find all elements that exist right now with the class 'test' and assign a click handler to those elements". If you put such code outside the document ready then the browser will not have parsed any HTML that is after that bit of script so it will not find any elements defined further down the page - they don't exist in the DOM yet.
Putting the code inside document.ready (or in an onload event handler) means that it won't be run until the whole page has been parsed, at which point all elements will exist and can be accessed from your code. (It should also work if you put it right at the bottom of the page after all the HTML.)

jQuery toggle() doesn't work inside included (using PHP) code.

I have the following code defined in order to hide certain elements of a list:
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".done").toggle();
});
});
</script>
Basically, any < button > element being clicked will execute the toggle() function on any element with the "done" class. I know this works, because it works on some of my buttons. I have a page made up of several included files (using PHP include()). Usually, the javascript works in and out of these included files, but for some reason if I put a button inside one of them, it doesn't work - the function only works for buttons placed on the document where the script is defined. Is this always the case, or am I doing something wrong?
try using jQuery live function:
$("button").live('click', function(){
$(".done").toggle();
});
Try changing:
$("button").click(function(){
to:
$("button").live('click', function(){
This will make the event bind to any button, no matter when they are added. If you are using .live, then you don't need it inside a $(document).ready( block, as .live will add the event when the element is added.

Jquery load data from URL or go to URL

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.

Categories