AJAX vs PHP right in JS

I have a little mystery. I mainly develop the WYSIWYG Editor plugin for jQuery specifically for my web application. One of the functions will be to insert a built-in tooltip based on the images that the user has uploaded. For instance:

Hello there my name is [i="profile_pic.png"]A. Username[/i] 

The part I am having a problem with is determining which images are available to the user, whether I should embed a PHP array directly in Javascript, for example:

 var available_images = "<?=json_encode($User->Profile->images)?>"; 

or switch to Ajax GET, which returns an encoded array of image sources? I think inline php makes more sense, since it eliminates the need for an ajax call unnecessarily, but I did not think that inserting inline php in javascript is an awfully good form?

Any suggestions?

+6
source share
3 answers

There is nothing wrong with embedding data collected by PHP in JS, how else will JS get the data? The only reason you should consider calling AJAX would be if users can upload new images while editing them. This would mean that the information needs to be updated, which would make an AJAX call more attractive than static JSON when loading the page.

+4
source

If the array did not change in any way during the life of the page, I would spit out the array exactly as you suggest in your code snippet. There is no real benefit of having an extra ajax call because the size of the array, which I assume, will not be so huge as to affect the initial page load time.

If you browse the pages and do the source view, they do this all the time.

If the amount of data is huge and perhaps adds seven or more seconds to the page load time, I would consider calling ajax. At the very least, the page is rendered, and the user has something to see, meanwhile you may have an image with a tiber with a status message, loading or something else.

I would also say that I see a lot of unnecessary ajax, just for the sake of it. It’s like premature optimization, people add complexity to solve a problem that they don’t have. Start with a simple how you do if you have problems with the answer on the road with the specified page, and then consider what benefits ajax will bring to the table.

+4
source

Do you always get an array of images or only occasionally (for example, in response to a user action)? If the first one, I would say make it inline. Otherwise, do it like AJAX. that is, do it only with AJAX if it reduces your traffic, etc. But if you always need to do this, I see no advantage. I do not see any problem with mixing the built-in php and javascript, except that it means that you need to make your own built-in javascript and not in external .js files that can be cached (or at least the part in which you fill in your array).

+2
source

Source: https://habr.com/ru/post/887854/


All Articles