You get a bonus - 1 coin for daily activity. Now you have 1 coin

JSON Jquery sending data using AJAX

Lecture



transferring data in JSON format from the server to the browser .

1) The server-side ( PHP ) script forms an array with data, converts them into JSON format (using the json_encode function) and sends it to the browser. and reports headings before displaying

header ('Content-type: application / json');

echo json_encode (['data' => $ data, 'error' => $ error]);

2) On the browser side, the JS script processes the received data.

That is, all data transformations are reduced to the use of two functions.

Sending data to the server from the client (browser) is a bit more complicated.
You can send data in JSON format in the request parameters (GET or POST), i.e. just like any other data

for example? data = [{"id": "10"}, {"email": "2@gmail.com"}]) & param2, with a preliminary url encode

or in pure JSON with appropriate headers

The sending algorithm will be as follows.

1) Create a JavaScript object with the data you want to send.

2) Convert this object to JSON format.

3) Send the request to the server. In one of the request parameters we pass a string with JSON data. or at once a line but with the title that we move not the text but JSON

4) On the server side, we read the transferred data (they will come in the $_GET or $_POST array).

5) Using json_decode convert JSON data into an array. // if we didn’t give a Json header, if you’ve passed it all, then there should be an array formed by php right away

  example 

  1. transfer with title “jison” 
  $ .ajax ({
     url: '/ api / metod', 
  contentType: "application / json; charset = UTF-8" - // headers to pass
     , type: 'POST', 
  dataType: 'json' // received data format
     , 
  data: '[{"id": "15"}, {"email": "1@gmail.com"}]' // if the string is already formatted in json 
  , 
  data: JSON.stringify ([{"id": "10"}, {"email": "2@gmail.com"}]) // if the string contains arrays and javascript objects 
  , success: function (res) {console.log (res);  }}); 

  2. transfer of mixed data without a header 
$.ajax({
url: ' / api / metod'
, type: 'POST'
, data: 'jsonData=' + $.toJSON(formData)
, success: function (res) {
  console.log (res); 
}
});
JSON Jquery sending data using AJAX

Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone