How to change server side language cookies like client side using Ajax?

Server-Side Ajax Call (Fix)

in your language.ini.php you have to change the line:

setcookie ('language', 'es', time()+60*60*24*365, '/', 'es.example.com');

to :

 setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');

because if you specify domain of cookie in header, it will be none host-only cookie and, in your both example.com and es.example.com will be use.

according to RFC6265

How Cookies Works

  1. Cookies usually will be requested to set by server-side and browser will save them.

  2. The Browser sends Cookie in every Request.

  3. Server can access cookie from the Request from browser.

Cookies Are Essential Since Http is Stateless Protocol, and Server want to Associate a data to a client and use it in next requests .

A Preferable Scenario (Desired Solution)

as long as your user decide to view your site in which language they prefer. and your server will not doing nothing with it (no controls, no security threads).

you can use a shortcut .

Set The Cookie in Your Client-side

and just remove the language.ini.php file.

you can do this by pure Javascript and when the user try to navigate in browser. his/her requests will be sent via new cookie which javascript has been set.

just you have to be aware TO NOT Enable HTTP-Only Flag on Cookie (Which can prevent Js t manipulate Cookie).

Jquery Example:

$.cookie('language', '', { expires: 365, path: '/', domain: 'example.com' });

instead of sending an ajax request your js can looks like this:

$(function() {
    $(".lang").click(function(e) {
        e.preventDefault();
        var language = $(this).attr('data-value');
        $.cookie('language', language, { expires: 365, path: '/', domain: 'example.com' });

    });
});