Opi
Opi

Reputation: 1308

Joomla setRedirect doesn't work

I have a simple Joomla controller, but I can't redirect anything.

According to the documentation:

class MyController extends MyBaseController {

 function import() {
    $link = JRoute::_('index.php?option=com_foo&ctrl=bar');
    $this->setRedirect($link);
  }

}
//The url contains & html escaped character instead of "&"

This should work, but I get a malformed URL. Is there something I'm missing here? Why is Joomla converting all the "&" characters into &'s? How am I suppose to use setRedirect?

Thank you

Upvotes: 2

Views: 6846

Answers (5)

/libraries/joomla/application/application.php

Find line 400

    // If the headers have been sent, then we cannot send an additional location header
    // so we will output a javascript redirect statement.
    if (headers_sent())
    {
        echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n";
    }

replace to

    // If the headers have been sent, then we cannot send an additional location header
    // so we will output a javascript redirect statement.
    if (headers_sent())
    {
        echo "<script>document.location.href='" . $url . "';</script>\n";
    }

This works!

Upvotes: -3

3rdLion
3rdLion

Reputation: 159

After inspecting the Joomla source you can quickly see why this is happening:

if (headers_sent())
    {
        echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n";
    }
    else
    {
    ... ... ...

The problem is that your page has probably already output some data (via echo or some other means). In this situation, Joomla is programmed to use a simple javascript redirect. However, in this javascript redirect it has htmlspecialchars() applied to the URL.

A simple solution is to just not use Joomlas function and directly write the javascript in a way that makes more sense:

echo "<script>document.location.href='" . $url . "';</script>\n";

This works for me :)

Upvotes: 0

Jobin
Jobin

Reputation: 8282

Try this.

$mainframe = &JFactory::getApplication();
$mainframe->redirect(JURI::root()."index.php?option=com_foo&ctrl=bar","your custom message[optional]","message type[optional- warning,error,information etc]");

Upvotes: 1

McRui
McRui

Reputation: 1931

Glad you found your answer, and by the way, the boolean parameter in JRoute::_() is by default true, and useful for xml compliance. What it does is that inside the static method, it uses the htmlspecialchars php function like this: $url = htmlspecialchars($url) to replace the & for xml.

Upvotes: 1

Opi
Opi

Reputation: 1308

Alright, I fixed it. So if anyone needs it:

instead of

$link = JRoute::_('index.php?option=com_foo&ctrl=bar');
$this->setRedirect($link);

use

$link = JRoute::_('index.php?option=com_foo&ctrl=bar',false);
$this->setRedirect($link);

to make it work.

Upvotes: 11

Related Questions