Hello! That would seem to be a simple example. The user enters the text, presses the button, the reboot does not occur (AJAX technology), the data gets to the server and is processed (convert to upper case). If the request is successful, the word Yes and the data from the server will be displayed, if not, the word Error. It's simple, but it turned out not all. Look at the code, what's wrong?

index.html

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>New Страница</title> <!-- подключаем библиотеку онлайн через Google CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <form action="a.php" method="POST"> <input type="text" name="a" /> <br /> <br /> <button type="submit">OK</button> </form> <p></p> <br /> <br /> <label></label> <script> $(document).ready(function () { $('button').click(function() { //преобразуем данные формы в строку, но нам же нужен формат JSON //var data = $('form').serialize(); //создаем объект данных var obj { a: $('[name=a]').val() } //превращаем объект в строку формата JSON var strInForm = JSON.stringify(obj); $.ajax({ url: "a.php", cache: false, type: "POST", dataType: 'json', data: strInForm, success: function (str) { $('p').text('Yes!'); //превращаем строку формата JSON в массив var ara = JSON.parse(str); //обращаемся к массиву по индексу $('label').text(ara[0]); }, error: function() { $('p').text('Error!'); } }); }); }); </script> </body> </html> 

a.php

 <?php //строковые данные должны быть в кодировке UTF-8 header('Content-type: text/html; charset=utf-8'); //обычный способ, строка пришла на сервер //$str = $_POST['a']; //но теоретически, должна ведь приходить строка, которую //мы превратили из объекта в строку формата JSON //и она должна соотвествовать строке, указанной в data: strInForm $str = $_POST['strInForm']; //теперь превращаем эту строку в массив, так как она может //иметь несколько значений $ara1 = json_decode($str); //что-то делаем на сервере, преобразуем строку в верхний регистр $str = strtoupper($ara1[0]); //теперь будем отправлять строку обратно //помещаем строку в массив $ara2 = array($str); //кодируем массив в строку формата JSON $str = json_encode($ara2); //возрващаем строку в формате JSON echo = $str; ?> 

    3 answers 3

    In your code, an error on error and error chases.

    php - the last line should not be echo = $str; and echo $str; and too many strange operations being in a code that remains a mystery to me.

    html - the button type does not submit but button , because otherwise it sends data with a page reload in any case. If you need a button then you need to remove the default action ( event.preventDefault() ).

    javascript - JSON.parse not needed if you have dataType === json . The answer and so will come in JSON . You send an object with property a and read PHP strInForm ( //$str = $_POST['a']; - the correct version).

    In general, you have too many errors in the code that make it difficult to figure out exactly where the joint is. Although it is possible as soon as you fix everything it will work;)

    • It is disturbed by the fact that this is a site with questions, and not ala "here's a curve code for you, but for some reason it does not work, and since I'm too lazy to do everything for me." And all these errors were revealed when I checked this code at my place. You said that the code is not working - I said why. - DOC_tr
    • Dear DOC_tr, as I understand it, the code did not work for you ... You identified errors, but the code did not work for you ... - Sergey

    Fixed a few things:

    1. Inserted sign =

       //создаем объект данных var obj **=** { a: $('[name=a]').val() }; 
    2. Added return false; buttons to the end of the click event handler return false; so that the button does not work to send the form.

    3. Fixed echo = $str; on echo $str; .

    UPD

    Updated the code, now the data transfer is working.

    Corrections:

    1. Removed var strInForm = JSON.stringify(obj); . I simply $.ajax() obj object as the value of the data property when calling $.ajax() .

    2. Removed json_decode($str); in PHP, data comes in its normal form. You only need to encode the data in JSON when returning the result of the PHP script.

    3. Fixed type: "POST" on method: "POST" .

    4. I am returning from PHP not a numbered array with one element [$str] , but an associative array ['result' => $str] .

    5. In the success handler, renamed the str parameter to data , removed var ara = JSON.parse(str); - data comes in the form of a JS object (you do not need to handle JSON in any way). I get the result by the result index from the variable data : data['result'] .

    HTML:

     <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>New Страница</title> <!-- подключаем библиотеку онлайн через Google CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <form action="a.php" method="POST"> <input type="text" name="a" /> <br /> <br /> <button type="submit">OK</button> </form> <p></p> <br /> <br /> <label></label> <script> $(document).ready(function () { $('button').click(function() { //создаем объект данных var obj = { a: $('[name=a]').val() }; //превращаем объект в строку формата JSON //var strInForm = JSON.stringify(obj); $.ajax({ url: "a.php", cache: false, method: "POST", dataType: 'json', data: obj, success: function (data) { $('p').text('Yes!'); //превращаем строку формата JSON в массив //var ara = JSON.parse(str); //обращаемся к массиву по индексу $('label').text(data['result']); }, error: function(e) { $('p').text('Error!'); } }); return false; }); }); </script> </body> </html> 

    Php

      <?php //строковые данные должны быть в кодировке UTF-8 header('Content-type: text/html; charset=utf-8'); //обычный способ, строка пришла на сервер //$str = $_POST['a']; //но теоретически, должна ведь приходить строка, которую //мы превратили из объекта в строку формата JSON //и она должна соотвествовать строке, указанной в data: a $str = $_POST['a']; //теперь превращаем эту строку в массив, так как она может //иметь несколько значений //$ara1 = json_decode($str); //что-то делаем на сервере, преобразуем строку в верхний регистр //$str = strtoupper($ara1[0]); $str = strtoupper($str); //теперь будем отправлять строку обратно //помещаем строку в массив $ara2 = array('result' => $str); //кодируем массив в строку формата JSON $str = json_encode($ara2); //возрващаем строку в формате JSON echo $str; 
    • Hello Vladimir Serykh! Your answer is the standard! That's it in this format should be the answers. Separately made mistakes. Shows the full code that you can insert and test! But, the code "a little bit" does not work. Data goes to the server and ... do not come. I will correct the code and add it in the question. - Sergey
    • I updated the code yesterday. If he works and helped you, please mark my answer. - Vladimir Serykh

    Heavy preface ... As I understood the purpose of JSON. The main task of JSON is to transfer data between client and server and back.

    Theoretically, we should turn the data on the client into a JSON object, and then use JSON.stringify() turn it into a string to be sent to the server.

    On the server, we need to turn this string into an array using json_decode () to work with this data. After all, we are already working with them as with elements of the $_POST array, in this example $_POST['a'] , and theoretically should come at a time $_POST['strInForm'] , we after all indicated this line data: strInForm in functions $.ajax() . That is, in one cell of the $_POST array comes a string in JSON format, which we must turn into an array. I thought so ...

    Next, we did something with this array data and now we have to turn it into a string again using json_encode() and send it to the client.

    On the client, this string needs to be turned into an array using JSON.parse() . I thought the same way ...

    In general, I was mistaken as I could.

    1) we type="submit" on type="button"

    2) the creation of the object

     var obj = { a: $('[name=a]').val() }; 

    and turning an object into a JSON string

     var strInForm = JSON.stringify(obj); 

    "for some reason" does not work, you will have to use the usual option

     var strInForm = $('form').serialize(); 

    3) the transformation of a JSON format string sent from the server to the same “for some reason” array does not work

     var ara = JSON.parse(str); 

    therefore, we refer to this line as an already prepared array

     $('label').text(str[0]); 

    4) a.php redid the file completely.

    5) Another error occurred, if the user enters a word in Russian, then the Abra-Kodbra will be displayed. Perhaps the transcoding problem can be solved with JSON_UNESCAPED_UNICODE in PHP5.4, but I have a lower version.

     $str = json_encode($ara, JSON_UNESCAPED_UNICODE); 

    index.html

     <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>New Страница</title> <!-- подключаем библиотеку онлайн через Google CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <form action="a.php" method="POST"> <input type="text" name="a" /> <br /> <br /> <!--исравляем type="submit" на type="button"--> <button type="button">OK</button> </form> <p></p> <br /> <label></label> <script> $(document).ready(function () { $('button').click(function() { var strInForm = $('form').serialize(); $.ajax({ url: "a.php", cache: false, type: "POST", dataType: 'json', data: strInForm, success: function (str) { $('p').text('Yes!'); //обращаемся к массиву по индексу $('label').text(str[0]); }, error: function() { $('p').text('Error!'); } }); }); }); </script> </body> </html> 

    a.php

     <?php //строковые данные должны быть в кодировке UTF-8 header('Content-type: text/html; charset=utf-8'); //строка пришла на сервер $str = $_POST['a']; //что-то делаем на сервере, преобразуем строку в верхний регистр $str = strtoupper($str); //отправляем обратно, помещаем строку в массив $ara = array($str); //кодируем массив в строку формата JSON $str = json_encode($ara); //возрващаем строку в формате JSON echo $str;