AJAX - PHP Communication Templates

I am creating a webapp in MySQL / PHP / Javascript.

In PHP, I have all the classes from the domain that are stored in the database. Javascript has a cache with objects from recent requests.

When an object in Javascript is updated by the user, it must be updated on the server side. What would be the best way to do this?

Should I create a class in PHP and Javascript for communication purposes? Should every object in Javascript send an AJAX request to a different php file depending on the class of the object it should update? Are there any patterns to solve this problem?

+4
source share
3 answers

Creating a separate PHP file for each class will certainly be more maintainable, if at all it is a project of any size. It will also allow you to do something like class-based server level authentication.

On the JavaScript side, you definitely need some kind of AJAX library, regardless of whether you are going to build it (I did it once in about 50 lines of JavaScript) or used one of them. You might need a helper function or two that know how to serialize data (XML, JSON, limited, whatever).

You can write object-oriented code in JavaScript, and if you already do this, it makes sense to add the write () or updateServer () method to call the AJAX library with the correct parameters for consistency. If you are not writing OO code, it may still make sense to have separate functions, but only if you need to save no more than one place.

+1
source

Most AJAX frameworks (jQuery, etc.) will send the header 'HTTP_X_REQUESTED_WITH' set to 'xmlhttprequest'. I like to use this to decide which species to use.

This means that the same URL can be used to retrieve a JSON, XML or HTML fragment using JavaScript, or to return a complete document if a standard GET / POST request was made.

This means that your application will simply return to normal queries if the user has disabled JS.

+1
source

I think you should take a look at the REST ful API with PHP and JavaScript. You address the domain model objects as unique resources (for example, / application / books / 1). If you want to implement CRUD functionality, a generic controller that updates the appropriate domain model (for example, using an ORM tool such as Doctrine ) should be enough.

If you really want to have the same client-side model in JavaScript, depends on your application. I like the idea of ​​simply managing one client-side JavaScript object that will be loaded via REST and then populated into HTML forms and sent back, for example. as JSON (or as a simple form of sending) to the server. If the idea of ​​a client-side model appeals to you, I recommend taking a look at JavaScript MVC , which has a rather interesting model implementation.

0
source

All Articles