Often I add helper functions to my PHP that return complex HTML. For example, it is not an easy task to ensure that a form element is accessible, can handle errors etc. and so I will have a PHP function wrap this problem.
Unfortunately, sometimes, I will need to generate the same HTML but with JS instead. An example of this is where I have a Flash uploader which uploads multiple files. As each file is uploaded, I want to populate another form on the same page which will allow the user to edit the files data.
I already have the specification for the inputs for this form in PHP helper functions. At the moment, I just recreate these inputs manually with JS. However, this is inefficient and frustrating because if I wish to change some aspect of these inputs, I now have to change them in two places.
One thing I could do is pass the form elements back to JS in the same AJAX request which uploads the file. This works fine but could be problematic if I have large amounts of HTML.
Is there a better way than this or is using the AJAX request the best it gets?
One thing I could do is pass the form elements back to JS in the same AJAX request which uploads the file. This works fine but could be problematic if I have large amounts of HTML.
Certainly, this would allow you to avoid the code duplication.
But if you're just requesting identical HTML twice, that means - regardless of the size - there's an additional HTTP request for the same data.
It's probably not a big deal, but if you're that concerned, use AJAX to request the data once, store the result, then just used the 'cached' HTML next time you need to add an element.
Of course that only works if the HTML is identical.
Now if it is identical, and if the initial request puts one copy on the page, why not skip the AJAX request, and just have the javascript 'cache' a copy of the form when the document is loaded? Then you can duplicate the original form each time it's needed.
Make a page/controller in your php, that will be given a reference to the specifications you have stored, and will call the function and send back it's output.
Then you make an ajax call when required, that will request the page with the required parameters to get the wanted content.
Half-way through your answer I was going to suggest grabbing the inputs as JSON via a web service. In other words, I was going to suggest AJAX (or AJAJ I guess).
I do not see how you would coordinate the content otherwise.
Related
I have a little bit of a conundrum. Basically I'm developing a WYSIWYG Editor plugin for jQuery specifically for my web application. One of the features will be inserting an inline image tooltip based on the images a user has uploaded. For example:
Hello there my name is [i="profile_pic.png"]A. Username[/i]
The part that I'm having an issue with is, when defining which images are available to a user, whether I should insert the PHP array directly into the Javascript like so:
var available_images = "<?=json_encode($User->Profile->images)?>";
or to go for an Ajax GET that returns an encoded array of the image sources? I think the inline php makes more sense since it removes the need for an unnecessary ajax call but I didn't think that inserting inline php into javascript is terribly good form?
Any suggestions?
There's nothing wrong with inserting data collected by PHP into JS, how else would JS get the data? The only reason you should consider the AJAX call would be, if users could upload new images while they are editing. This would mean the information needs to be updated, which would make the AJAX call more appealing than the static JSON on page load.
Unless the array changes in any way over the life time of the page, then I'd spit out the array exactly as you suggest in your code snippet. There isn't any real benefit to having an extra ajax call because the size of the array I'm guessing won't be so huge as to impact the initial page load time.
If you look around the Stack Overflow pages and do view-source, they do this sort of thing all the time.
If the amount of data is huge and maybe adds a seven or more seconds to the page load time then I'd consider an ajax call. At least the page is rendered and the user has something to look at, meanwhile you can have a throbber image with a status message saying loading or whatever.
I'd also say that I see a lot of unnecessary ajax goings on just for the sake of it. It's like premature optimisation, people adding complexity to solve a problem they don't have. Start off simple as you're doing, if you're having response time issues down the road with the said page, then consider what benefits ajax will bring to the table.
Do you always get the array of images, or only sometimes (e.g. in response to a user's action)? If the former, I'd say do it inline. Otherwise do it as AJAX. i.e. only do it by AJAX if it'll reduce your traffic etc. But if you have to always do it, I don't see any advantage. I don't see any problem with mixing inline php and javascript, other than it means you have to do your javascript inline too instead of in external .js files that can be cached (or at least the part where you populate your array).
I am (mostly) a front-end developer working on a prototype with a backend guy on a site. The basics of it would require a user login area, as well as a search form that would search and return results from a database table.
He is doing the backend logic with Java and PostgreSQL. He proposes to return a JSON format to me upon a query. This means I will have to take the data from the JSON string and populate/create the HTML markup. I can do this with either Javascript, or PHP. It seems to be that PHP would be a no brainer as I don't need to create HTML markup with Javascript/jQuery and also all the data populated by the server already, reducing the load on the client side, but this means as a "front-end" person I am also writing PHP.
And regarding loading all server data onto a page with Javascript, is this standard practice? Or should it only be used on AJAX?
Should the backend guy be generating the markup as well? What's the best way of separating this frontend and backend work? THanks!
If you are using PHP, you are a backend-guy, too.
If the markup is generated by the server, than you would usually not write an AJAX-application, because the markup is generated by the server.
In fact if you want to write a ajax-application, you have to manipulte the DOM with Javascript. Use jQuery or something like that to do this.
Seperating frontend and backend is done by creating an Interface, a contract which will separate the UI from the Backend-Logic. In your case the contract is the format of your JSON Data.
A good compromise would be to do either:
Option 1
A small PHP script server-side which formats the restults into a table with appropriate Ids/similar to allow javascript to add classes for styling. This entire table could be returned via an AJAX call and placed within a placeholder div on the page.
Option 2
The server returns simple JSON to the front-end, the front-end uses whatever mechanism it sees fit to build the appropriate HTML
The first one is a little cleaner to code - The generation of the HTML is seperated from the styling, but it's an extra hop (the PHP) and is slightly inflexible - the JS can modify the table as appropriate but it's limited by the html PHP sends.
The second is slightly more verbose to code but completely flexible.
I send the data from the server to the browser in JSON all the time, format on the browser with templates of one form or another. I would rather work with arrays in Javascript as the array methods like map and filter make it much easier.
Is there a way to keep children added to the DOM via .appendChild() after a POST/GET without regenerating them in JavaScript? Right now I'm regenerating them with a few function calls written in a script tag using php.
If the page is reloaded, the DOM is recreated from scratch, and any earlier modifications are lost.
Possible solutions:
Use Ajax to avoid reloading the page. You would be able to send requests asynchronously without losing the state of the DOM.
When responding to specific requests, reconstruct the correct elements while rendering the HTML from php. This requires some duplicated logic on the server-side that you are now handling on the client-side.
Not if you are appending on the client side. The server has no way of knowing that the source doc has been altered, and in turn has no way to make sure the update doc is served after a GET/POST. Best analogy that I can think of is if you open a Word doc, modify some text, and then close the app without saving the file.
I have been making extensive use of XMLHttpRequests and JSON to fetch from a MySQL database and return records as arrays. It works perfectly.
Additionally, I have three cases in which I have the server (via PHP) formatting the data as a web page and creating bar charts (as opposed to sending arrays back to JavaScript for processing). Currently, I call the PHP file via a hidden iframe and then insert the HTML into a DIV (since I don't like certain aspects of iframes and prefer to not have them accessible).
Is using an iframe the best method or can I accomplish the same thing via a XMLHttpRequest and JSON? I'm asking because of the length of the data being returned. At present, it translates to a full page of data, but I want it to be extensible (e.g., perhaps a couple of pages of data in the future).
Thank you for any insights.
If you want to get formatted html from other page and insert it in the current page dom the easiest way according to me is using the jQuery load methods. It make ajax request to a given url, gets the html and appends it to specified page element.
Generally the two methods - passing JSON data and passing Formatted html are good for different things. I personally prefer to pass JSON data and format it with client script and html. In this way it is more reusable.
Difficult to explain this Question, but im currently passing variables in a php page to some html hidden inputs.
Im fetching those values from the hidden inputs with a javascript function. This function gets called like this:
<body onload="function();">
It works on my system now, but is there any chance that the value passed from php might not get through because body has called the function BEFORE the php code sets the input type hidden?
Thanks
You have may have mixed up which part does what.
PHP generates the HTML page on the server side. When the HTML page arrives at the browser, PHP has done its job. There is no way for PHP to do something after it has rendered the HTML.
Javascript is executed in the user's browser after the page has been generated and loaded. (Or during; as theraccoonbear points out, Javasript can run in the browser before the page has loaded completely.)
A Javascript command can not communicate with the PHP script rendering the page, because when Javascript comes into play, PHP is already gone.
So the answer to your question is: No, the JS function can not execute before PHP is done. As several commentators point out, that is not entirely true. A Javascript could come into action before the input HTML elements have been rendered. In your example however, the Javascript triggers only when the document is completely loaded. In that constellation, the answer is no, it can't happen.
That shouldn't be an issue, as you are using the body's onload property, which will ensure the dom and all images etc have loaded.
Using jQuery to it like below would be better in my opinion, fires as soon as the dom is ready, rather than waiting for all images etc.
$(document).ready(function() {
// do stuff here
});
This is also easily done from an external JS file if required, which helps you logically separate your code.