Placing jquery plugin in joomla module - php

I'm trying to create a module in joomla, which uses one jquery plugin. I've to do an ajax operation while clicking on an element in the module. Currently I'm specifying the whole path to the php file. But I know Its a wrong method.
The code in jquery plugin is like this.(please note the second line where the path is specified in the jquery plugin file)
$.get(
"/subdirectory/MyBlog/modules/mod_calendar/getCalendar.php", {
month: $("#selectedMonth").val(),
year: $("#selectedYear").val(),
flag: '-1'
}, function(data){
$("#monthlyCalendar").html(data);
$("#monthlyCalendar").show();
}
);
What is the correct method to specify the path in a jquery plugin file.
Also I need to know where to put my jquery plugin file in the module.

I found an answer in the following blog.
http://blog.subooa.com/development/joomla-coding/ajax-in-joomla-with-jquery/

The best way I found to do it is to use the JURI::root method to create a javascript variable that I can then use. In your php code, you would do something like this:
?>
<script type="text/javascript">
var joomlaRoot = '<?php echo JURI::root(); ?>';
</script>
<?php
You can then use that variable when you are doing your AJAX call.
As for where to put the jquery plugin file in your module, you can put it whereever you want under your module's directory and then use JURI::root again to create a path to it and call the JDocument::addScript method.
On a side note, you may consider using MooTools. It comes bundled in Joomla! already. It has the ability to do AJAX calls. Also, by using it, you avoid the possibility of having jQuery conflicts.

Atlast I was able to find a good solution to use the Ajax using Jquery in Joomla.
For this first you need to create a view and model to get required html through AJAX call.
Then use jQuery code similar to the following to get only the output of the required view.
//Code to get the base URL of joomla installation
szURL = document.URL;
componentList = szURL.split('/');
szDocument = componentList[componentList.length-1];
szURL = szURL.replace(szDocument, "");
//URL to the required component
url = szURL + "?option=COMPONENT_NAME&view=VIEW_NAME&tmpl=component&uid=" + getRandomValue();
jQuery.get(url, function(data) {
jQuery("#mydiv").html(data);
});
//Function to get a random number
//It is used for Ajax calls from IE; Else IE will use the cache values
function getRandomValue(){
return Math.floor(1000000 * (Math.random() % 1))
}
Note the URL used for the ajax call. It uses "tmpl=component" to get only the html for the selected component without joomla HTMLs.

Related

Execute php function only when clicked (wordpress)

For one of my wordpress site php files, I have the following code:
<div class="tabs">
Items
</div>
<div class="section" id="tab1">
<?php get_template_part('page/tab1'); ?>
</div>
So, it will call the tab1.php file into the div id="tab1"section.
However, I want to make it so that the get_template_part is only executed or called when the Items tab is clicked.
What would be the jQuery to call or execute the get_template_part function?
EDIT:
So, what I am trying to achieve is similar to Ajax. Since the get_template_part function won't be called till the "Items"tab is clicked, the browser does not have to call unnecessary files and slow down the page.
Let me know if you think this is the best way to do it.
Thanks!
Though the idea behind is already illustrated by Raphael in his answer, I intervene to add some details.
the best way to use AJAX with Wordpress is to use its built-in way of handling it, and that by sending requests to wp-admin/admin-ajax.php( I know the “admin” part of the file name is a bit misleading. but all requests in the front-end (the viewing side) as well as the admin can be processed in admin-ajax.php, with a lot of benefits, especially for security. And for the server-side code php that will be executed, it should be placed in functions.php.
Your jQuery code will look something like:
$(document).ready(function() {
$('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'yourFunction', id: tab_id}),
success: function(data){
$('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
infunctions.php of your theme (or directly in your plugin file), add:
add_action('wp_ajax_yourFunction', 'yourFunction');
add_action('wp_ajax_nopriv_yourFunction', 'yourFunction');
and define in the same file yourFunction callback function like this:
function yourFunction() {
// get id
// your php code
die();
}
For the javascript part, take a look at ajax() and its shorthand get(). And for the best practices using AJAX with Wordpress, there are many tutorials on the web (I will be back to give one). Good luck
Edit:
As it is mentionned by Karl, you can use .load() instead of ajax(), It should be noted that .load() is just a wrapper for $.ajax(). It adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...) which internally calls .ajax().
But my original answer is on how to organize php code respecting Wordpress best practices.
You can't really call a PHP function from javascript because by the time the browser sees the page, the PHP has already executed (or in your case, not executed )
The only way for you to do what you want is to spin the PHP function off into a separate script and then call that file using AJAX. Have the script echo HTML, and then insert the HTML into the tab1 div in the AJAX callback.
I think the easiest solution for you would be to use the jQuery load() function. It is the easiest way to achieve what you describe. The only issue that when someone clicks the header, there will be a delay to get the subitems as they do not exist yet (which would be the case for any situation where you delay the load.
HTML:
<div class="tabs">
Items
</div>
<div class="section" id="tab1"></div>
JS:
$(function () {
//wait for the page to finish loading
$('#items_id').click (function (e){
//watch for the items header to be clicked
e.preventDefault();
//prevent it from opening a link
$('#tab1').load('tab1.php');
//load the tab1.php file, or whatever file INTO the div
});
})

How to use index.php?-url with colorbox

I got those php-urls like www.***.com/index.php?task=login.
My question is how can I use them with colorbox? I'd like to load the content from the login page into my modal popup but I get unexpected results: it shows the complete website inside of the popup. How can I load the content into my modal popup properly when used with such URLs?
Currently my code looks like this:
$(document).ready(function(){
$(".login_link").colorbox({
href: "<?php echo $setting['site_url'];?>/index.php?task=login",
onOpen: function(){
$("#colorbox").css("opacity", 0);
},
onComplete: function(){
var title = 'Login';
$('#cboxTitle').text(title);
$("#colorbox").animate({"opacity": 1});
}
});
Now we know that the reason why you see the whole site in the modal is because you are loading the whole site into it (nothing to do with parameters getting ignored), we need to look at how you might load just the component you want.
I assume you are using some kind of CMS framework? This may have a method built in to supply things like this (Joomla for instance allows you to add &tmpl=component to the url and it will magically deliver what you are asking for. I don't know what framework you are using so I cannot advise specifically. This will be the "proper" way to perform the task.
Now assuming the file /includes/misc/misc.inc.php is under your document root, you should be able to invoke it by using something like:
http://your.site.domain/includes/misc/misc.inc.php
as the url. HOWEVER!!!! This is unlikely to work. The chances are that other parts of the framework are instantiated by the calling of index.php, which will not happen if you call the include file directly. Indeed, unlike WordPress, Joomla has measures in place which prevent execution of any of its included files unless they have been invoked via index.php.

Get config data to javascript file - magento

I have a really simple requirement but cant find a good solution to it.
How do I get config data into javascript files within magento. I need to load some config data from a module and make it available from within some javascript code. Without loading this data onto hidden fields on the page or using ajax to fetch them from a controller - how do i do this?
Thank you in advance for any help.
You can grab the value you are looking for like this:
// using seo as an example. look at the path field on core_config_data
$value = Mage::getStoreConfig("web/seo/use_rewrites");
Put this in a template that will echo your code:
<?php
$seo_value = Mage::getStoreConfig("web/seo/use_rewrites");
?>
<script type='text/javascript'>
magento_config = {}
magento_config['seo_value'] = "<?php print $seo_value; ?>";
// ... add more ...
</script>
Add that template to your layout and you will now have a global JS object called magento_config that you can use to grab your values. Depending on where you put your template, you may have to wait for the page to load before your variables are available.
Make sure not to echo these values indiscriminately, as there may be security implications in echoing store config data to the frontend.
Hope that helps!
Thanks,
Joe
Add this code in before you load the JS...
<script type="text/javascript">var var_name = <?php echo $var_name; ?></script>
Then you can load in JS like
<script type="text/javascript" src="/js/file.js"></script>
In your file.js (providing that the file is loaded after the variable definition) you can do something like...
//execute as soon as DOM is loaded
window.onDomReady(onReady);
//do on ready
function onReady()
{
alert(var_name);
}
Or if you were using jQuery
$(document).ready(function(){ alert(var_name); }

call php class functions through jquery

I have a dropdown which i want to fill through jquery. Problem that i am facing is that i want to call a class function directly from jquery. eg
My class_function PHP class contains get_locations function. how can i call this get_locations function using jquery .post method without introducing a third page?
The way I usually do that is to have an if statement at the top of the php page checking for a special mode.
jquery
$.get(
'page.php?mode=ajaxGetLocations&someVar=' + $('#someVar').val(),
function(data) { $('#myDropDown').html(data); }
);
PHP - near the top of the code
<?php
if (isset($_REQUEST['ajaxGetLocations'])
{
$someVar = $_REQUEST['someVar'];
// Get your data here
// Output your select box here
?>
<select>
...
</select>
<?php
exit; // You don't want to keep processing the page
}
?>
Have your PHP page upgraded with
if (isset($_GET['get_locations'])) {
echo $this->get_locations();
return;
}
and call it from jQuery with
$.ajax({
//..
data: "get_locations=1",
//...
});
You can't, because jQuery and PHP run in entirely different environments - PHP on the server, jQuery on the client. jQuery runs after PHP is done.
You want to look into jQuery's Ajax functions to find out how to call a PHP script from Javascript.
Ajax is used to make an HTTP request from the browser, using JavaScript, without leaving the page.
so you cant call a class function directly... but you can handle it by allowing the constructor to call this function depending on the parameters you have passed

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