2

I'm trying to load some local variables onto a page which is supposed to have different texts, depending on the user's system (or browser) language. Here is what I did so far:

A simple HTML page:

<html>
    <head>
        <title>Page title</title>
        <<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="/css/style.css">
        <script>
            $( document ).ready(function() {
                jQuery.ajax({
                    url: "login_backend.php",
                    dataType:'json',
                    success:function(response)
                    {
                        $('#loginline').html(response.first );
                        $('#passwordline').html(response.second );
                    }
                });


            });
        </script>

    </head>
<body link='#b9b5b1' vlink='#f2f0ed' alink='#908f8e'>
<table width='100%' height='100%'>
<form method='POST' action='buzz-login.php' enctype=utf-8 accept-charset=utf-8>
<tr>
<td align=center><table>

<tr>
<td><table>
<tr>
<td><div id = "loginline" class = "loginline">Test1:</div></td>
<td><input type='text' name='login' size='15'></td>
</tr>
<tr>
<td><div id = "passwordline" class = "passwordline">Test2:</div></td>
<td><input
type='password' name='password' size='15'></td>
</tr>
</table></td>
</tr>
<tr>
<td align = center><input type='submit' name='ok'
value='$login_button'></td>
</tr>
<tr>
<td align = center><font color='red'>Random msg</font></td>
</tr>
</table></td>
</tr>
</form>
</table>
</body>
</html>

login_backend.php

<?
    session_start();
    $_SESSION['locale'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);// detecting language
    include "locale/{$_SESSION['locale']}.php";//loading locale file with proper prefix
$locale = array[ //the array is filled from variables, initiated in a particular locale file
"loginline"=>"$login_line", 
"passwordline"=>"$password_line"
];
echo json_encode($locale);
?>

And lastly we have several local files which look like the following (en.php):

<?
$login_line           = "ID";
$password_line        = "Password";
?>

The big idea was to request the local variables upon page load and place them into proper divs. I'm getting no errors, but it's not working.

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
RWS
  • 538
  • 5
  • 14
  • 1
    What do the keys `first` and `second` represent? Don't see any values declared in PHP, e.g `response['pasword_line']` should work .. – dbf Apr 12 '16 at 22:43
  • Running a http request is very costly. I feel it's good if u place it on page load only. I feel it would be better to load it via ajax if the operation is going to take more time(getting data from api etc) – Arjun J Gowda Apr 13 '16 at 11:20

1 Answers1

2

The response variable inside the success callback of your .ajax request does not return a first or second key. If you look at your login_backend.php (why is it called login_backend? I don't see anything specifically concerning a login) it returns an array with keys loginline and passwordline, as in

{
  "loginline": "ID",
  "passwordline": "Password"
}

Verify this with a developer console for your browser, e.g. Firebug or similar when working with asynchronous requests.

Your .ajax request setup tells me your expecting a JSON, dataType:'json'. You should tell the PHP file (in your case login_backend.php) that the content it returns is of type JSON by setting its headers correctly.

<?php
  header('Content-Type: application/json');
  .. code ..

  echo json_encode($locale);

When using PHP's session, make sure you close the session when you don't need it anymore. Sessions are being locked when used, unlock the session with session_write_close when you don't write or read from the session.

session_start();
// detecting language
$_SESSION['locale'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// loading locale file with proper prefix    
include "locale/{$_SESSION['locale']}.php";
/* close session lock */
session_write_close();

It's in general a good thing to start writing your own material before using any 3rd party source that solves localisation for you. Though your setup has a few steps too many.

First you build an array $locale in login_backend.php from a list of variables included from 'locale/{$_SESSION['locale']}.php' where you copy each variable to its equivalent key, even the variable/key names are almost identical.

You can make this simpler by letting the file en.php return this array immediately

<?php
  /** file: en.php */
  return [
    'login_line' => 'ID',
    'password_line' => 'Password'
  ];

and catch the returned array in a variable and let login_backend.php immediately encode the array to a json string.

Besides that, make sure you always proper check

  • The existence of keys in globals/session, e.g. isset($_SESSION['locale']) or array_key_exists('locale', $_SESSION') to properly handle errors.
  • Make sure you know the difference between include and require, see this question
  • Never assume a file exists based on a filename from an external (3rd party) source.
Community
  • 1
  • 1
dbf
  • 3,278
  • 1
  • 24
  • 34
  • Thank you for useful tips. For now I have made the following modifications to the jquery function: success:function(response) { $('#loginline').html(loginline); $('#passwordline').html(passwordline); } And the login_backend.php has been added with header('Content-Type: application/json'); I used firebug and determined that the php returns proper data, however the jquery does not substitue the divs with proper values (now they are blank for some reason). Could you please help me figure out whats wrong with the jquery? – RWS Apr 13 '16 at 19:45
  • If you made the changes I proposed to the _backend\_login.php_ file, you should use `response.password_line` instead or `response['password_line']` – dbf Apr 13 '16 at 21:05
  • $('#loginline').html(response['loginline']); It worked, thank you very much! – RWS Apr 14 '16 at 07:48