• 35
Votes
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /var/www/html/cnasolution/site/application/views/question.php
Line: 191
Function: _error_handler

File: /var/www/html/cnasolution/site/application/controllers/Questions.php
Line: 419
Function: view

File: /var/www/html/cnasolution/site/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Using AJAX to set selected language in Wordpress Session

I want to use a session in WordPress to store language selected by site visitors so that I can check the session and set the language in my site. I am new to WordPress so, I cannot figure out how would I go about calling a PHP file and setting the session data using jQuery. Am I going the wrong way about doing this? Is there an easier way of storing these variables and using them to change the front-end in WordPress?

I am trying to call a custom PHP script from jQuery as :

 jQuery.ajax({        type: "POST",        url: "set-language.php",        data: 'en',  }); 

but I am getting a 404 not found error.

Download script demo [LINK] [Origin]
Download script demo [LINK 2] [Onedrive] Download script demo [LINK 2] [Google drive]

Simple Example

data = {}; data.action = 'change_language'; data.language = 'en';      jQuery.post( ajaxurl, data, function ( response ) {     console.log( response ); // just for debugging     alert( response.some_more_data );    } ); 

ajaxurl is provided by wordpress and points to wp-admin/admin-ajax.php

PHP-Code:

// place this in your functions.php or where you want function ajax_language_changer() {          $lang = $_REQUEST['language'];          // do stuff to change the language          $response = array(         'request' => $_REQUEST, // just for debugging         'what_ever_you_want' => 'mixed_data',         'some_more_data' => 'Im done',         '     );          wp_send_json( $response );      }  add_action( 'wp_ajax_change_language', 'ajax_language_changer' ); add_action( 'wp_ajax_nopriv_change_language', 'ajax_language_changer' ); 

The hook wp_ajax_nopriv_change_language is for visitors (frontend). wp_ajax_change_language is for logged-in users. In this example ajax works for both.

see demo
  • 49
Reply Report