I'm using a session for setting language
if(!isset($GLOBALS['lang'])){
$GLOBALS['lang'] = 'en';
}
Then I'm using ajax to update this:
var lang = 'no';
$.ajax({
type: "POST",
url: url,
data: {
lang : lang
},
success: function (data) { (...) }
});
The file being called looks like this:
global $lang;
if(strlen($_POST['lang']) == 2 ){
$lang = $_POST['lang'];
$result = array('lang_set' => $lang);
echo json_encode($result);
}
But my global session is not changed. I'm guessing this is due to the fact that lang.php uses another session instance.
I'm using Wordpress so I'm looking into if I can use some of the built in functions for this purpose. But I'm wondering if I can use PHP sessions for keeping track of selected language? Or do I have to use another method like adding selected language to my url?
UPDATE
Thanks to Ghost, I made it work. If you are using Wordpress, I'm doing the following in functions.php:
// Initialize session
if(session_id() == '') {
session_start();
}
// Set lang session with default language
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'no';
}
//globals
$GLOBALS['lang'] = $_SESSION['lang'];
If you want them to persist on the entire application, use sessions:
session_start();
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'en';
}
Then on the other:
session_start();
if(strlen($_POST['lang']) == 2 ){
$_SESSION['lang'] = $_POST['lang'];
$result = array('lang_set' => $_SESSION['lang']);
echo json_encode($result);
}
Related
I'm developing a multilingual site (es and en), and I need to change the language of the whole site when the user clicks on any of the language buttons. I store the session variable in config.php and load the page in the selected language with the require statement:
<?php
session_start();
if (!isset($_POST['lang']) && (!isset($_SESSION['lang']))) {
$_POST['lang'] = 'en';
$_SESSION['lang'] = $_POST['lang'];
} else if (isset($_POST['lang']) && $_SESSION['lang'] != $_POST['lang'] && !empty($_POST['lang'])) {
if($_POST['lang'] == 'en')
$_SESSION['lang'] = 'en';
else if ($_POST['lang'] == 'es')
$_SESSION['lang'] = 'es';
}
require "lang/" . $_SESSION['lang'] . ".php";
echo $_SESSION['lang'];
?>
en.php
<?php
$lang = array(
'mainTitle' => 'What is our business?',
'mainDescription' => 'Our description'
);
?>
I then make an AJAX call in main.js to change the session variable when any of the language buttons are clicked
function loadDoc(str) {
$.ajax({
type: 'POST',
// this is to prevent cached results
url: 'php/config.php?t=' + Math.random(),
data: {
lang: str
},
success: function(result) {
console.log('Session language: ' + result)
},
})
}
$('.langContainer .es').click(() => {
loadDoc('es')
})
$('.langContainer .en').click(() => {
loadDoc('en')
})
While the AJAX success function returns the changed session variable, the call doesn't change the language of the site until I reload it, which is kind of frustrating.
This could work perfectly with reload by sending a GET request from any of the buttons with anchor tags, but I want to know if it is possible to update the session variable with AJAX so that the content changes in the appropriate language without refreshing the page.
I'm starting with PHP, so I have no idea what's going wrong. I'm trying to update some value in my $_SESSION var using a function, but is not working.
First of all, I started the session and set a default value to the session if it is "undefined" in my header.php:
<?php
session_start();
if (!isset($_SESSION["locale"])) {
$_SESSION["locale"] = 'pt_BR';
}
?>
Then I have some ajax which calls my PHP function.
$('#change_locale_br').click(function() {
$.ajax({
type: "POST",
url: "i18n/i18n_functions.php",
data: { action: "changelocale", new_locale: "pt_BR" },
success: function() {
}
});
});
After in the php file, I have the following code:
<?php
function changelocale($l) {
$_SESSION["locale"] = $l;
}
if(isset($_POST['action']) && $_POST['action'] == 'changelocale'){
$l = $_POST['new_locale'];
changelocale($l);
}
?>
So the changelocale function is being called with the different values (pt_BR, es and etc), but after called it doesn't really change the $_SESSION["locale"] value.
I made a lot of research and NONE of the suggestions made here or in the PHP documentation page worked. Does someone knows what could be done in this case?
Thanks in advance.
You need to include session_start() at the top of your page, which you intend to set or access $_SESSION information.
Here is the solution: I called session_write_close(); (which is used to assure session data will be "unlocked", since php doesn't allow concurrent writes) right after setting the default values for the session in my header.php:
<?php
ini_set('session.cookie_domain', 'localhost');
if(!isset($_SESSION)) session_start();
if (!isset($_SESSION["locale"])) {
$_SESSION["locale"] = 'pt_BR';
}
session_write_close();
?>
Then in my changelocale.php I called the session_start() and at the end called the session_write_close(). It's like this now:
<?php
if(!isset($_SESSION)) session_start();
function changelocale($new_locale) {
$_SESSION["locale"] = $new_locale;
}
if(isset($_POST['action']) && $_POST['action'] == 'changelocale'){
$l = $_POST['new_locale'];
changelocale($l);
}
session_write_close();
?>
For me this is something new, so I am just researching this and trying to understand it.
As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.
Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck.
I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?
The problem is that when I attach a database to it, I would need to consider all inputs that can happen.
How do I specify a specific php function when using jquery & ajax?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:
url: "function.php?action=functionname"
or:
data: {
name: 'myname',
action: 'functionname'
}
Then in PHP, you can access that attribute and handle it:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
Implementation example:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
You are actually quite close to what you want to achieve.
If you want to specify which function will be called in PHP, you can pass a variable to tell PHP. For example, you passed request=save in AJAX, you can write the PHP as follow:
$request = '';
switch(trim($_POST['request'])) {
case 'save':
$player_name = (isset($_POST['playername']) ? trim($_POST['player_name']) : 'No Name'));
saveFunction($player_name);
break;
case 'load':
loadFunction();
break;
default:
// unknown / missing request
}
EDIT: You can even pass along with other parameters
This may not be exactly what you are looking for but it can help some others looking for a very simple solution.
In your jquery declare a variable and send it
var count_id = "count";
data:
{
count_id: count_id
},
Then in your php check if this variable is set
if(isset($_POST['count_id'])) {
Your function here
}
I currently have the following function in my functions.php which checks if a username exists in the DB.
function check_username() {
$username = $_POST['user'];
if ( username_exists( $username ) ) {
$return['user_exists'] = true;
}
else {
$return['user_exists'] = false;
}
echo json_encode($return);
die();
}
add_action('wp_ajax_check_username', 'check_username');
I'm using Ajax to call that function with an appropriate username:
$.ajax({
url : "http://examle.com/wp-admin/admin-ajax.php",
type : "GET",
dataType : "json",
cache : false,
data : {
action : 'check_username',
user: 'test'
},
success : function (json) {
if (json.user_exists) {
alert(json.user_exists);
}
}
});
The problem is that $username returns null instead of test. I've been trying for several hours now different combinations yet they've all returned null.
Assigning this makes the above php function work $username = 'test'; so I'm pretty sure this isn't an issue with the php code.
So my question is, how do I get the variable $username to listen and fetch the correct parameter instead of null?
Thanks
It's because ajax is submitting a GET variable, and php is looking for a POST variable. Either change ajax type to POST or change php to use $_GET['user'].
I am trying to prevent users from accessing my POST/AJAX files directly. I have decided to create a random token I call it "nonce_key". This key is created using a SESSION and then I pass it via POST. If the SESSION key is the same as the POST then I allow access. The problem is that sometimes it does not work.
Here is my workflow:
I have a single select on my index.php that when the user changes its value it calls "change_status.php" via ajax.
For some reason the SESSION key set on index.php is not the same value as the SESSION key on change_status.php.
I have the following code in my functions.php file
function nonce_key()
{
return hash('crc32b', time());
}
Then in my index I have
session_start();
require_once 'functions.php';
$_SESSION['nonce_key'] = nonce_key();
echo '
<script type="text/javascript">
$"#change_status").bind("change",function() {
var form_data = {
nonce: "'.$_SESSION['nonce_key'].'",
id: $("#id").val(),
};
$.ajax({
type: "POST",
url: "change_status.php",
data: form_data,
success: function(result) {
$("#message").slideDown("slow").html(result);
}
});
});
</script>'
;
Finally in my change_status.php file I have
session_start();
require_once 'functions.php';
if(isset($_SESSION['nonce_key']) && isset($_POST['nonce']))
{
if($_SESSION['nonce_key'] == $_POST['nonce'])
{
change_app_status($_POST['id']);
} else echo 'Nonce Invalid';
} else echo 'Not Allowed';
check that $_POST has the hash. And you have no need in require_once 'functions.php'; in change_status.php. And you can make one if less by using ===