AJAX blocking Javascript - php

Consider the following code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
});
</script>
The first script is for background changing logic and the second script gives list of thumbnails of the themes. The problem is that the first script doesn't work beacause of the second. If I don't use this AJAX technique everything works fine. Working code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<div id="dcontent">
<?php include('printThumbs.php'); printThemesThumbs();?>
</div>
The background changing logic looks like:
$(function() {
$('.themes li a img').click(function() {//code
});
Any help will be greatly appreciated.

in your first snippet of the code you defined a click function on .Theme and in the third snippet of the code .theme, is this correct?, i mean both classes seems to be different try to use the same class name return by your php function.

You're calling $(document).ready() twice, as $() is an alias, and the second definition is overwriting the first. First you are setting the document ready callback to
function() {
$('.themes li a img').click(function() {//code
}
and then overwriting it with
function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
}

you have to add your second code in a callback function. you can't bind something if it is not already in the dom. if you want to make changes to the printThumbs output you need to add a callback...
<script>
$(document).ready(function() {//this is also a callback function when document is ready
$('.Themes').click(function(){//this can be understand as a call back too... code is fired after a click
$('#dcontent').load('printThumbs.php',function(){/*your callback code here...this code will be fired after you've loaded printThumbs*/}
});
});
</script>
if you want to do some jquery or other client side stuff on the respons of an ajax call (html,xml, json or whatever) you have to specify a callback function. to make things less complicated you have to look at the callback function just as the on document ready function with the difference that the callback is applied to the respons of your ajax call. if the code is not in a callback function you can't manipulate the respons because it is not injected in the dom/it simply does not exists in your browser when the document is ready.

Related

Javascript within AJAX loaded pages

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.

Javascript variable not working in a different file

I have this script in index.php file:
<script type="text/javascript">
$(document).ready(function(){
$('#ads').load('output.php').fadeIn('slow');
});
</script>
And the output.php file contains a hidden input by which I pass a php variable and retrieve it succesfully:
<script type="text/javascript">
num = document.getElementById('number').value;
</script>
And if I put, say, an alert(num); in the output.php file, everything works. Though when I do the same in the index.php file, javascript doesn't seem to see that num variable.
Im just going to ges that you dont actually wait until the file is actually loaded before testing to access that variable
http://api.jquery.com/load/
the load method takes a completed callback that u can use like this
$(document).ready(function(){
$('#ads').load('output.php', function() {
alert(num);
}).fadeIn('slow');
});
but you should probably not solve your problem this way i sugest you call a function from your
loaded file instead of setting a variable
You can't access variables before you create them. In the code you provided the first time num is being assigned to is when the output.php file is loaded and parsed. Since jQuery's load function isn't blocking - that is, your browser will continue executing JS while the load function is doing its magic - you have no good way to know when num will be assigned to. It could be milliseconds, or it could be never if your webserver refuses to return the output of output.php for whatever reason.
In jQuery programming, using a callback function is common practice, although you can make it cleaner by passing it a function reference instead of an inline function:
$(document).ready(function(){
$('#ads').load('output.php', outputLoadCallback).fadeIn('slow');
});
function outputLoadCallback(response, status) {
console.log(num);
}
Maybe an even better way would be to include the logic you need to run in the callback function like so:
var num; // Make sure num is in the global scope
function outputLoadCallback(response, status) {
num = document.getElementById('number').value;
console.log(num);
}
If you're "not much of a pro", may I suggest jQuery in Action?

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.

OnmouseOver Jquery/Javascript call external function

I could be mistaken here but I thought that inline html can call an external javascript file's function with onmouseover.
For example:
<a href="#" onmouseover="updateParentImage('<?php echo $this->getGalleryUrl($_image) ?>');">
And my EXTERNAL jquery/javascript file function looks like:
function updateParentImage ($image_url)
{
alert($image_url);
$('.product-img-box .product-image img').attr('src', $image_url);
}
The function never runs. Am I completely missing something? Shouldn't that tag call the appropriate file even thought the javascript is external?
Note: If I include the javascript inline, the alert box shows but the image that I am trying to change in the document does not change, even though I"m using the same referencing as another place in the code where it successfully updates the image.
Any help would be appreciated. Thanks!
How about something like this...
<a href="#" class="imageChanger" data-imagesrc="<?php echo $this->getGalleryUrl($_image) ?>">
Then use jquery to add a mouseenter event
$(document).ready(function(){
$('.imageChanger').mouseenter(function(){
alert($image_url);
$('.product-img-box .product-image img').attr('src', $(this).data('imagesrc'));
});
});
Based on your comment, I've come to this solution that might help you:
This is one of many links
Then you can have this in your script:
(function($) {
$(document).ready(function() {
$('a').hover(function() {
// this happens onmouseenter
var imageUrl = $(this).data('imageurl');
updateParentImage(imageUrl);
}, function() {
//this happens onmouseleave
});
});
function updateParentImage(image_url) {
alert(image_url);
$('.product-img-box .product-image img').attr('src', $image_url);
}
})(jQuery);
That small piece of code binds to all 'a' elements, which might not exactly be right in your case, but it's just there as an example. Then I've wrapped all the code in a closure/immediately invoked function expression (IIFE), to make sure we don't pollute the global namespace too much. It also makes sure that $ stays jQuery inside that closure.
One more thing to be noted is that I've used the data attribute on the links to store the image URL for that link. Clean and easy :)
If you have any question, shout out!
(See comments above for context for response)
You should never have to duplicate event binding, and doing inline, obtrusive JavaScript in never an answer.
Bind once and set your URL to a property that you can grab. Further, I write the following under the assumption that you don't want to touch your external JS function:
<div id="linkContainer">
Something
</div>
JavaScript (can be placed in your page's HTML in script tags if you must):
$('#linkContainer a').bind('mouseover', function() {
updateParentImage($(this).data('imgsrc'));
return false;
});

Categories