Use JS to relieve PHP

Asked

Viewed 667 times

15

Well, I have a PHP file that generates a document (I get it by AJAX). This document goes through some functions (which I did in PHP), such as converting a string to code, adding fields..

Well, for organization purposes, I did everything with PHP these adjustments(then the document is delivered ready, the JS does not need to enter the scene to finish the work after the request).

But what would be the indication? Relieve to the server(memory, less processing, faster delivery.. ??), or if this to the server would be of such little importance(requires little processing) that it is not worth to stick to details but rather preserve a cleaner and simpler maintenance code.

  • 3

    That’s a question I’ve been asking myself, especially with Infinite scroll to make javascript assemble the elements. But have the composition outside the view makes me a little uncomfortable. I look forward to a Bench on the topic.

  • 2

    I believe that the answers are coming out a bit of the scope of the question which is not about the amount of requests, validation before or after, etc... Giving my opinion, turned to the question, I believe that js can be, to some extent, used as your view (separate from the server). All the logical part and the business rules would remain on the server, but who processes the interface part, who organizes the information to display to the user, would be the js.

5 answers

7

Hello.

First of all I’m going to start by quoting a little thing that people usually say or think when they come across questions like that:

Javascript despite being one of the main web languages, you can never replace PHP in a web application that wants to maintain the total integrity of the data leaving the client for the server and vice versa ( read this if you think I’m wrong ).

Another thing is, relieve with the Javascript, is nothing more than pre-validating data before it is sent to the server according to your question.

The Javascript in itself, serves only to handle animations and dynamization on the client side or control events directly, being that if you leave the Javascript do most of the service, in addition to those that really compete, and then send to the server information and not perform another check, who knows what data you just sent directly to the server, because the Javascript did all the work including the PHP or other language BACKEND in use, and the server merely received them as if he were the one who verified them.

Hence the principle of validating with Javascript and then re-validate with PHP or another language that is acting on the server side. Until the frameworkdo it, but otherwise.

In the end I don’t know if I answered your question, but I hope you understand at least that Javascript should never replace PHP, try to make your script on the server side more efficient.

  • exact.. basically the same as I answered

  • Yes, it is practically the same, although I have extended the explanation and deepening a little more, still the author: As respostas atuais não contêm detalhes suficientes., if with this he does not understand what are the limits of Javascript, then there’s nothing I can do.

  • Yeah. I don’t understand what else he wants.. maybe he wants to see codes with common case studies and kilometric responses with tables, graphs etc. rsrs

  • Really? I thought I was the only one who thought that :).

  • @Edilson, before I put the reward of 100, there were no more complete answers( or simply answers ) than Danielomine’s, I will analyze these now and see if met my expectation :). Thank you for the reply!

4

Validations should be made in PHP (server side) regardless of what happens on the client side (js, html).

To "ease" processes, it is recommended to apply Javascript validations to avoid server requests.

Examples are: Validate email format Validate number of characters Validate numerical or letter-only data

It is worth noting again that regardless of whether there are client-side validations, with Javascript, the same validations should be done on the server side with PHP.

"Relief" is also useful for accessibility. For the user on the client side, it is visually better and performative.

  • Would your exception be revalidation only in case the client’s browser is not Javascript enabled? But in this case it would not be better to check the presence of this, and if not, request in the request (through a parameter for example) to be made the validation. I am the idea of saving the server, are small details but that add up may make some difference, but if this difference is so little then it is worth more to ensure application in terms of data security (how to revalidate). Anyway, I don’t know the size of the server effort for such feats.. @Daniel Omine

  • I don’t know if you understand, because you described the same one I posted, but with different words. And about the case of browser without JS support, it is irrelevant to the case. Therefore, it is unnecessary to say that you need to have validation on the server and not rely solely on the client side. And again pointing out, client-side verification with JS is essential to avoid unnecessary processes, especially server requests. And browser without JS support, you see, without JS support, you won’t be browsing virtually any website. A request can be made without a browser, for example, but that’s another matter.

  • 2

    Why is your answer based solely on validation?

  • I understood that a way to "ease" would be to actually check if the request is valid to persist with the work by the server, so it does not throw a request out and saves the server’s efforts. But I did not understand (perhaps due to lack of knowledge) why to redo the same (same) verification in both (client, server), if passed in one, which prevents to pass in another?

  • Papa Charlie, I do not understand the reason for your question. If you can explain thank you.

  • 3

    Alexandre C. Caus, the reason is that verification on the server side should always be done and verification on the client side is optional. Even if you do client-side verification/validation, the same checks should be done on the server-side because requests do not always come from a conventional browser.

  • @Alexandrec.Caus If you do not have validation on the server, nothing prevents me from making a request to your page directly, without using your site / form, sending invalid data and possibly breaking your site.

  • Why do you have to repeat the validation on the PHP side ? Simple, do you really think that a method could never be exposed for integration into a webservice ?

  • I think saying it’s a rule, revalidating on the server side, is wrong. If you do not compromise the security of a database there is no reason to play more work for the server. Don’t give me rules of application, every case is a case.

  • Alexandre.. ???? What do you mean ? I really don’t understand how you can’t understand ?? rsrsr.. Like this guy, you’re twisting what’s been put in. None of the answers says that "all the weight" should go to the server.. Not at all. Anyway.. learn to read and interpret..

  • @Danielomine, whether you like it or not, this was under the table, to understand that became a rule. I will not argue about it, just say that nothing is rule, it depends on each case, your answer was worth but was not enough. thanks!

  • "Under the cloths"?? "became rule" ?? You are well expensive ? rssrs

Show 7 more comments

2

TL;DR: depends a lot on your application and the benefit cost of changing the functionality to the front-end.

Using Javascript to relieve the back-end is good. But whether you should use it or not depends a lot on your application, whether you have an application that is slow in the back end, it is worth leaving more tasks to the front end. If you have a small application that is generating the documents in the back end without performance problems you may not need to modify it and start using JS.

We must take into account the work that will change the application and how much this will imply in performance. If it is a major modification, which will take many hours of work and which will remove little back-end load, then it is not worth it. On the contrary if the modification is not so complex, but rather relieve the server then it is worth doing.

As already mentioned in other answers here, tasks such as data validation should always be done in the back end, can be done in the front end to give a faster feedback to the user, but must be redone in the back end to check the integrity of the data, since if the data were validated only front-end would create the possibility for a malicious user to disable Javascript and make an attack on the site as for example a SQL Injection.

Another important point is that more and more cloud computing services are currently used for hosting, these services typically charge for CPU usage and/or usage time, so the less processing is used, the more economical it becomes. Soon, the more functions are given to the front-end and back-end withdrawals the cheaper the service will be.

  • is the same view as mine

2


In my view, the question is about using javascript to do PHP work. A request made with ajax can return data formatted in back-end or may receive a json and format for composing a view. My answer is based on this assumption.

I will give as an example a simple request containing an array of 2 indexes, only name and surname and formats in JSON, XML and HTML for comparison purposes only.


DATE

 array( array( 'Papa' , 'Charlie' ) , array( 'Papa' , 'Charlie' ) )

JSON

LENGTH : 39
STING  : [["Papa","Charlie"],["Papa","Charlie"]]

XML

LENGTH : 191
STING  : <usuarios>
             <usuario><name>Papa</name><lastname>Charlie</lastname></usuario>
             <usuario><name>Papa</name><lastname>Charlie</lastname></usuario>
         </usuarios>

HTML

LENGTH : 66
STING  : <div>Papa</div><div>Charlie</div><div>Papa</div><div>Charlie</div>

An output in HTML will use the server to process the data, and you can display the data using simple functions. It may be the best option when there is little data flow or for those who are not so familiar with javascript. On the other hand, we have a larger data stream and can make the application more trapped.

Data in JSON are easy to work with type object, besides having a much smaller length than the other formats, and this is an interesting point for bandwidth saving. JSON and XML are more flexible and simple to implement webservices, apps, desktop, mobile devices...

I couldn’t find a benchmark of respect that I could use as a comparison effect, but I don’t see such a drawback in the processing time between PHP and javascript as a decisive factor for change. In fact PHP consumes more resources to assemble HTML, while javascript composes at low cost. But to answer which to use or when, depending on the need - reduce traffic, make application more flexible to other platforms... I think are points of greater importance in choosing.


Some interesting references

• Why is it a bad Practice to Return generated HTML Instead of JSON? Or is it?

• AJAX - Using JSON vs echo HTML

• Why do Facebook, Twitter and Gmail render all their data to the browser as JSON as opposed to HTML?

• PHP vs Node.js: The REAL statistics

• The AJAX Answer: XML, HTML, or JSON?

• Creating HTML: PHP server-side vs. jQuery Clie

  • agree, it depends on the need and feasibility in the issue of security, we can not simply say that it is an OBLIGATION to validate everything on the server, because there are several cases where can be applied the "exceptions" that result in performance gain.

  • 1

    Wow.. Good references, when I have time I will analyze these, thank you for the reply, I will consider it the most complete and reward you. hugs

1

To throw wood on the fire, I can make a "CLEAN" code on the client side until I get to the server side, and continue programming javascript on the server side just use the nodejs.

https://nodejs.org/

So the question of validating on the server or client side will depend on what is validating, if it is something that will not compromise the security of a database, or leave a client-side javascript where it can override a function to change something in such cases leave everything on the server side.

But a validation of type type type your login which is the email, and a function that checks if the email has a @ in the middle of the string, in which case I can quietly play it from the client side.

  • Nodejs is a framework :)

  • This is an answer would ? We should always validate the data of dubious origin (that its application has no control). Even an email/password should be validated, imagine you have a password policy, you could validate this policy before going directly into the database and still take advantage of the same rule in your user registration.

  • I agree that if not compromising the security of a database, throwing the work to the client side (some cases) would save the server from doing extra work (such as repeating the same process). I do not understand why the people insist on saying consistently (without exception) that it should be verified on both sides. Each case is a case, as Sneeps said, and I agree, "So the question of validating on the server or client side will depend on what it validates, if it’s something that won’t compromise the security of a database"

  • @Edilson completing Nodejs is a server-side sim framework, and uses javascript ;)

  • 1

    @wryel I think you misunderstood me, the validation of an "email" if it is within the domain name@domain format I validated only with client-side javascript, if it is used as login, and it pass wrong simply will not log in, and the client-side validation script will warn that the email format is wrong, simple asism.

  • @Sneepsninja won’t even log in, I agree. What I’m trying to highlight here is a "requirement" of your software that you just checked when creating the login, but are not checking at the time of the login. I even confess that I have already made methods of logons in which not valid email format for example as you yourself justified, but it is not right, we are circumventing the requirement of the format of the email, in this case we should throw an exception or and exit the main stream (in this case, saving a trip to the resource that validates the data provided).

  • I think I’m going to Offtopic, but focusing on the answer of the author of the question, the data should ALWAYS be validated on the server, and what is interesting to increase the user experience, should be validated on the client side.

  • 1

    @wryel as quoted ["we should throw an exception or and exit the main stream"] in which case I use javascript to launch the exception, so no email arrives without being formatted for the server check, and ref. to exit the MAIN STREAM this yes php will handle (if a post is sent to the server in a Machiavellian way) not logging in because the unformatted email will not be located in the DBMS.

  • Exactly, there are points to address on the server side (how to treat the data via POST (avoid sql Injection)), and others that in case it is deemed necessary, but nothing else, cleaner and more useful code, anyway.. my opinion from what I see and can analyze from users.. Thanks for the Reply Ninja Sneeps, nodejs really is interesting, I will read more about when there is some time left!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.