How can I link to a controller and return/redirect with data? We have a plugin that logs you in and out of a third party service.

Login is easy as we can POST to a controller action, but for logout, we have a link that goes straight to an action URL.

My problem is that I want to redirect back to the URL the user submitted from, with some data that we use in the view (a message to say you've logged out).

redirectToPostedUrl() is no good as this isn't a POST request, and from what I can see in the docs redirect() doesn't give us the option to add data and anything we add in craft()->urlManager->setRouteVariables() doesn't come through when you redirect.

And if we don't redirect or return, we get a 404 as the user is just left on the controller action URL, for which there is no template output.
$_SERVER['HTTP_REFERER'] should give you the url the request was coming from, which you can then pass in to the redirect function. You could add some URL parameters like ?message='Logged%20out!' and have your template check for the message existing and display it. 

Be aware that this function comes with a small caveat from the PHP documentation:


  The address of the page (if any) which referred the user agent to the
  current page. This is set by the user agent. Not all user agents will
  set this, and some provide the ability to modify HTTP_REFERER as a
  feature. In short, it cannot really be trusted.


Here's the full documentation on the PHP $_SERVER array.

Edit: Other Option Using a Form

It might be a little bit clunky, but you would have the like to logout actually be a form submit. You could post the current URL to your controller and use craft()-&gt;urlManager-&gt;setRouteVariables(array('message' =&gt; $myMessageObject)); to send your message back to the user.

Form: 

&lt;form method="post" action="" accept-charset="UTF-8"&gt;
    &lt;input type="hidden" name="action" value="{{ actionUrl('pluginHandle/controller/method', { return: 'this/page/url' }) }}"&gt;
    &lt;input type="submit" value="{{ 'Log out'|t }}"&gt;
&lt;/form&gt;


All you'll need is a little bit of CSS to style the submit link, or even somme javascript to trigger the form submit. If you wanted to get even fancier, you could AJAX the request and avoid the form all together. 

Here's the documentation on posting to controller actions for reference.