Difference between transporting data in JSON and String

9

I'm finishing building a site in PHP with the MVC architecture, the next step is to integrate the application (which only has the interface) with the core ( controller ) site, to fetch information from the database. data. This will be done with Ajax because the application is hybrid, in HTML , with Intel XDK .

I want to know the best way to transport this data:

  • Sending Ajax to the site and returning a JSON , thus manipulating the array to use in the application.

  • Sending Ajax to the site and mounting it with string with code HTML and returning it to the application to use this HTML in its interface.

I see the second best option because of my greater familiarity with PHP , but which of the two options requires less the Internet speed of the device and compromises the performance of the app less? I know it's a theory question and you risk being denied, but in my view it's a valid question, not based on opinions as it derives from performance rather than what you think is best.

    
asked by anonymous 17.05.2016 / 05:06

5 answers

4
  

Sending Ajax to the site and returning a JSON, thus manipulating the array to use in the application.

In this case, the required JavaScript code will be much larger , since it contains the logic to display the data.

This means that you will have to load more JavaScript before displaying the data .

But this can be paid over time if the data is loaded multiple times without reloading the page, since the amount of data transmitted is less per request.

This approach tends to show better performance , but also greater complexity and soon your code base can become chaos unless you and the other team to be disciplined developers and write modular JavaScript (AMD, ES 6).

  

Sending Ajax to the site and mounting it to a string with HTML code and returning it to the application to use this HTML in its interface.

JavaScript tends to be much simpler and more concise , but the amount of data transmitted per request is much greater .

Changing in kids, the site loads faster, but with each new asynchronous update it will consume a bit more bandwidth and processing on the server.

Another problem with this approach is that it can be complex to keep page snippets separate from the main page that are now rendered within the context of the page, sometimes independently. Without good organization and a good rendering engine this tends to generate spaghetti or duplicate code.

  

Normally it pollutes the backend code with infinite HTML tags being concatenated

Not necessarily. In PHP you can have snippets of templates that can be rendered independently or in conjunction with the page. Some frameworks allow you to create components or widgets that work that way.

  

You prevent that ajax url from being used in other parts of your project, because not everyone who needs those data needs that HTML.

Rendering HTML definitely engages the service with your page, but nothing prevents you from keeping JSON and private HTML services privately separate.

In my experience, third-party data consumers often have a different view of data. This is not always the case, but trying to maintain a single API for internal and external use can be a much greater headache, as you get stuck by the API contract that you can not break into external systems.

  

Anyway, I would choose to just return the data to your frontend and treat all the HTML you need right there.

From an architectural point of view this is more sophisticated form, the current trend and preference of the great majority of front end developers, because it enables:

  • Better concept separation : does not divide rendering logic between client and server, but focuses on the client
  • Flexibility : Allows the evolution of the front end independent of the back end APIs or services.

Finally, if you're really concerned about performance, consider using a more compact protocol than JSON, such as Google Protobuf . Here are some advantages here and an implementation in PHP here .

    
20.06.2016 / 07:22
12

Dude,

I will refrain from comparisons between JSON and XML and stay focused on what you asked.

You put it like this:

  

I want to know the best way to transport this data:

     
  • Sending Ajax to the site and returning a JSON, thus manipulating the   array to use in the application.
  •   
  • Sending Ajax to and from the site   assembling a string with HTML code and returning it to the application   use this HTML in your interface.
  •   

And for me in your own question you have already offered the answer.

  

I want to know the best way to transport these data .

In my little experience, I believe that when an ajax request is made what you are looking for from the server are data and nothing more.

I do not think returning HTML is a good practice for a few reasons:

  • Normally pollutes the backend code with infinite HTML tags being concatenated
  • You prevent that url from being used in other parts of your project, because not everyone who needs those data needs that HTML.

Anyway, I would choose to just return the data to your frontend and treat all the HTML you need right there.

I also found this little discussion in StackOverflow. I think you'd better take a look and draw your own conclusions.

    
09.06.2016 / 16:02
9

Do not reinvent the wheel, use JSON!

There are several formats to be used for data transport, but in my understanding, JSON is the best format currently being widely used, that is, programming languages are adapted to the conversions:

  • Object for JSON
  • JSON for Object

And also because it is a more compact format than XML.

With a String you would have to first create a pattern that only you would understand or who had your source code to parse, other than JSON which (as it was previously) is already "massed."

Example

In an "Owner" class you would have to create a function to transform the data into JSON and would also have to have a method to turn JSON into an instance of an Owner. With JSON these methods should probably already exist natively or through third-party code.

JSON VS XML

class Proprietario { id, nome }

Json

"proprietario":{"id":1,"nome":"Victor"}

XML

<proprietario>
    <id>1</id>
    <nome>victor</nome>
</proprietario>

Note that the size of JSON even on such a small scale is much smaller, so imagine in a list of 1000 owners.

Conclusion

It's no use reinventing the wheel by not using something that works and is already extensively tested.

    
09.06.2016 / 04:55
4

The best way to transport this data is through JSON, it is used in several service distributors through Representational State Transfer (REST). Previously, XML was used for this.

There are a few reasons why you should not send HTML data, including:

  • The uploaded file will contain a lot of useless information;
  • You will need to feed information into it, and a change in page layout may compromise your application;
  • You will not find much on the internet about this method of yours;
  • It will only work for you because it will not follow a pattern, depending on HTML content
  • Some reasons to use JSON:  1. JSON is the standard adopted by large companies for sending and receiving data between applications. Facebook, twitter and Google itself use it;  2. It is lighter than XML because it does not have huge tags and this will save you bandwidth if your application is over the internet and time;  3. You can follow the REST standard through the HTTP protocol and provide services to third parties in the future, if applicable.  4. There are JSON to Object and Object to JSON converters in different languages  5. If you need to maintain your site, your JSON services are not compromised and your application will continue to run normally, ie independent of the HTML site.

    HTML VS JSON VS XML

      

    I see the second best option because of my greater familiarity with   PHP, but which of the two options requires less internet speed   of the device and compromise the performance of the app less?

    The download time for the information will be longer and the performance of the app will be reduced if you opt for HTML, since JSON has a simple architecture. Just to illustrate, a user-related example follows:

    In JSON:

    {"nome":"Anderson"}
    

    In HTML:

    <html>
    <title>Dados do usuário</title>
    <body>
    <div id="container">
    <h1>Dados do usuário</h1>
    <div class="algumacoisa">
    <p>Nome do usuário:<span id="nomedousuario">Anderson</span></p>
    </div>
    </div>
    </body>
    </html>
    

    In XML:

    <nomedousuario>Anderson</nomedousuario>
    

    The size of the files as you can see is very different, while JSON is simple and only has the relevant information, the HTML has a lot of useless information (for the app) and the difficulty of processing to get the desired information will be much larger and XML has tags that make the file much larger than JSON. You can use JSON and XML, prioritizing JSON, but do not use pure HTML as a service because it is too heavy to perform this function.

    Conclusion

    I recommend:

  • Use Object Orientation
  • Use the REST architecture with JSON and / or XML, the two can live in the same application and without much difficulty;
  • Read a little more about HTTP protocols to better understand the which happens underneath the cloths;
  • In summary: follow existing standards.

    I hope I have helped and I am at ease.

    Hugs!

    Here are some links that can help you:

    Introduction to REST

    How to create a basic web service with PHP

    Working with JSON in PHP

        
    09.06.2016 / 05:20
    2

    "... I want to know the best way to transport this data: ..."

    For me it was not very clear whether your question is to send something to the server or whether it is to get back from the server ("Sending Ajax to the site").

    I imagine it is when you receive information from the server via JSON. But I will post here a piece of my code that I always use for situations involving JSON both to send to PHP, and to receive from the server to be handled in JS.

    As many have already discussed above, do not resent the wheel, use JSON. But this approach uses a mixed solution, after all it turns JSON into a string, to improve performance during the transfer process.

    //Aqui é o seu código PHP (seuSErvidor.php).
    //Recuperando as informações enviadas do Javascript para o php, FrontENd=>BackEnd.
    
    $ObjEvn=$_POST["ObjEvn"];//valor = btn_Login
    $dataJsToPHP=$_POST["dataJsToPHP"];//valor do input "#txt_EmailLogin"
    $eviarQQCoisa=$_POST["eviarQQCoisa"];//Valor 123
    
    //NOTA: Não é aconselhado recuperar valores enviados de JS sem um tratamento prévio. Geralmente eu faço as validações no lado javascript.
    
    //aqui vc pode direcionar o seu fluxo(processo). Pode ser uma página admin, por exemplo que vai gerenciar todos direcionamentos como um controler.
    if($ObjEvn=="btn_Login"){
        //Código para testar login de usuário .... depois crie sua array $arrToJSON para ser enviada para javascript.
    }
    elseif($ObjEvn=="btn_DeleteUsuario"){
        //Código para deletar usuário .... depois crie sua array $arrToJSON para ser enviada para javascript.
    }
    elseif($ObjEvn=="btn_QualquerAcao"){
        //Código para outras ações  .... depois crie sua array $arrToJSON para ser enviada para javascript.
    }
    
    
    
    //Depois de fazer suas consultas no banco de dados, vc pode enviar os dados     para uma array php. Note que vc pode criar quantos índices vc quiser e colocar o que quiser dentro da array, incluisive código HTML, com javascript embutido. Funciona perfeitamente para mim. Eu carrego páginas inteiras utilizando essa técnica.
            //Crie sua array  
            $arrToJSON = array(
              "dataPHPtoJs"=>"algumDado de quaqluer formato",
              "htmlToPHP"=>"<div class=\".class1\">algum código html aqui</div>"    
            );  
            //Nota: a depender do tamanho da informação que vc quer guardar em "htmlToPHP" talvez precise usar um código para escapar espaços e carateres especiais. Vou colocar a função logo abaixo.
    
            //Essa função pega a array e transforma numa representação JSON - string. http://php.net/manual/en/function.json-encode.php
    
            return json_encode(array($arrToJSON));
    
    
    
    
        //No seu lado javascript ou "SITE" como vc disse. O evento foi iniciado pelo elemento "#idElement". Pode ser um click ou qualquer outra coisa. Vc vai mandar algo para o PHP (o codigo acima) e vai receber a $arrToJSON (que agora é uma string) no processo return
    
        $(document).on("event", "#idElement", function(){
            //Veja que aqui vc tbm está enviando para o PHP o objeto
             var dt={ 
                      ObjEvn:"btn_Login",
                      dataJsToPHP: $("#txt_EmailLogin").val(),
                      eviarQQCoisa: 123
                    };
    
            //Ajax      
             var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
                                    url: "seuSErvidor.php",
                                    type: "POST",
                                    data: dt,
                                    dataType: "json"
                                });
    
            //Então quando requisição AJAX estiver terminada, vc acabou de receber do seu PHP uma string que vai ser tratada aqui em javascript
    
                request.done(function(dataset){
                    for (var index in dataset){ 
                         dataPHPtoJsJS=dataset[index].dataPHPtoJs;//Aqui é o index da array que vc usou no php.
                         htmlToJS=dataset[index].htmlToPHP;
                     }
    
                     //Aqui vc pode usar o que recebeu do PHP e modificar as sua página de acordo com o recebido. POde carregar htmls interios, inclusive.
    
                     if(dataPHPtoJsJS){
                        $( "#idseuElemento1" ).removeClass( "class1" );
                        $( "#idseuElemento2" ).html( htmlToJS );
                     }
    
    
             }); 
    
            //Ajax Fail 
                request.fail(function(jqXHR, textStatus) {
                    alert("Request failed: " + textStatus);
                }); 
        }
    
    //Função para filtrar espaços (ou minimizar) javascript ou HTML
    
    
    function html_rows_Event_Details() {
    
    $str =<<<eof
      <tr class='evntdet'>
          <td colspan='4' style='background-color:#00BABF ;  padding: 10px;  text-align: center;'>
              Something
          </td>
      </tr>
    eof;
    
    
    
    $re = "/(?:\s*([<>])\s*|(\s)\s*)/im"; 
    $subst = "$1$2"; 
    
    return  preg_replace($re, $subst, $str);
    
    }
    

    Source: Link .

        
    09.06.2016 / 16:47