I have a database that contains strings in the format:
"key:value|key:value|key:value|key:value"
Due to some other reasons, I can not have the key value pairs stored in the database.
Should I use PHP to split the string and pass it into the javascript charting framework,
or,
Should I pass the complete string into javascript and have javascript parse it.
In theory, either would be acceptable. In practice, I would lean toward doing as much repetitious work on the server as possible. If you think about it in terms of which can do it faster, you KNOW how fast your server can do it. The resources stay (relatively) constant.
Doing it in javascript relies on the client environment. With a web application, the client environment is infinitely varied. You never know how much memory a client will have available, so it is impossible to estimate how efficiently they can parse the data. 99% of your clients might be fine, but the other 1% get a locked browser when they use your script.
The safest bet is always to use known quantities as much as possible. In this case, the sever is your known quantity - do the work there.
It's more or less negligable. Something to consider, however, is the possible length of the sting. If you know that there will be be quite a bit of NVPs then it might be smart to just transmit as the single string and break it up on the other end (assuming it will have the same glue to attach the parts).
If the string is data specific and the string is generated from the backend, it might be better to let PHP manipulate it. You usually want to limit most of your javascript for UI/client-side interaction, unless of course your using JS on the backend.
Related
Here is my situation. I am building an application that contains some heavy mathematical calculations where the formula needs to be editable by a sufficiently privileged, but untrusted, user.
I need a secure server side scripting language. I need to be able to access constants and values from 4+ database tables, the results of previous calculations, define user variables and functions, use if/then/else statements, and I'm sure more that I can't think of right now.
Some options I've considered:
I have considered using something like this matheval library but I would end up needing to extend it considerably for my use case. I would essentially be creating my own custom language.
PHP runkit sandbox. I've never used this before but am very concerned about the security issues involved. Considering the possible security issues, I don't think that this is a viable option.
One other idea that has crossed my mind that I don't know if it is possible would be to use something like javascript on the server side. I've seen js used as a scripting platform in desktop applications to extend functionality and it seems a similar approach may be feasible. I could ideally define the environment that things ran it, such as disabling filesystem access etc. Again, security seems like it would be an issue.
From the research I have done, it seems like #1 is probably my only option, but I thought I would check with a larger talent pool. :-)
If #3 is possible, it seems that it would be the way to go, but I can't seem to turn up anything that is helpful. On the other hand, there may not be much difference between #2 and #3.
Performance is another consideration. There will be roughly 65 some odd formulas each executing about 450 times. Each formula will have access to approximately 15 unique variables a hundred or so constants, and the results of previous formulas. (Yes, there is a specific order of execution.)
I can work with an asynchronous approach to calculation where the calculation would be initiated by a user event and stored in the db, but would prefer to not have to.
What is the best way to work with this situation? Are there any other third party libraries that I haven't turned up in my research? Is there another option in addition to my 3 that I should consider?
There's almost no reason to create a custom language today. There's so many available and hackable, writing your own is really a waste of time.
If you're not serving a zillion users (for assorted values of a zillion), most any modern scripting language is securable, especially if you're willing to take draconian measures to do so (such as completely eliminating I/O and system interfaces).
JavaScript is a valid option. Its straightforward to create mini-sandboxes within JS itself to run foreign code. If you want folks to be able to persist state across runs, simply require them store it in "JSON-like" JS structures that can be readily serialized from the system on exit, and just as easily reloaded. These can even be the results of the function.
If there's a function or routine you don't want them to use, you can un-define it before firing off of the foreign code. Don't want them using "read" to read a file? read = func(s) { }
Obviously you should talk to the mailing lists of the JS implementation you want to use to get some tips for better securing it.
But JS has good support, well documented, and the interpreters are really accessible.
You have two basic choices:
a) Provide your own language in which you completely control what is done,
so nothing bad can happen,
b) Use some other execution engine, and check everything it does to verify nothing bad happens.
My problem with b) is it is pretty hard to figure out all the bad things somebody might do in obscure ways.
I prefer a), because you only have to give them the ability to do what you allow.
If you have a rather simple set of formulas you want to process, it is actually pretty easy to write a parser/evaluator. See Is there an alternative for flex/bison that is usable on 8-bit embedded systems?
It isn't clear to me that you have a performance problem. yes, you want to execute something 450 times; but it includes database accesses, whose cost will dominate any computation involivng a 1000 arithmetic steps. You may find that your speed is limited by the DB access that that you need to cache the DB accesses to get it to go faster.
Should I have my server return JSON data and then have the JavaScript parse it to create / render HTML directly or should I have my server-side code return HTML directly, which can be directly placed by the JavaScript.
Thoughts?
Render the code server side (e.g. as it is done in Rails' AJAX), then return the view to the client where it will just be placed.
Then profile your code. If it turns out to be too slow, return the JSON and think of a way to render it client-side.
Your priority for this should be to not make the whole thing too copmlicated.
I'm not a fan of returning generated HTML. IMHO I'd return JSON and use something like JQOTE 2 to handle the rendering. Let the clients resources handle that work.
(Side note: JQOTE is an amazing tool!)
I think that if you won't need the data later, e.g. for filtration, on-the-fly search, etc, then you should return HTML.
Premature optimization is the root of all evil. Start with whatever is easier. If it's just too slow, find a way to optimize (perhaps by using an alternative).
If one is not easier than the other to you, go with the server side. I can't imagine a circumstance where a server side scripting language operation would be slower than javascript in a browser.
If all you have to do is render HTML, then it's probably much easier to do it directly with the server (php). Otherwise, you have to convert it to JSON with php first, then convert it back with JS later. That's at least one extra step and extra work for the javascript side.
I'll vote for your first proposed approach.
JSON serialized data size is smaller than (X)HTML one and your first approach saves a lot of CPU cicles, network traffic, memory and speeds-up your client, which ends in a responsive user interface.
Just send data in JSON format and parse it in JavaScript in the client-side so things will be more simpler in the server and rendering things will be delegated to client web browser.
There is no one right answer; it depends on your expectations.
If you want the application to be accessible (ie. processed by a screen reader), picked up by search engine bots or want the UI to be cacheable between requests and users, you will have to use server generated HTML and no dynamic loading. If you use a cache for the generated HTML, you get a lot of mileage without the constant re-rendering. There are more server side tools than client side but that is becoming less of a true statement as JS grows.
OTOH, producing JSON that is rendered by the client using some JS library can really help your server reduce load. You're distributing the work of rendering to the client but that does take control out of your hands. If you have a JS heavy solution and the client can't process JS (screen readers, search engine bots, etc), then the site should degrade gracefully or expect to have some audience that can't view it. That audience might be minuscule for you but it's something to know. As long as you manage the rendering well, (set min size for areas, wait icons, etc) then you can have client side rendering that is as smooth as server side (when comparing visual rendering steps). Producing JSOn also gives you more flexibility as more interfaces are defined or other non-UI clients become important.
It depends on what you are trying to achieve. If you are writing a mobile application you may want to save bandwidth and work with client-side templates (just as an example: John Resig's micro templates). If bandwith is not that important to you I would just use server-side templates to generate the HTML you need.
In my opinion it's all about responsiveness. Your server is ALWAYS going to be able to process data faster than the UA, however the difference between the two may be negligible. If that's the case, then I'd recommend passing JSON to the UA and then use client-side code to do the dirty work. That way, you'll have clear separation of concerns between the server and the client, allowing you to deliver JSON data to different client endpoints in the future without having to modify your server-side code.
However, if there is a significant performance hit with doing the data processing on the client side then it might make more sense to deliver HTML directly to the client. HOWEVER I highly recommend that you still deliver JSON, only to your server-side HTML creation function (rather than the UA) so that you can still deliver JSON data to multiple endpoints without having to alter core code in the future.
I'm designing some UI's for a product and we want to utilize jQuery and PHP. The content to generate is a list of checkboxes (10-100) that a user will be modifying (removing multiple at a time and changing the entries). I thought I'd try something new and ask StackOverflow (read: you) what is preferred: generate the html in the php call and return, or return JSON data that jQuery can than go and generate the html checkboxes using.
I appreciate the feedback! My preferred method so far is to let PHP generate html because it knows more about the data at the time of modification (it's interacting with the database and it could build the html easy enough without having to pass back id's, names, etc in JSON).
Thanks!
[Edit] Bandwidth is not a constraint. This is an internal intranet application. The information needing to be printed to the user will not require dom modification after the fact (outside of checkboxes, but that's built in to the browser...) some good points have been made on the amount of data that's being passed back though:
passing back
Label
vs.
{
"Label": "Unique_ID"
}
is obviously a lot of redundancy.
There's really no right/wrong way to do this. Passing JSON back, and then using client-site processing to turn that into HTML uses less bandwidth, but more local processing power. Passing HTML back, uses more bandwidth and less local processing (these are seriously minor points, only if you're talking extremely popular or frequently changing sites might it even be relevant).
Return Flexibility - HTML
One of the benefits to HTML passing is you can return anything if the request causes an error, or could generate different types of data you just return different HTML. If you're returning JSON, the parsing script has to deal with these alternate structures (ie error handling, and/or multiple structure parsing algorithms).
Local Processing - JSON
If you're localizing, sorting, or framing the data from the user's point of view, it may well be simpler to return JSON and then use client side scripts to interpret. For example when user=2, reporting "You" instead of "Mike" might be a nice personalization touch. You could do this server side, but now the script needs to take that into account, so the same query needs to return different data based on context (again not impossible). You can keep your server code more generic by using client side scripts to perform this.
Local Presenting - JSON
Perhaps a single command collects the data, but there's multiple parts of the page that should be updated with what's returned. With an HTML approach, you either need separate queries, or some sort of delimiter in your return (with escapes!), and a local processing script to decide what goes where... with a JSON approach, the local processing script can update the locations from the same single source as it's retrieved.
You could approach the question both from the aspect of server burden and in terms of client performance.
If your server is having to dynamically generate the HTML output for every user, it will endure a somewhat higher burden than if you delegated the content-generation to client-side JavaScript. Clients have abundant computing power at their disposal, so feel free to have them collectively shoulder the burden rather than having your server do all the work (which could easily add up, depending on how busy your server is).
Likewise, generating the HTML markup on the server results in a significantly larger page download for the client. The markup for a hundred check-boxes could easily add kilobytes to the size of the page, while the data itself--which is all you would send using the JSON approach--is much smaller. Of course, larger page downloads mean longer download times for the client. We as web developers often forget that there are still quite a few people who still have dial-up internet connections.
For these reasons, I would personally opt for sending the data via JSON and doing DOM-modification via JavaScript.
Cheers,
Josh
The answer is: it depends. If you are going to be doing DOM manipulation on the new data, then you pretty much have to append the elements using jQuery. If there is no such manipulation needed, then you can just print it out with php and add the blob.
I think that the latter is much easier and simpler, so if you don't need to do DOM manipulation on the elements, you can just add the html blob from php.
I am using a webservice which provides a large result set either in XML or JSON format.
Which format will be faster or better (perfomance based)? Also which language should I use to parse the XML/JSON? Should I use PHP or JavaScript?
"PHP or JavaScript" sounds like an odd choice to offer: PHP is usually used as a server-side language, whereas JavaScript is usually used as a client-side language.
What's your situation? What makes you suggest those two languages in particular? If you could give more information about what you're trying to do, that would help a lot. (We don't know whether you're developing a web app, a batch processing tool, a GUI application, etc.)
I suspect JSON will be a bit more compact than XML, although if they're compressing the data you may well find they end up taking the same bandwith (as a lot of the "bloat" of XML is easily compressible).
As ever, the best way to find out is to test the specific web service with some realistic data. Generalities aren't a good basis for decision-making.
both have their advantages:
JSON
easy to handle: $dataStructure = JSON_decode($serializedString);, done.
XML
partial data handling: if your result-set is too big to be processed (parsed) at once, this may be the way to go. note: SimpleXML is the easier to work with xml lib, but also parses the whole xml-file at once, so in this case there's no benefit over JSON.
the question which language to handle your result set with is a bit non-sensical. javascript is client-side*, php is server side. so, it depends on what you want to do with the result set.
you can pass the result directly on to the browser/js without doing anything on the server side, and let the client do the filtering and rendering. this may make sense in certain situations, but normally it's not what you want.
my advice: if possible, use JSON.
ad *: you can use javascript on the server side (rhino, v8cgi, ...), but that's not what you have in mind.
I would go for JSON, you're not paying the "angled bracket tax". The choice between PHP and Javascript is related to the amount of processing required on the data (I'm taking a leap here).
Lots of processing, use PHP so it's server side. Little processing use Javascript for a more responsive page (load data via AJAX).
Although performance aspects really vary a lot between language/tool combinations, in the end xml and json tend to have similar performance characteristics when using best tools of the platform. That is, you won't find one more twice as fast or more; theoretical limits are similar for textual formats. Both are "good enough" in this regard for almost any use case.
So I would focus more on tool support, for the task you have. Other than that, format choice is unlikely to be the most important aspect to consider.
And like Jon mentioned, comparison of PHP and Javascript really sounds odd... apples and oranges or so.
One thing that has perhaps been missed is that a JavaScript client does not have to parse JSON, so you will get a performance win there. The browser will parse the XML into a DOM and hand this to your callback, you then need to extract from that DOM the info you need. With JSON you get back an object and the need to extract from the DOM is gone.
I think you'll have to measure it yourself. The performance will depend on:
the size of the data
the complexity of the data
its format (JSON or XML)
So you can see there are a number of variables.
Does the web service that you're using take longer to assemble the data in one format vs. another ?
There are a sizable number of options for parsing JSON and XML, so don't restrict yourself to PHP or Javascript (if you have a choice). And finally, if you're requesting from a webservice, you'll have the overhead of network transport costs, connection setup etc. So any time savings in parsing performance may be negligible. Your efforts may be better spent elsewhere.
I don't think I've answered your question, other than give you more things to think about!
You should use python, preferably :)
As for format, I guess JSON would be a bit faster, but it depends on the details, and this task would be network-bound anyway.
If you are using application with ajax then you should choose Javascript to process data on the client side which will reduce the usage of php on the server means more efficient server side. you can store your resultset in a json file and then can call it on client side with javascript this will be the best possible way because this will not consume you resources on server and data will be processed in the client side. here i will give preference to json over xml because xml takes more space to store than json because of its style of tags and json is like an array in javascript which will be faster than xml. same thing in server side, you can easly convert your json array to php array (just refer to json_decode function in PHP).
Now days json is in fashion because of it is easy to use and is faster.
for faster performance you should reduce the data processing on the server side and should use client side resource instead this approach will give your application speed and cost effectiveness.
I'm writing a shopping cart in PHP, and part of its function is to calculate shipping for a given set of products. For users with Javascript enabled, I want to provide the smoothest experience possible by having an accurate shipping calculation done on the client side so that changes in the cart do not require page reloads or AJAX calls.
Currently I have a function in PHP that calculates the shipping charge, and another function in Javascript that mirrors its functionality. I'm concerned that the formula may change frequently, and having to rewrite two separate functions in two different languages (and make sure their outputs match) could create maintainability problems.
What I'm looking for is a way of representing the formula for calculating shipping charges in some language agnostic way, so that it can be interpreted by both PHP and Javascript. Currently the shipping formula is only a function of a single variable (number of items) although I would like the capability to add more without too much rewriting.
Is there an accepted way to represent a fairly simple mathematical formula in a way that can be interpreted by both PHP and Javascript? Preferably without writing my own interpreter?
Edit: I don't need a whole function, just a fairly simple mathematical formula along the lines of "4 + 1.5n". The kind of thing you would find in a typical spreadsheet cell.
Generally, you are best off just to maintain two versions of the code. The most elegant solution, of course, is to write the server logic in JavaScript itself (see cappuccino.org); this would be a poor choice for you because it sounds like you have already written a ton of PHP code.
However, if you really feel the need to scratch this itch, consider an AJAX callback to the server. While slightly slower, most users will not notice.
I would say do it on server side, and user AJAX, It won't make much of difference for user, but maintaining two versions can make a difference when user after submitting the order sees the different calculation.
Anyway if you due to some reason do not want AJAX at all, best way would be to have single javascript library which is executed both at client and server side.
You may execute javascript from php on server side.
e.g. you may use following from linuxto execute javascript
http://www.mozilla.org/js/spidermonkey/
http://www.mozilla.org/rhino/
http://www.wxjavascript.net/
see http://en.wikipedia.org/wiki/Server-side_JavaScript for more options
This is a bad idea, and will become a worse idea the more complex the calculation becomes.
That being said, Javascript does support the dollar sign as legal in variable names. There's enough common syntax between the two languages that you could easily write code that parses and works the same in each, as long as you're only dealing with simple math. Arrays may be a bit tricker. Check out PHP.JS, a set of libraries to mimick PHP builtin functions in Javascript.
(Edit: I edited in the link to php.js without knowing someone else was going to post the same thing during my edit. Credit / horrors to him. ;) )
Maybe. Take a look at php.js. It gives you all the php functions but in JavaScript.
You could also write the whole validation in php, and use Ajax to query on the client side.
One would say this is the time to add some automated tests to your application, and run them at least each time you want to deploy your application to your production server -- and if some of those fail, cancel the deployment.
You'd have tests both for PHP and JS code, and some of those tests would calculate some total amount / charges / shipping costs ; and if something goes wrong because of some code change, you'd be able to detect the problem automatically, without your application breaking in production.
Of course, it requires a bit more work (both to write the tests, configure the building platform, and maintain the test data) ; but that would be a great security...
Another possible solution would be to write your calculation code only in Javascript, and run it both on the client side (this is not the hard part, obviously), and on the server side.
From PHP, you can execute JS code using the Spidermonkey PECL extension (Note it's still in beta, though ; and you'll need to be able to install PHP extensions, which will probably be possible only if you are admin of your server -- and not sure about stability).
Here is an article about it : Using JavaScript in PHP with PECL and SpiderMonkey.
With this solution, you could use JS for the code that only runs on the client ; PHP for the code that only run on the server... And JS for the code that runs on both sides.