All posts by vnikolchev

Favorite photos and places

Using jQuery and JSON to validate and save data sent from web form to server with PHP Zend Framework 1

This is a very basic example that demonstrates how to pass, validate and save data with PHP, JSON and jQuery from a web form to the server without refreshing the browser. It covers usage of PHP Zend Framework 1.

The main idea in short:

  1. Visitor submits a web form that passes some key/value pairs data with a jQuery (Ajax) post method to the server Zend action;
  2. The incoming data will be validated on the server side Zend action and:
    1. In case of success:
      1. The data will be saved to the server (database) and.. ;
      2. A success message will be passed back to the Zend view HTML form.
    2. In case an exception occurs during the validation or during attempt to save the data: the server will send back a message with the exception without saving the passed data to the database;
  3. Above the web form will be displayed a success/exception message from the server as a result of the above operations, assuming the visitor can submit the form again.

In this paradigm JSON is used to handle the passing data between the client side JQuery and the server side Zend action.

Files involved:

1) Zend view file containing the web form HTML code. The file was called “profile.phtml”:


2) Javascript file containing the jQuery code. In this case:


3) Zend controller file called “UserController.php” that will validate and pass the data to the Zend model in order to save/update a database record:


The code

1) The Zend view file (profile.phtml) contains the following code:

Notice the 2 div layers above the web form:

<div class=”alert alert-success” style=”display: none”><strong>Saved!</strong> <span id=”success-text”></span></div>
<div class=”alert alert-error” style=”display: none”><strong>Error!</strong> <span id=”error-text”></span></div>

They are both intended to hold and display a success or exception alert sent back from the server as a response. By default the two layers are hidden.

2) The jQuery code in /js/userprofile.js:


3) The Zend controller file (UserController.php) contains this code:

Doing some validations here, before saving the changes, allows us to work on the server. It is much easier, safer and reliable than doing this with a javascript function directly in the web browser. The good thing is that the communication between the client and the server is still behind the scenes because we use Ajax to exchange the data with the server without reloading the web page.

Installing WordPress xili-language plugin

Installing xili-language plugin

Activity Diagram
Fig. 1. Main activity diagram for “translating” a WordPress website with xili-language


This is a short manual that represents a sample installation of xili-language WordPress plugin. The main aim of this operation is to get a WordPress website fully translated into multiple languages including some specific settings and patches that should help you receive all the interface elements translated: like menus, text labels and sliders. This manual covers the issue with showing language flags instead of the names of the languages in language selector menu.

For a sake of simplicity only one language will be added. However adding more languages is straightforward.


  1. You need a working instance of WordPress. This example covers the last stable ver. 4.1.
  2. You need a WordPress theme installed that is translation-ready. How to recognize if your theme is translation ready? Look in folder:

    You should see a POT file there and eventually some MO and PO files.
  3. You need permissions to access the WordPress admin panel in order to install the language plugin.

PART 1. Main Procedure

Install and activate the xili-language plugin

Go to “Plugins” >> “Add new”, and when the page opens search for “xili-language” keyword. Submit the form. Install the plugin.
Fig. I. 1. Installing the plugin

Add a language

After the installation finish you will see the plugin among the installed plugins. Open it’s settings and add a language you need. Choose the language from the drop down menu (Bulgarian language in my case). You can enter an Order: 1 for example, if you want it to appear below the English language that is with Order 0 in the list. You may notice that the Bulgarian flag icon is missing (fig. I. 2.) but don’t worry – this specific icon is for the admin page only.
Fig. I. 2. Go to plugin setting

Fig. I. 3. Install your second language

Check the new language files

Go to “Managing Language Files” tab and check out if you have all the language files installed. Just for any case push “Check again before downloading mo” and then “Download mo” and the system should do everything right for you:

  • in case you don’t have the files they will be downloaded to the correct folder;
  • in case you have the files they will be updated
    Hint: You can see these (.mo) language files through FTP client in folder “wp-content/languages”. Do not edit them manually. The system takes care.


Fig. I. 4. Check and download / update the language files.

Check the theme MO and PO/POT language files

The MO file (like and the POT file (a language template) are related to the current theme. The MO file is a binary created from POT file. The MO file translates the theme to the additional language against the main language in your theme (English in my case is the main language). In case your theme is translation-ready it should include by default some popular languages like FR, DE, etc. However it most probably wont include MO file for translating a rare language like Bulgarian. Look for the MO/PO/POT files inside the theme language folder:

(best approach is to use FTP client). Options:

  • In case you don’t have the bg_BG.po and files you should easily create them by yourself:
    • Download the POT template file in order to create your MO file from it;
    • Open it with a tool like POedit;
    • Translate the strings inside against the English theme strings;
    • Save a MO file from it:
    • Upload both and bg_BG.po to the theme language directory. The system uses the binary .mo file. The .po file may be used later from you for further modifications of the translation.
  • In case you have the bg_BG.po and you are ready to go. If you want you can edit the po anytime to create a new Remember that the system needs the .mo file only.

Create / edit your content in the additional language

Let’s create a new page in English, save it, and then translate it to Bulgarian:

  • First create your page;
  • At the bottom you see a tool section with two language radio buttons. First select English language and save the page;
  • Then click the link “Create and edit” in row with the second language (fig. I. 6.);
  • This creates a new draft page in Bulgarian and maps it to the first one (the English one). Translate the texts and save it to finish;
  • Repeat these steps and create 2 more pages.

Fig. I. 5. Create / edit your content to map it to a language

Fig. I. 6. Create the translated version of the file for the second language

Create two menus: one menu for each language

These menus will appear on the website and will switch between each other when language changes.
On the left admin page menu go to “Appearance” >> “Menus”:

  • Create the first menu (for English version).  Name it “English main menu”. Add all the English pages to this menu. At the left sidebar accordion open section “Pages” and check the English pages that you have previously created. Add them to the menu. Then you can rearrange their links inside the menu;
  • Save the menu. NOTE: DO NOT CHECK “Top primary menu” checkbox. Just save the menu;
  • Create the second menu (for Bulgarian version). Name it “Bulgarian main menu”. Add all the Bulgarian pages to this menu. At the left sidebar accordion open section “Pages” and check the Bulgarian pages that you have previously created. Add them to the menu. Then you can rearrange their links inside the menu;

Fig. I. 7. Add English pages to English menu and respectively the Bulgarian pages to the Bulgarian menu

Now create a third menu (for combining the other two menus in it).

Name this menu “Main Multilingual Menu”. This menu will contain both the two languages menus in it. It will contain also a language selector bar with links to each language.

  • From the sidebar accordion tab called “[xili] Language list“ select radio button “Nav Menu Singular” and add it to the menu. This adds a language list insertion point with language links (selectors for English and Bulgarian);
  • Check the “Top primary menu” checkbox in Menu Settings, Theme locations. It is very important, otherwise this approach don’t work;
  • Save the menu;
  • Now open the sidebar accordion tab called “[xili] Menu Selection”, in the combo box dropdown select “English main menu” for English and “Bulgarian main menu” for Bulgarian, check the box “Check before adding the menu” and push “Add to menu” button;
  • You play with the positions of the points (drag and drop to reorder);
  • Save the menu;
  • Now, if you open the “Menu list insertion point” you will see a text like:

    One menu from this list of menus will be inserted here according current language of displayed webpage.
    English main menu= [en_us] ( english-main-menu )
    Bulgarian main menu = [bg_bg] ( bulgarian-main-menu )

This means you have successfully combined the two languages menus.



Fig. I. 8. Combining the 2 languages menus in one main menu. Read the description above carefully.



Fig. I. 9. This message means you have correctly added the 2 languages in the main XILI menu.

That’s all! Now go to your website and switch between the two languages.


The pages mapped to each language are narrowed by the XILI-LANGUAGE plugin. Each language has its own menu that switches with the other content. All the other webpage interface parts are translated from the theme MO language file (

PART II. Showing flags in language selector menu

The aim of this part is to show flags instead the languages names in the menu selector that switches the languages.

Edit and save the (child) theme functions file

Open the theme functions file:

Inside the code of this file navigate to the function that setups the theme (in my case it is “spacious_setup()”) and call a function “add_theme_support ( ‘custom_xili_flag’)” at the end of it, like shown in the following figure:


Fig. II. 1. Call this function at the end of spacious_setup() and save the file.

It is recommended to install a child theme and edit the functions file of the child theme. If you edit the functions file of the main theme you take a risk to loose all your changes in case you update the main theme later. Google for information on how to install a child theme.

After refreshing the page you will notice a new link under left menu, “Appearance” >> “xili Flag Options”. Enter it. This is a powerful xili toolbox that offers an user-friendly interface to use images assigned as a flag of a language in media library.

Upload in media library the languages flags icons

Now it’s time to upload and set as a flag each of the two flag icons images.

  1. Go to media library in the left admin menu “Media” >> “Library” and upload the first flag;
  2. When the flag is uploaded choose the link to edit it (fig. II. 2.);
  3. Inside the edit tool set the file as a flag, choose its language, and push Update to save the settings (fig. II.3.);
  4. Repeat it for the other language.


Fig. II. 2. Go to edit the uploaded file.


Fig. II. 3. In edit tool set the image as flag, choose its language and update it.

Go to XILI flag options and set the flags

  1. Open from the main left menu the tool under “Appearance” >> “xili Flag Options”;
  2. Check “Menu with flags” check box (arrow 1 in above figure);
  3. You must see the language flags (arrow 2). In case they are missing here go to the icons file in Media Library and check if they are set as language flags;
  4. Check and modify if you need the css properties (arrows 3-6);
  5. Save the changes.

That’s it! Go to your web page and refresh it. You should see the flags in your language menu (fig. II. 4).


Fig. II. 4. The language flags in main menu

PART III. Patching a slider to support the two languages

For this example we will use the “spacious” theme again. Note that “spacious” jQuery slider does not support multiple languages directly. But of course it can be adopted with a little patch inside one PHP file. So choose this approach: we are going to adopt a condition that the slides #1 and #2 should appear in Bulgarian version of website, and the slides #3 and #4 should appear in English language. In order to achieve this:

  1. Create the four slides: go to “Appearance” >> “Theme Options” >> tab “Slider” and:
    1. save the Bulgarian texts/images under slides #1 and #2;
    2. save the English texts/images under slides #3 and #4.
  2. Activate the slider with checking the box in its tab and save the changes;
  3. If you go to the front page and refresh it you will see all the slides in your default language;

Now open this file:

and edit a little part of its content: locate the function “spacious_featured_image_slider()”. Edit the first few lines that originally look like this:


To this:


Notice this very small piece of logic added that basically says:

That’s it! Save the file and refresh the home page. Switch between the languages and you see the slides switches as well.

It is recommended to install a child theme and always edit the files of the child theme. If you edit the files of the main theme you take a risk to loose all your changes in case you update the main theme later. Google for information on how to install a child theme.


Морфология със Sphinx. Синонимен речник “wordforms”.

Това е допълнителна морфологична функционалност във Sphinx, която включва употреба на речник с множество двойки думи-синоними. Речникът е опционален в конфигурацията на Sphinx и когато е включен бива обработван от Sphinx преди употреба на стеминг механизма. В случаите, когато термът попада в този речник, стеминг механизмът не се включва за този терм и така се предоставя по-прецизен контрол и също възможност за използване на стеминг изключения със синоними.

Думите-синоними са групирани по двойки на всеки ред.

Синтаксисът е: [разглеждай-тази-дума] > [като-тази-дума]

Първоначално файлът може да бъде произведен с помощта на spelldump инструмента:

Където .dict и .aff файловете са главният речников файл, в ispell или MySpell формат, и неговият афиксен файл; Обикновено имената им спазват конвенцията [language-prefix].dict и [language-prefix].aff и са достъпни с повечето Linux дистрибуции, и също могат да бъдат намерени онлайн.

След като бъде генериран wordforms файл в него могат да бъдат добавяни, редактирани или изваждани двойки думи. Еднократно се описва път до него в конфиг. файла:

След редактиране на този речник е необходимо пълно преиндексиране за да се приложат промените.

Пример за свързване (мапинг) на синонимни форми

В макроикономиката и финансите британският термин “gear” е синоним на американският “leverage”. Задача е да създадем синонимна връзка вежду тези термове, която да работи и при търсене на всички техни морфологични форми. Това в wordforms се описва така:

Оригинално съдържание на wordforms файла:

(така няма връзка между двата терма)

Модифицирано съдържание на wordforms файла:


Така при търсене на “gearing” или “leverage” резултатите ще включват и документи, съдържащи и двата терма, както и всички останали техни морфологични форми.

След редактиране не забравяйте да преиндексирате за да приложите промените.