Load JS through php class method. Is it possible? - php

I am attempt to load a little JS code using a method php static class.
The aim is to maintain every JS on the same place of their HTML object.
So, when we call the method it will create the HTML obj and will create a tag script whit the $jsString inside it.
myClass
myMethod(){
btnObjc id=txtbtnid
$jsString="
$(document).ready(function(){
$(\"#txtbtnid\").click(function() {
alert(\"oook\");
});
});
";
}
so far so good. It creates the btn Object and create the tag script just after the btn, whit the $jsString inside it.
The problem is it is unresponsive. That means I press the button and not is happening.
Any idea folks?

The problem is that you are creating button after page loading
Solution:
Use live function instead:
$(document).ready(function(){
$(\"#txtbtnid\").live('click',(function() {
alert(\"oook\");
}));
});

Related

jQuery load ...execute parent js

I have a PHP query that displays the first 30 documents, then an anhor which loads the rest of the documents using jQuery load.
Although, the parent uses javascript for some effects. Although once loaded onto the document it doesn't seem to inherit it's script tags.
is there any solution for this?
you have to put your "effects" into a function, then in the success of the load you have to call that function again.
function effects(){
//all your effects
}
$('#result').load('ajax/test.html', function() {
effects();
});

AJAX blocking Javascript

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.

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

Jquery Impromptu

I've been having some trouble adding Jquery Impromptu boxes into a project of mine. The code works fine outside of the project, but when placed inside malfunctions.
<script type="text/javascript">
function openprompt(){
var txt = 'Text here';
function mycallbackform(v,m,f){
if(v != undefined)
$.prompt(v +' ' + f.alertName);
}
$.prompt(txt,{
callback: mycallbackform,
buttons: { Add: 'add', Cancel: 'cancel' }
});
}
</script>
When executed this function will do nothing. If I remove the $.prompt then it will work.
I'm also getting this console message when I execute the function...
Uncaught TypeError: Object function ( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
} has no method 'prompt'
The code is placed in a PHP file which I think might be causing the problem, but I have tested the code in another PHP file, so its not the PHP alone.
I am planning to use the prompt to display a combo-box which is why I can't use a standard alert.
I'm quite new to these things, am i doing anything obviously wrong?
Thanks
Have you extended the jQuery methods when you used this code out side this project? If yes you should include that extension of jquery in this project.
$.prompt this means, in your jquery library there is a method name prompt.
If NO, your jQuery library of project is not same with Out side the project where you have tested this code. There must be a method (function) name prompt and you have to include that in your project.

Include Jquery script in .js page

Sorry if title is not too clear but I think it's about right. NEhow, what I would like to do is a bit like (well is to a certain extent) building a widget with JQuery (pref), PHP & CSS.
What I would really like to happen is for a "member" of my site to simply paste 2 lines of code in their HTML to load the widget. Something like this:
<script type="text/javascript" src="http://www.mydomain.com/script.js"></script>
Then to display the widget something like this <div id="displaywidget"></div>
OK that bit is "easy" and ok. But how do I include JQuery or "something" to generate the widget in script.js
What I mean is "displaywidget" - the ID of the widget div will be the name of a php file on my server so essentially script.js will need to load displaywidget.php into the div displaywidget.
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
Thinking as I write "pure" java can do "most of what I want i.e. document.getElementById('displaywidget'), BUT I would prefer to also "include" Jquery.js as I would like some aspects of the widget to use JQuery. Example being the JQuery UI date function.
Sorry if I am rambling a bit but trying to think as I go along. My "real" problem is I am not too sure on "pure" javascript i.e. getting the div to display/load displaywidget.php
Suggestions please. (Oh if I am barking up the wrong tree please feel free to tell me - nicely:) )
Thanks in advance
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
You're looking for the AJAX behaviors inside of jQuery which would make the call to the php page and then push the data into the div.
You should be loading jQuery early on in the process, right up front in your head element. Once its loaded it will be cached so no worries of its on every page. No real overhead incurred.
Once jQuery is installed you can call one of many AJAX functions related to obtaining data and popluation elements. Theres $.load(), $.ajax(), and a few others that escape me unless I go and check out their docs section.
You can do all of this without jQuery, but its more code and you have to control for browser differences.
You can load jquery into script.js, just copy and paste it after or before whatever javascript lives in script.js.
So if script.js is:
//start of file
alert('ex');
//end of file
Make it:
//start of file
alert('ex')
Copy and pasted Jquery source
//end of file
After a bit more "trawling & thought" I found this code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
writtend by Alex Marandon and found here http://alexmarandon.com/articles/web_widget_jquery/ - works a treat, exactly what I wanted, including/installing JQuery into a .js file

Categories