skip to Main Content

I know that JSON can be used between 2 web servers, for example facebook API provides some infos using aFile.json so my website need to handle it using PHP’s json_decode() function,

the problem that I can’t imagine any pratical situation wherein we can use it between a server and his client to exchange data. If the client request for some data, the server will use either SQL to retrieve them from a database or a JSON recieved file or whatever else… but finally he will respond only by an HTML file (& probabely some images) so the client’s browser can interpret it,

Am I wrong and the JSON files can be sent to the client ? then why ?
I readed also that JSON is used to communicate between PHP and javascript in the same server, can you give me an example of this case ?

2

Answers


  1. You can think about it in this way:

    1. You go to the website X, and your browser (client) sends request to the server, for particular page. In this case, server will respons with HTML page wich will be rendered by your browser to you.
    2. You already are on website X, your browser already rendered a page for you, and now you have input with newsletter subscription, you put your e-mail in this input and click ‘subscribe’. Here one of the scenarios is that JavaScript will post your e-mail to the server using JSON-format, and server will respond to the JavaScript associated with your HTML some confirmation (also in JSON-format), which will be displayed for you.

    This second scenario might be used in order to avoid reloading the page which is already render for You.

    You can go to developer tools in your browser, you can display section network, and You can observe different HTTP messages which are sent back and forth between client and server.

    For more information I suggest reading https://developer.mozilla.org/pl/docs/Web/HTTP because they have nice documentation regarding HTTP there.

    Login or Signup to reply.
  2. JSON is basically a JavaScript Object (JSON stands for JavaScript Object Notation) in text.

    You can fetch JSON data from the server with an AJAX call. This is a simplified JavaScript example that makes an AJAX call and then assigns the response JSON to var myObj.

    var myObj, xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       myObj = JSON.parse(xmlhttp.responseText);
      }
    };
    xmlhttp.open("GET", "/example", true);
    xmlhttp.send();
    

    Servers response

    {"name":"John", "surname":"Doe"}
    

    Printing the received data to HTML element “demo” after the response has been assigned to myObj

    document.getElementById("demo").innerHTML = myObj.name + " " + myObj.surname;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search