Change PHP language $_SESSION variable with AJAX and no page reload - php

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.

Related

Code technique - jquery login with php server

It is my 2nd day developing mobile app. And for now I'm dealing with login credentials.
I'm using Intel XDK. I have an idea/logic on how the login page will work. But at some point, I'm new to jquery ajax method. What I would like to accomplish is how to successfully implement it with existing server(website).
This is the submit button code.
$(document).on("click", "#login", function(evt)
{
var email=$("#input_email").val();
var password=$("#input_password").val();
var user_data = 'email='+email+'&password='+password;
if($.trim(email).length>0 && $.trim(password).length>0) {
$.ajax({
type: "POST",
url: "www.mysite.com/app/login_user.php",
crossDomain: true,
dataType: 'json',
data: user_data,
beforeSend: function(){
$(#loader).css({display: "block" });
},
success : function(data){
$(#loader).css({display: "none"});
alert(data);},
error : function(httpReq,status,exception){
alert(status+" "+exception);
}
});
}
return false;
});
And This is my code on php server-side.
<?php
header("Content-Type: application/json");
header('Access-Control-Allow-Origin: *'); //newly added
include('../config.php');
session_start();
if(isset($_GET['email']) && isset($_GET['password'])){
$get = $_GET;
array_walk_recursive($get, 'clean');
$sql = "SELECT * FROM user WHERE //some condition here ";
$user = db::select_row($sql);
$access = 'true password';//should logged in the user, and landed to home page.
if($user['user_status'] == 'active' || $user['user_status'] == 'new' || $user['user_status'] == 'not active'){
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['user_email'];
$_SESSION['user_fullname'] = $user['user_fullname'];
}elseif($user){
$access = 'Account is deactivated!'; //Show as popup message
}else{
$access = 'Username and password didn\'t match.'; //Show as popup message
}
echo json_encode($access); //newly added
}
////////Conditional code to be added here base on $access value.
////////Send result to mobile app and respond.
////////Need some help.
?>
I hope you understand my needs. All ideas for improvement is greatly appreciated.
Edited#1: I added some line of code to my php server and some additional code to my jquery code. It is working now, it is alerting the data $access.
Question#1: How can I use the server response(e.g "$access value" is = 'true password' or 'Username and password didn't match.') to make some action on the client-side?

How can update my session using ajax?

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);
}

Wordpress Table Won't Update after AJAX / PHP (even with 200 ok response)

This is my first attempt at trying to update a database with ajax & wordpress. I am trying to set a field to a status of 'complete' when a link is clicked. Everything seems to go fine, I get a "200 ok" response from the console, and the jQuery even shows the success actions that I'm taking. However the php doesn't update the database. The proper variables are being echoed out to the console, so I know those are being set correctly. I don't know if it's my MySQL query that I'm trying or if there's something that I'm overlooking. Any help or suggestions would be greatly appreciated.
Here's my jQuery:
// Click to Complete Activity Functionality
jQuery(".complete-activity").click( function( e ) {
e.preventDefault();
nonce = jQuery(this).attr("data-nonce")
wp_user_id = jQuery(this).attr("wp_user_id")
activity_post_id = jQuery(this).attr("activity_post_id")
wp_user_id = parseInt(wp_user_id);
activity_post_id = parseInt(activity_post_id);
console.log('My wp user id is: ' + wp_user_id);
console.log('My Activity id is: ' + activity_post_id);
jQuery.ajax({
type : "post",
url : myAjax.ajaxurl,
data : {
action: "gw_complete_activity",
"wp_user_id" : wp_user_id,
"activity_post_id" : activity_post_id,
"nonce" : nonce
},
success: function(response) {
console.log('Your field has been set as completed');
jQuery('li#active-'+ activity_post_id).css('display', 'none');
}
})
}) // End click to complete activity
Here's my php code:
<?php
//Complete Activity in Database (AJAX)
add_action("wp_ajax_gw_complete_activity", "gw_complete_activity");
add_action("wp_ajax_nopriv_gw_complete_activity", "my_must_login_to_complete");
function gw_complete_activity() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "gw_complete_activity")) {
exit("No naughty business please");
}
$wp_user_id = $_REQUEST['wp_user_id'];
$activity_post_id_complete = $_REQUEST['activity_post_id'];
$date_completed = current_time('mysql', 1);
global $wpdb;
$wpdb->update (
'wp_gwactivities',
array( 'date_completed' => $date_completed, 'activity_status' => 'complete'),
array( 'wp_user_id' => $wp_user_id)
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result_add = json_encode($result_add);
echo $result_add;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
function my_must_login_to_complete() {
echo "You must be logged in to complete your activities.";
die();
}
?>
Just because you get a 200 (OK) from the requested page, doesn't mean the requested page didn't error out :) Secondly, it looks like this is going to be used in Wordpress... with that said, you can't use add_action without having wordpress loaded.
For files outside the normal wordpress install, you need to include wp-load.php include "/path/to/wordpress/wp-load.php", for example. Then you can use its functions.
After your update query ,put below code and check query in mysql directly.
print_r($wpdb->last_query);
provide your query here also if its not work.

Session value changes on ajax page when using a random value

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 ===

PHP Session ID Variable Returned With AJAX

I'm working on an AJAX login system and am not sure how to return the PHP session variable from AJAX unto the login page. My question is, how do I return the php variable unto the login page, if that is even possible. Below is the sample I created.
Login Page
<?php
session_start();
?>
<form>
<input type="text" id="username" />
<input type="text" id="password"/>
<input type="button" id="submit" />
</form>
<script type="text/javascript" >
$('#submit').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.post('ajax_file.php',
{
username: username,
password:password,
},
function (data) {
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"', 2000);
});});
</script>
Here is the ajax page. I understand that the logic doesn't make sense for the session variable to pop out of nowhere, let's just assume that is was created earlier in the page.
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
return $session_user_id = $_SESSION['user_id'];
}
You can just do the AJAX post, set the session variable to the session in the page receiving the post, and it will be stored in the session (it's the same session). In the AJAX callback forward the user to the home page.
Of course you must consider the scenario that the login credentials are incorrect.
The trick is that your JavaScript doesn't even have to know about sessions at all; you can configure PHP to use HttpOnly cookies for its session management via the respective ini setting.
I would implement the AJAX script like this:
session_start(); // start the session
if (login($username, $password)) {
// alter session to hold user id
$_SESSION'user_id'] = $user_id_from_database_or_something;
return true;
} else {
return false;
}
The AJAX complete handler looks at the return value and redirect to the homepage if it was true. Something like below (I'm assuming that the PHP return is translated into something like echo json_encode($return_value):
if (data) {
// do redirect
} else {
// login failed
}
Then, when the user comes to the homepage their browser would send a session cookie so you can determine if they're logged in.
Improving the Answer
FOr Jquery, USe function below
function sendAjax(showAllExist, controller)
{
$.ajax({
type: "post",
url: login.php,
data: yourformdatacomeshere,
beforeSend: function() {
//do whatever you want to do before request
},
error: function() {
//display in case of error
},
success: function(data) {
//display in case of error
if(data!=""){
//redirect use to home pahe
window.location.href ='homepage.php';
}else{
//display login is not correct
}
},
complete: function() {
//hide any event which you have started on beforeSend
}
});
return true;
}
Cant you just do this:
$.post('ajax_file.php',
{
username: username,
password:password,
loginSession: <?php echo $_SESSION['user_id']; ?>
},
function (data) {
//Check here if login is correct.
if correct, create this variable:
var logged= "?logged="+data.SessionID;
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"+logged+"'", 2000);
});})
When data comes back go the homepage.php with a sessionID.
on the php script do this:
if(isset($_GET['logged'])){
start_session();
$_Session['LOGGED']='true';
}
use this method which is improvised above shail answer.
your ajax file code
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
$session_user_id = $_SESSION['user_id'];// this is from your code
$responseArray = array("message"=>"success","sessionId"=>$session_user_id);
}
else
{
$session_user_id = "";
$responseArray = array("message"=>"error","sessionId"=>$session_user_id);
}
echo json_encode ( $responseArray );
die ();
then in ajax function make below changes.
var frmdata = jQuery("#logindata").serialize(); // which contains the data of username and password
jQuery.ajax({
type : "POST"
,url :'ajax_file.php'
,data :frmdata
,dataType: "json"
,success : function(data){
if(data.message == "success")
{
//redirect it to your desire page
}
else
{
//redirect it to your login page
}
}
,beforeSend: function(html){
// some loader goes here while ajax is processing.
}
});
hope this help feel free to ask anything for this answer.

Categories