• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Solved] Modifying sessions with Javascript

#1
[eluser]Jilimay[/eluser]
Hello everyone,

I am posting here because I have a piece of code that won't work, and I really
would like to know why !

My original idea was to allow users to change my site's language by clicking on
corresponding flags, somewhere in the page. In order to do that, I thought I
would use the XMLHttpRequest object in Javascript, and call a given function
from a controller via a GET request on the good URL.

So here is how it looks (please note that the 'echo' and other 'var_dump' are
obviously there for testing purposes) :

First, the controller supposed to change the site's language :

Code:
class LanguageSetup extends CI_controller {

    public function setLanguage($newLanguage = 'english')
    {
        echo "<p>Switching language to $newLanguage</p>";
        $ref =& get_instance();
        $ref->session->set_userdata('language', $newLanguage);
        $ref->lang->load
                         (
                             $ref->session->userdata('language'),
                             $ref->session->userdata('language')
                          );
        var_dump($ref->session->userdata);
        echo '<p>'.$this->lang->line('hello').'</p>';
    }
}

When I call the function from my browser, it displays what is expected :

Code:
Switching language to english

array
  'session_id' => string 'f89dd59fdabbabc4c7c918146be57788' (length=32)
  'ip_address' => string '127.0.0.1' (length=9)
  'user_agent' => string 'Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/2010010' (length=50)
  'last_activity' => int 1303376217
  'language' => string 'english' (length=7)

Hello !

And of course if I open another tab, the settings are still the same.

But when I try to call it with a xmlhttprequest, nothing seems to happen. :roll:

Here is the Java'script :

Code:
function switchToEnglish()
{
    var xmlhttp =  new XMLHttpRequest();
    xmlhttp.open('GET', '&lt;?php echo base_url(); ?&gt;languagesetup/setlanguage/english', true);
    xmlhttp.send(null);
    return true;
}

function switchToSwedish()
{
    var xmlhttp =  new XMLHttpRequest();
    xmlhttp.open('GET', '&lt;?php echo base_url(); ?&gt;languagesetup/setlanguage/swedish', true);
    xmlhttp.send(null);
    return true;
}


So please, what do I get wrong :question:

Thanks for reading !

#2
[eluser]Nick_MyShuitings[/eluser]
Doing XMLHttpRequests by hand is never fun. Are you not using any javascript library in your site that you could take advantage of? perhaps jquery. If not, your error is more of a javascript AJAX question than a CI question.

Provide me some of the info from FireBug or Chrome debug console, you should be able to see if the request was sent, if it was sent to the proper url, what the response was, etc.

#3
[eluser]Aken[/eluser]
Is there a reason you're defining another reference to the CI instance within the setLanguage method? The variable $this is already a CI instance that is available to every controller.

And as Nick says, use Firebug or another JS debug console to see where the request is being sent to, or if it's actually going at all. And I would suggest using a Javascript library (or at minimum, a small codebase designed for doing Ajax requests easily), as there are some browser limitations and other things that can be an issue for you and/or your users.

#4
[eluser]toopay[/eluser]
Make sure you load url helper before use base_url, then try this
Code:
function switchToEnglish()
{
    var xmlhttp =  new XMLHttpRequest();
    xmlhttp.open('GET', '&lt;?php echo base_url(); ?&gt;languagesetup/setlanguage/english', false);
    xmlhttp.send();
    // Write the response to body, remove the backslash
    document.body.\innerHTML = xmlhttp.responseText;
    return true;
}

#5
[eluser]Jilimay[/eluser]
Hi everyone,

First of all thank you for all your answers !

I tried Toopay's solution, and it actually worked :-) !

Apparently, I just had to switch the boolean to false in :

Code:
xmlhttp.open('GET', '&lt;?php echo base_url(); ?&gt;languagesetup/setlanguage/english', false);

Now, I would have two subsidiary questions for you :

- First, why is it that having this boolean on true makes the request fail ? I thought
the boolean was only here to say whether or not the browser should wait for the server's
answer, which, from my newbie's point of view, was the clever thing to do in order to
have the session updated when reloading the page !

- Then, you talked about browser limitations with javascript, what were you thinking about
exactly ?

Thanks for reading !

#6
[eluser]toopay[/eluser]
[quote author="Jilimay" date="1303819721"]First, why is it that having this boolean on true makes the request fail ? I thought
the boolean was only here to say whether or not the browser should wait for the server's
answer, which, from my newbie's point of view, was the clever thing to do in order to
have the session updated when reloading the page ![/quote]
The boolean was the asynchronous flag. True when fetching is done asychronously. False when fetching is done synchronously. See full reference
[quote author="Jilimay" date="1303819721"]Then, you talked about browser limitations with javascript, what were you thinking about
exactly ?[/quote] I also would love to know what he really means with that.

#7
[eluser]Jilimay[/eluser]
Ok, thanks for the reference. I actually did the opposite from what I wanted to do.

But what I still don't understand is why does it matter that the request is synchronous ?

Here is how I was seeing the process : the browser sends the request to the server, which modifies the session, then sends the response.
The response is not received since the request was asynchronous, but nobody cares because the only thing we wanted was to modify the session !

But i guess it is not that simple :-S ?

#8
[eluser]Aken[/eluser]
Browser limitations meaning some browsers handle Ajax requests differently (IE6 being the main culprit).

This page explain the XMLHttpRequest method very well, including the (a)synchronous differences and why they are affecting the response you're getting: http://ajaxpatterns.org/XMLHttpRequest_Call

#9
[eluser]toopay[/eluser]
[quote author="Aken" date="1303881801"]Browser limitations meaning some browsers handle Ajax requests differently (IE6 being the main culprit)[/quote]

The other trivial statement/question would be : "What If Javascript Is Not Enabled?"

When dealing with Javascript and "progressive enhancement enthusiast," someone always asks how this should work / degrade if the end user does not have Javascript enabled. While this might be a contentious answer, if your target user does not have Javascript enabled, then I don't think they should be using a single-page application. That's like asking how a user should navigate a FLEX application if they don't have Flash installed; it doesn't make sense! If we talk related with Javascript, we're not talking about building "pamphlet" sites here - We're talking about building complex, user-experience-oriented applications.

#10
[eluser]Jilimay[/eluser]
Hello again,

Ok I get your point Aken, and I read the page you linked, but that still doesn't answer my question : why does the call have to be synchronous in order to trigger the php script properly ?

Here are the http request and response when the call is synchronous :

Code:
[09:32:52.650] GET http://127.0.0.1:8888/chartProject/languagesetup/setlanguage/swedish [HTTP/1.1 200 OK 15ms]
[09:32:52.678] GET http://127.0.0.1:8888/chartProject/ [HTTP/1.1 200 OK 32ms]

And here they are when it is asynchronous :

Code:
[09:31:17.901] GET http://127.0.0.1:8888/chartProject/languagesetup/setlanguage/english [undefined 0ms]
[09:31:17.919] GET http://127.0.0.1:8888/chartProject/ [HTTP/1.1 200 OK 31ms]

The first line being the click on the flag icon, and the second the refresh of the page.

In my mind the call in itself is the same, so I am completely confused here !

Thanks for reading.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.