Joomla 2.5: Distinct based on the language website with navigator - joomla

I have a joomla 2.5 bilingual website and I have the following code in index.php
<script type="text/javascript"> // <![CDATA[
if ( (navigator.userAgent.indexOf('Android') != -1) ) {
document.location = "a.html";
} // ]]>
</script>
As a result if you login from your Android phone/tablet it will lead you at the a.html link.
What I wanna do is:
Assume the website's url is the www.test.com/index.php?lang=en so when you login from android it leads you at the a.html and when you login from www.test.com/index.php?lang=fr should lead you at the b.html .
I need to distinct based on the language.
Thanks in advance.

You could maybe use something like this:
<?php
$app = JFactory::getApplication();
$menu = $app->getMenu();
if ($menu->getActive() == $menu->getDefault( 'en-GB' )) { ?>
<script type="text/javascript"> // <![CDATA[
if ( (navigator.userAgent.indexOf('Android') != -1) ) {
document.location = "a.html";
} // ]]>
</script>
<?php }
elseif ($menu->getActive() == $menu->getDefault( 'fr-FR' )) { ?>
<script type="text/javascript"> // <![CDATA[
if ( (navigator.userAgent.indexOf('Android') != -1) ) {
document.location = "b.html";
} // ]]>
</script>
<?php }
?>
Please note I haven't tested this so let me know if it work and if not, I can update it.
Update:
As Oriol said, it's better to redirect server side rather than javascript. I was messing around with the code yesterday and half of what I wrote worked:
<?php
$lang = JFactory::getLanguage();
$app = JFactory::getApplication();
$menu = $app->getMenu();
if ($menu->getActive() == $menu->getDefault( 'en-GB' )) {
?>
<script type="text/javascript">
alert("<?php echo $lang->getTag() ?>");
</script>
<?php
}
elseif ($menu->getActive() == $menu->getDefault( 'fr-FR' )) {
?>
<script type="text/javascript">
alert("<?php echo $lang->getTag() ?>");
</script>
<?php
}
?>
It basically gets the current language tags and alerts then, depending which language the website is being viewed in. So it will either alert en-GB or fr-FR. Try using a server side redirect inside the if and else else statements

Related

How to open contact form 7 by using wordpress ajax

I am using contact from 7 plugin and my question is to open contact form 7 in popup via wordpress admin ajax but my code not working. Only popup open but contact form 7 not submitting. It is redirecting in admin ajax url and returns 0.
Here is the code that i am doing in functions.php
<?php
add_action('wp_head', 'my_action_popup_cf7_javascript');
function my_action_popup_cf7_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.myajaxcarrer').click(function(){
//alert(1);
var mydata = $(this).data();
$(".overlay").fadeIn('slow');
var data = {
action: 'my_action_popup_cf7',
//whatever: 1234,
id: mydata.id
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
//console.log(ajaxurl);
$('.item').removeClass('active');
$('[data-id=' + mydata.id + ']').parent().addClass('active');
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
// alert('Got this from the server: ' + response);
$('#testcarrer').html(response);
var offset = $(window).scrollTop();
$(".career-form").css("top", offset+50 );
$('.closeBtn').click(function(e){
e.preventDefault();
$(".overlay").fadeOut('slow');
$('.career-form').css("top", -1000+"%" )
});
});
});
});
</script>
<?php
}
add_action('wp_ajax_my_action_popup_cf7', 'my_action_popup_cf7_callback');
add_action( 'wp_ajax_nopriv_my_action_popup_cf7', 'my_action_popup_cf7_callback' );
function my_action_popup_cf7_callback() {
global $wpdb; // this is how you get access to the database
//$whatever = 'ID=> '. $_POST['id'];
//echo $whatever;
?>
X
<h3>Apply Now</h3>
<div class="formBox">
<?php echo do_shortcode('[contact-form-7 id="905" title="My New Carrer Form"]'); ?>
</div>
<?php
exit(); // this is required to return a proper result & exit is faster than die();
}
And code in page template file is
<span class="applyBtn"><a class="myajaxcarrer" data-id="903">Apply Now</a></span>
<div class="overlay"></div>
<div class="career-form">Ajax result Load here..</div>
And js code is below.
$('.applyBtn').click(function(e){
e.preventDefault();
var offset = $(window).scrollTop();
$(".overlay").fadeIn('slow');
$(".career-form").css("top", offset+50 )
});
$('.closeBtn, .overlay').click(function(e){
e.preventDefault();
$(".overlay").fadeOut('slow');
$('.career-form').css("top", -1000+"%" )
});
You can open it by echoing do_shortcode('[form name with id]'); it in you php function.

ajax mysql lookup not returning correct result for multi word string

I have followed a tutorial on an ajax lookup that informs the user if the username is already taken.
So the controller syntax is:
<?php
class Login extends CI_Controller
{
function index()
{
$this->load->view('loginView');
}
function getResultfromdb($username){
$this->db->where('username',$username);
$query = $this->db->get('users')->num_rows();
if($query == 0 ) echo 'userOk';
else echo 'userNo';
}
}
the view is:
<html>
<head>
<title>Check User Name</title>
<link type="text/css" rel="stylesheet" href="<?=base_url()?>css/style.css"/>
</head>
<body>
<form method="post" action="">
<label for="username">Enter Your Name</label>
<input type="text" id="username"/>
<span class="checkUser" ></span>
<input type="hidden" class="hiddenUrl"/>
</form>
<script type="text/javascript" src="<?=base_url()?>js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="<?=base_url()?>js/check.js"></script>
</body>
</html>
the check.js is:
$(document).ready(function(){
$('#username').blur(function(){
if( $('#username').val().length >= 3 )
{
var username = $('#username').val();
getResult(username);
}
return false;
})
function getResult(name){
var baseurl = $('.hiddenUrl').val();
$('.checkUser').addClass('preloader');
$.ajax({
url : baseurl + 'index.php/login/getResultfromdb/' + name,
cache : false,
success : function(response){
$('.checkUser').removeClass('preloader');
if(response == 'userOk') $('.checkUser').removeClass('userNo').addClass('userOk');
else $('.checkUser').removeClass('userOk').addClass('userNo');;
}
})
}
})
As mentioned, this works great. so it will validate bob and andy perfectly. however it fails on bob smith and andy jones. How can the code be adapted to validate strings with spaces?
Thanks as always,
It's failing because you're trying to pass the username in the URL, the browser is likely encoding the space as %20 when passing it. So your CI function is looking for bob%20smith and not bob smith.
First of all I don't think it's great practice to even allow spaces in user names but to each their own. You need to decode the URL first
function getResultfromdb($username){
$this->db->where('username',urldecode($username));
$query = $this->db->get('users')->num_rows();
if($query == 0 ) echo 'userOk';
else echo 'userNo';
}
use the encodeURIComponent(string),for example :
var name = encodeURIComponent(name);
and you js will look like this
$(document).ready(function(){
$('#username').blur(function(){
if( $('#username').val().length >= 3 )
{
var username = $('#username').val();
getResult(username);
}
return false;
})
function getResult(name){
var name = encodeURIComponent(name); // Replace name before send it
var baseurl = $('.hiddenUrl').val();
$('.checkUser').addClass('preloader');
$.ajax({
url : baseurl + 'index.php/login/getResultfromdb/' + name,
cache : false,
success : function(response){
$('.checkUser').removeClass('preloader');
if(response == 'userOk') $('.checkUser').removeClass('userNo').addClass('userOk');
else $('.checkUser').removeClass('userOk').addClass('userNo');;
}
})
}
})
and the php :
<?php
$url = urldecode($_GET['name']); // Replace with your parameter
?>
Okay good luck

Stop Loading Automatic Scripts in Joomla 2.5

In Joomla 2.5, the scripts below are loaded automatically.
<script src="/media/system/js/mootools-core.js" type="text/javascript"></script>
<script src="/media/system/js/core.js" type="text/javascript"></script>
<script src="/media/system/js/caption.js" type="text/javascript"></script>
<script src="/media/system/js/mootools-more.js" type="text/javascript"></script>
<script src="/templates/pswedge/js/jquery.min.js" type="text/javascript" defer="defer"></script>
I don't want to load these files. How can I remove these links?
I would not recommend you to change the core files of Joomla.But if you really need to that then you can try this:
Step to disable the preloaded script file in joomla template.
Step one: Using your favorite file editor, open for edit:
/libraries/joomla/document/html/renderer/head.php
Step one: Find this code at line 151 and update it to include the code with this :
// Generate script file links
foreach ($document->_scripts as $strSrc => $strAttr)
{
// Code to disable mootools for your site (still loads it for your admin)
$ex_src = explode("/",$strSrc);
$js_file_name = $ex_src[count($ex_src)-1];
$js_to_ignore = array("mootools-core.js","mootools-more.js","core.js","caption.js");
if( in_array($js_file_name,$js_to_ignore) AND substr_count($document->baseurl,"/administrator") < 1 AND $_GET['view'] != 'form')
continue;
$buffer .= $tab . '<script src="' . $strSrc . '"';
if (!is_null($strAttr['mime']))
{
$buffer .= ' type="' . $strAttr['mime'] . '"';
}
if ($strAttr['defer'])
{
$buffer .= ' defer="defer"';
}
if ($strAttr['async'])
{
$buffer .= ' async="async"';
}
$buffer .= '</script>' . $lnEnd;
}
After saving the changes above, clear the cache that you have set and test your Joomla website and your Joomla Admin Dashboard. If you view the source code,all the predefind files are not there.
Or
You can try like this to hide it from index.php in template. Just put this line before the <jdoc:include type="head" /> and make necessary changes as needed to the scripts.
<?php
$search = array('mootools-more.js', 'caption.js');
// remove the js files
foreach($this->_scripts as $key => $script) {
foreach($search as $findme) {
if(stristr($key, $findme) !== false) {
unset($this->_scripts[$key]);
}
}
}
?>
May one of these method work-
Method 1:
Put Before <jdoc:include type="head" />
$search = array('mootools', 'caption.js');
// remove the js files
foreach($this->_scripts as $key => $script) {
foreach($search as $findme) {
if(stristr($key, $findme) !== false) {
unset($this->_scripts[$key]);
}
}
}
//Method 2
in index.php of template
$parameter_script = 'scripts';
$headerstuff=$document->getHeadData();
reset($headerstuff[$parameter_script]);
foreach($headerstuff[$parameter_script] as $key=>$value){
unset($headerstuff[$parameter_script][$key]);
}
$document->setHeadData($headerstuff);
//Method 3
In the file directory /plugins/system create a new file called “removemootools.php” and insert the following code (you will need to register the plugin in the database, too).
class plgSystemRemoveMooTools extends JPlugin
{
public function onAfterDispatch()
{
$app = JFactory::getApplication();
if($app->isSite()) //Only ever remove MooTools from the client-side, never the admin side
{
//Repeat these three line for all js you want to exclude
$mootools = JURI::root(true).DS.'media'.DS.'system'.DS.'js'.DS.'mootools.js';
$document = JFactory::getDocument();
unset($document->_scripts[$mootools]);
}
}
}
I used this code to remove jquery files from the head ( Joomla! 3.3.1 )
<?php
//Remove jquery
$search = array('jquery', 'jquery.min.js');
// remove the js files
foreach($this->_scripts as $key => $script) {
foreach($search as $findme) {
if(stristr($key, $findme) !== false) {
unset($this->_scripts[$key]);
}
}
}
?>
<jdoc:include type="head" />

Iframe or Ajax ?

at the moment I've got a simple bit of code to display messages on a site.
the page includes an iframe that self refreshes every 90 seconds, and the iframe displays the contents of a mysql table limited to the most recent (30) posts.
I've been reading up on ajax and it still confuses me, i've never got it working properly, and would like to know, for a small task like this, is it really worth it ?
<head>
<META HTTP-EQUIV="refresh" CONTENT="90; URL=">
</head>
<body>
<?
$newsarray = array();
$sql = "SELECT * FROM `news` ORDER BY `date` DESC LIMIT 30";
$result = mysql_query($sql);
if(mysql_error()) { print mysql_error(); } else {
while($stuff = mysql_fetch_assoc($result))
{ array_push($newsarray, $stuff); }
foreach($newsarray as $newsstory) { ?>
<div class="newsstory">
<h2><? echo $newsstory['headline']; ?></h2>
<div><? echo $newsstory['story']; ?></div>
<label>By <? echo $newsstory['user']; ?> on <? echo $newsstory['date']; ?></label>
</div>
<? } ?>
</body>
It would be as simple as adding the jQuery library to your exsiting page and adding the following code:
<div id="result"></div>
Manually Fetch Page
<script language="javascript">
function updatestuff() {
$.ajax({
url: 'mypage.php', // The source
cache: false, // Make sure results are not cached
success: function (data) {
$('#result').html(data); // Update data once retrieved
}
});
}
setInterval("updatestuff()",90000); // In Milliseconds
</script>
This would run the function updatestuff() every 90 seconds which would update the <div> with content fetched from mypage.php.
If you want something that automatically updates every 30seconds then definitely Ajax is the way to go.
Some say (myself include) that you'd be insane not to use jQuery to do this.

How can I add custom code to the header

How can I add the following line to the header, in a component?
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="js/excanvas.min.js"></script><![endif]-->
Not sure if it will work with any text, but you could try:
$document =& JFactory::getDocument();
$document->addCustomTag('<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="js/excanvas.min.js"></script><![endif]-->');
I hope it will be helpfull.
You can use :
<?php
$document = &JFactory::getDocument();
$document->addScript( '/js/excanvas.min.js' );
?>
I am searching for how to add the conditional statement though ...
UPDATE
Checking if the user agent is IE
<?php
$document = &JFactory::getDocument();
//Is it Internet Explorer?
ereg('MSIE ([0-9]\.[0-9])',$_SERVER['HTTP_USER_AGENT'],$reg);
if(isset($reg[1])) {
//Yes, it is Internet Explorer
$document->addScript( '/js/excanvas.min.js' );
}
?>

Resources