avoid mismatch between server side and client side result - javascript

I use PHP and Javascript. In my website some results are processed server side some client side.
Using javascript only, prevents your website from being crawled correctly by search engines and using PHP only prevents correct real time response.
The problem is how to grantee both js functions and PHP functions give the same result? for example suppose there is a function which gives relative time:
JS:
function relative_time(timestamp)
{
...
}
PHP:
function relative_time($timestamp)
{
...
}
Keeping both functions matched with each other is not easy since I want to edit both. For example if both give us:
one year ago
And I change PHP only, to give me:
a year ago
Then JS is not updated too. Is there any standard way to ensure both will act in the same way?
unfortunately js function cannot be called on server side.

If there is some complicated logic, you should implement it server-side and just pull the results via AJAX. That way you only need to maintain the PHP code and provide a kind of AJAX API for access via JS.

I think you just need to make a decision where it is to be done, because if they do vary which is to be dominant ? (that's the one that should be doing it)
Also, how are you saving server load by doing it in both locations ?
Avoid this by making a decision for which code is to do it, failing that, Put a note in you code at both locations reminding yourself to update both locations ?

Related

Save large data-set to mySQL table from Javascript without POST?

I have a large-ish amount of server-side data that I need to store in a mySQL table. [I'm a novice, working through the learning curve of javascript & php.]
I'm thinking it's best to stringify the javascript array into a JSON object and send that to a PHP page to save to the database. Once the data's in a PHP array, I know how* to get it into the database; I'm just not sure what's the best way to get it there.
I can't POST (like this example) since the maximum length of a POST string is 2048 characters, and I have maybe 10-20kb of data.
I'd rather not use AJAX or Node.js (like this example) for the sake of simplicity, and since this is a one-off (but both on my list to learn in the future!)
Or, would it be best to create a temp text file to the server with javascript, and then call a PHP page to load & process the data? (Although I can't find examples of how to do that without using POST.)
I understand the difference between server-side & client-side (thanks to this great explanation) but the size limit of POST seems to be my issue?
*Also I'm a little unsure as to when/how it's necessary to encode data (like with this deprecated mysql-real-escape-string example) for storage with {json/posting/DB tables/text}. In this case my data could contain 'single' & "double" quotes (but no foreign characters 国外 वर्ण), which [in my short experience] seem like the only times it will be an issue?
Thanks!
The problem is that Javascript is client side language while PHP is server side language. This means that PHP cannot interact with the user without some HTML, CSS or JavaScript and visa-versa, JavaScript can't interact with server side files without some PHP. Why is this? Since JavaScript is client side the user can edit it as they can see the code while with a PHP script it is all on the server and they are not able to see the code, only what it outputs/prints. So in short you cannot do what you are asking without POST or GET and it is not possible to do this without a server side script such as a PHP script (Python is also very useful if you are thinking of learning more about web backends).
There are numerous example of how to do this that you can find with a simple google search, here is a great example send data to MySQL with AJAX + jQuery + PHP
Hope I could clarify your question.

Running Javascript functions or threads in PhP

I have written a game.
It is an async turn based game where each person logs in at any time in the day, submits their orders, and at some time at the end of the day, the present turn is resolved.
However, the client side needs to know how to resolve previous turns, because it has to display it visually with all its many nuances. I have written this turn resolution in javascript.
Unfortunately, there is a secrecy element to the present turn. So I cannot just send all the data for the present turn to someones machine, get it to use its javascript functions of turn resolution in the code, then send it back to the database for everyone else to gather when they log in. Why not? Because that one person could catch the data, see the secret bits from other players, before allowing it to be sent back.
That means I have to completely rewrite my javascript code in PhP, so the secret turn resolution of the present turn can be done in private on the server.
So here is my question. To help me having to write my turn resolution code twice, once in javascript for the client (who needs the visual interpretation from the turn resolution) and again in php so the secret stuff of the present turn can be done in private, is there any way my php code can call my javascript turn resolution code from the php page?
Ie, I want my php page to be able to call a javascript function in a js file, which is all done on the server.
Do you really need to do it in PHP ?
If your hosting solution support node.js, you can reuse directly your javascript inside your server-side app.
It's called isomorphic javascript. (see : http://isomorphic.net/)
Another way to do it, would be to embed a javascript engine and call it from PHP (e.g : https://github.com/phpv8/v8js)

Filtering PDO and MySQL queries with JS/jQuery

Sorry for my ignorance on the lack of knowledge I have on this subject however I cannot find an answer to my question anywhere.
So I have this MySQL table:
Feed_ID Vehicle_ID FullRegistration Colour FuelType Year Mileage Bodytype Doors Make Model Variant EngineSize Price PreviousPrice Transmission PictureRefs ServiceHistory PreviousOwners Description FourWheelDrive Options Comments New Used Site Origin V5 Condition ExDemo FranchiseApproved TradePrice TradePriceExtra ServiceHistoryText Cap_ID
As you can see each column will contain vehicle data.
I have displayed all of the results in the database using PDO onto my front end, all data is displayed in a listing style similar to Ebay.
Now I need to filter these results however I have noticed that many result filter systems are using JS.
Here are some examples so you get a better idea of what I am talking about:
http://www.autotrader.co.uk/search/used/cars/
http://www.motors.co.uk/search/car/
As you can see all the filters are using JS however I am having a problem understanding how JS is filtering the MySQL query?
I know this question might be a little broad but can someone show me an example of how JS can filter PDO results just like the examples I have shown?
Thanks
The first one uses what I suspect to be a combined method of Javascript and a server-side language (it's hard to prove, because I can't see the server-side code involved). For simplicity, I'll assume this server-side language is PHP, though it could easily not be.
Basically, all Javascript is doing on the first website is setting cookies and telling you to refresh the page. Once you refresh, PHP fetches the cookies that Javascript set and filters the results from the MySQL query based on those cookies.
Now, the second one is actually filtering using Javascript, yet at the same time still using PHP (again, it could be any server-side language).
This is a method called AJAX. It is a function built into Javascript which allows you to fetch another page from Javascript (aka. send and receive an HTTP request).
The reason this is useful is because once you've changed an option on that page, Javascript can send an HTTP query using AJAX to something like "http://www.motors.co.uk/search/getcarinfo.php?transmission=manual", allowing PHP to fetch a new dataset from MySQL and return it to Javascript (this probably isn't the API entry point that they use, but it has to be somewhere in their Javascript).
Once Javascript receives the response from that page (usually in JSON or XML form), it can modify HTML to update what's shown on the page.
To answer your question directly, Javascript doesn't filter the data. MySQL filters the data based on a PHP query, which returns its response to the Javascript. Then, Javascript just puts it on the screen.

PHP: Passing info to JavaScript

say, my PHP script needs some time to calculate its operations. I need to keep the client informed about the operation progress. An example can be PHP based file download, where I need to provide to client estimated time needed to finish the download, and the amount of data that needs to be copied.
In PHP I can calculate all the needed information. However, how to regularly update the client with this info?
Ideally, I would like to dynamically update JavaScript variable from within my PHP script. I read that this is not possible, so what options do I have then?
Possibilities that come to my mind:
Should I do regular AJAX calls from within my JavaScript into the PHP script to get the progress info?
Should I study for me yet unknown COMET methodology
Do the two above possibilities make sense? Is there any other more practical solution available?
Thank you in advance.
Yes, both of those options make sense.
There are lots of different COMET-style techniques, but one of the simplest is a long-running iframe. You have a PHP page that monitors the progress of the operation, and outputs something like this at regular intervals:
<script>parent.updateProgress(relevantUpdateInfo);</script>
...where relevantUpdateInfo is the information about the progress, and updateProgress is a global function on the page containing the iframe that shows the updated information in the UI.
When outputting the script tags, be sure to flush the output.

Best practices for returning and displaying data from AJAX calls

I have some jquery/php interaction set up on a page. It submits some data to the server and gets back records of data which are then to be aligned on the page for comparison and possible action beyond that.
My question is what is the best practice for returning the info and then displaying it?
Return JSON object and then create
html on the fly with js and display
the data?
Return JSON object and then
put that data in already created
containers for the data on the page?
Return pure html from the server and
just put that on the page?
I was rolling these through my head last night and couldn't really figure out if one way would be better for any particular reason.
I'm not a js guru so wasn't really sure the pros/cons and caveats to these different methods.
I think it ends up depending on your app.
Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not.
However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner.
Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.
This completely depends on the way you have things set up in your application. I, for one, prefer to return JSON (second approach in your list), because I have an 'error code' parameter that I check in onSuccess function before updating the content on the page, and if it's not zero then I notify the user of the error, including the error message that came back from the server (server-side validation, database timeout, etc.).
I think you're missing a perfectly valid option, one which I use often. This is my typical schema and it has yet to fail me... :-)
Here's the basic jQuery template I use:
$(function() {
$.getJSON('/some/page',{foo:bar,bar:foo},function(json) {
if(json.outcome == 'success') {
$('body').prepend(json.html);
} else {
// Somehow let the user know why it didn't work
alert(json.error);
}
});
});
Here's the basic backend (PHP in my case) structure I use:
<?php // Page: '/some/page'
/* Blah Blah Blah... do whatever needs to be done... */
// If everything turns out okay (assuming '$output' is the HTML
// you want to display...
echo json_encode(array('outcome'=>'success','html'=>$output));
// If something goes wrong... just do:
echo json_encode(array('outcome'=>'error','error'=>'Uh oh... something is broken'));
Naturally, you'll want to be more specific with your error by putting them into some variable or something. But, you should get the idea. Also, of course you can add more information to the json output. You can have some pre-made HTML and also some other information like a 'success notice' or a new class name for some element, I dunno... whatever... the possibilities are endless.
Anyways, the reason I choose this route is because it's usually faster (based on my experience) to append pre-made HTML to the DOM rather than looping over JSON and inserting the stuff unless it's just, like, a bit of text to replace into an element. But, the method I've shown is, IMO, the best of both worlds. You can attach HTML as a string to one of the JSON properties.
Happy jQuerying :-)
The "possible action beyond that" part of your question makes a big difference. If you need to do other things with the data besides display it, returning as JSON is a clearly better option because you can work with the data as a native JavaScript object instead of having to traverse the HTML DOM. If all you ever intend to do is display it, I don't see any reason to go through the trouble of building that display in JavaScript; just build the HTML in your presentation layer on the server.
This came up recently and possible a dupe: The AJAX response: Data (JSON, XML) or HTML snippet?.
If you are going to be creating HTML then you may as well be returning HTML directly and inject it into the DOM. However, there are times you need to work with objects which is where JSON comes in handy.
If you return a Person object for example then you can greet Person.Name and show Person.Preferences which is really handy. It depends on your design but the general considerations should be to keep HTML out of Javascript unless you're building RIA.
I have used all three and have come to the conclusion that returning HTML is better when introducing new elements to a page.
My experiance is that when building HTML with javascript I am usually replicating work that will have already have been done for the non javascript user journey.
I still prefer parsing json for updating existing elements or creating javascript only functionality. I tell myself this for bandwidth, but I think it just because I love javascript.
As a forth option, I read a great post about how Flickr deal with vast quantities of data with string concatination. Basically just parse a big o' string down the pipe and chop it up on the client. This significantly reduces the on the server, with only a marginal increase on the client.
Returning pure HTML is the best solution. For the most part gzip should neutralize any difference in bandwidth, and rendering via javascript on the client can be slow if the client is a crappy machine. Finally, writing javascript to render HTML is hard to work with compared to using something nice like a view if you use MVC.

Categories