javascript vs. php : pros and cons for code development - php

If a user refreshes a page I need to send the data using php as it accesses a mysql table.
If the user adds content, I don't want to run an AJAX call "first" as I can simply and immediately update the DOM, and then send a one-way ajax call to store it in the mysql table.
So on a referesh I have PHP creating my XHTML and sending it to the Browser.
On user input, I have the DOM update immediately followed by ajax call to put it in the mysql table.
Thing is I have to write code in JS and PHP for each user action that modifies the page.
Should I have the data sent to the Javascript for entry into the DOM and not do less with it in the PHP. What are the tradeoffs from taking user input and converting it to the UI with javascript vs. php?
Should I offload as much as possible to the client to reduce server load?

You have answered it yourself:
With php you need to send it through ajax and wait for response
With javascript you need to maintain 2 set of templates (server- and client-side one)

If you need to do something with the data serverside (validation, processing, etc), you can either use JavaScript with AJAX, or send it off on a page reload using POST or GET, depending on what you're sending. If you don't need to do anything with the data serverside, then using JavaScript to modify the DOM immediately is fine.

DOM operations aren't fast. Try it and you'll see that is better for your users to pass real HTML as it is or JSON-embedded with AJAX requests. Even big names like Twitter do it so.
If you still want to get away without PHP consider server-based JavaScript, e.g. Node.js.

Related

Validating From using AJAX and jQuery without sending data to another file

my problem is - for now - not about specific code but more about basic understanding - I think.
I want to create a formular and use the data without refreshing the page, so that brings me to AJAX.
Now do I always have to create a seperate file that works with the data that AJAX sends? Can't I just "grab" the data and work with it on the same page?
I think I missunderstood some basic concepts.
I thought about something like this:
<form id="load_filters_form">
..
</form>
<?php
var_dump($_GET); // values from <form>
?>
<!-- AJAX, jQuery -->
<script>
$("#load_filters_form").submit(function(event){
event.preventDefault();
$.ajax({
type: 'get',
data: $(this).serialize()
success: function() {
$("#load_filters_form")[0].reset();
}
});
});
</script>
What you're proposing is certainly possible, it's exactly how AJAX works. You make an AJAX request from JavaScript code, sending any data the server-side code will need, and handle the response from the server in your JavaScript code.
The problem with what you're proposing is that you're making it unnecessarily complex for yourself. Consider what your code in the question would return to the JavaScript code in the AJAX response. It returns an entire HTML page, most of which is already on the client.
Why re-transmit all of that data that the client already has? Why have code on the client to parse out the data it's looking for from all of the unnecessary markup around that data?
Keep your operations simple. If you need a server-side operation which receives data, performs logic, and returns a result then create an operation which does exactly that. Call that operation in AJAX and use the resulting data.
Now maybe that response is structured JSON data, which your client-side code can read and update the UI accordingly. Or maybe that response is raw HTML (not an entire page but perhaps a single <div> or any kind of container which presents an updated version of a section of the page), which your client-side code can swap into the UI directly.
The AJAX interactions with the server should generally be light. If you're intentionally re-loading the entire page in an AJAX operation then, well, why use AJAX in the first place? The point is to send to the server only the data it needs, and receive back from the server only the data you need. For example, if all you need is to update a list of records displayed on the page then you don't need the whole page or even the HTML table of records, you just need the records. JSON is useful for exactly that, returning structured data and only structured data to the client. Then the client-side code can render that data into the structure of the page.
Now do I always have to create a separate file that works with the data that AJAX sends?
Yes and no. You may choose not to have a specific file which your ajax is pulling, but you do need some sort of Routing and Controller relationship as most frameworks build it.
You could in theory create a request to self (the same page) but that's bad logic. You are going to mix backend logic with frontend and will get messy - very quickly. You really need to separate all three elements,
PHP takes the data and process it
JavaScript takes the data and displays it
Your html should be code free; Just a pretty finalized product.
The best design pattern is to separate those files in their proper environment.
Can't I just "grab" the data and work with it on the same page?
Not really, at least not consistently. You also have to keep in mind it's a potential issue in attempting to serve two separate contents from the same route/file:
if ajax
// do something
else
// do the other thing
Ajax does not want fully rendered HTML files, it takes too long; it's best to serve JSON objects/arrays which will be rendered in your frontend via JavaScript; which was also used to make the request - in the user's browser without the latency caused by their network or your server.
There's no sure way of knowing which request is what since no data from the client is trustworthy, including HTTP headers; they are easy to fake and could potentially lead to security/unwanted results.
Thus, the best solutions is to have a foreign file which you would make the requests to, instead of doing it from itself.

jQuery AJAX - Get data from php during the request

I'm using AJAX to insert data in MySQL database. During the AJAX request, there is a PHP function that loops inside a JSON array in order to get data and to insert it inside the DB. Everything works fine.
But, I would like to know if there is a way to pass, during the AJAX request a PHP var to jQuery in order to append it in HTML or to retrieve the data with console.log. I can get these info on AJAX complete but is it possible to get info during AJAX request?
I think you can just echo the php var on the page?
E.g. echo "<label>".$phpVarToAppend."</label>";
Nope. HTTP is stateless. You make a request and you get a result.
You must use different techniques to check the request's processing advancements from server.
Given that you store a record of the progression during the processing somewhere (db, cache or whatever), the simpler trick is using another AJAX call to a simple function that returns the last processing record.
This is a traditional polling mechanism.
A more advanced solution could be using a different connection upgraded to websockets. This will be a true realtime channel.
On top of these there's a world of possibilities. It only depends on what you need to manage with your POST request and how long does it take the processing.
For big payloads it's usually better to return immediately and start processing in a different task. (and thus a pooling mechanism to check progression)

How to track Update in database table using PHP?

I want to ask is there a way to track database table using php mysql.
I want to do something like i have a table called post. Now when user post some data other user need to view this data. That is latest one need to be view to user on the top. We can do this by refreshing div after every few sec or using ajax. But can we use Trigger. As we know it automatically fires when something is executed. Hence i want to know can we use trigger in PHP code to automatically detect changes in table. And when a new post is available it needs to return the data from database. Please give me a brief description about this. Thank you in advance.
The trigger is executed on Mysql Server, not on the PHP one (even if those are both on the same machine).
So, I would say this is not quite possible -- at least not simply.
Still, considering this entry from the MySQL FAQ on Triggers :
23.5.11: Can triggers call an external application through a UDF?
Yes. For example, a trigger could invoke the sys_exec() UDF available at MySQL Forge here: http://forge.mysql.com/projects/project.php?id=211
So, there might be a waty, actually, via an UDF function that would launch the php executable/script ; not that easy, but seems possible ;-)
Read more about it in:
https://stackoverflow.com/a/1467387/3653989
SQL trigger is a database object executed server-side.
You want a front-end technique to refresh your data without refreshing the whole page.
You can refresh your page using:
<meta http-equiv="refresh" content="5">
With PHP, you can refresh the page using:
header("refresh: 3;");
but no-one would suggest you to use such a method, because your need is refreshing the page, only after a change in your database, and not continuously.
So, if you already use PHP, you need Javascript Push technology:
Push, or server push, describes a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. (wikipedia)
JavaScript polling, long-polling, real-time techniques, and javascript frameworks such as jquery, node.js, socket.io include a lot of practices that give you this possibility.

Getting big amount of data from a very slow external data-source

I need to recieve a big amount of data from external source. The problem is that external source sends data very slow. The workflow is like this:
The user initiates some process from app interface (common it is fetching data from local xml file). This is quite fast process.
After that we need to load information connected with fetched data from external source(basically it is external statistics for data from xml). And it is very slow. But user needs this additional inforamtion to continue work. For example he may perform filtering according to external data or something else.
So, we need to do it asynchronously. The main idea is to shows external data as it becomes available. The question is how could we organise this async process? Maybe some quess or something else? We`re using php+mysql as backend and jquery at front-end.
Thanks a lot!
Your two possible strategies are:
Do the streaming on the backend, using a PHP script that curls the large external resource into a database or memcache, and responds to period requests for new data by flushing that db row or cache into the response.
Do the streaming on the frontend, using a cross-browser JavaScript technique explained in this answer. In Gecko and WebKit, the XmlHttpRequest.onreadystatechange event fires every time new data is received, making it possible to stream data slowly into the JavaScript runtime. In IE, you need to use an iframe workaround, also explained at Ajax Patterns article linked in the above SO post.
One possible solution would be to make the cURL call using system() with the output being redirected in a file. Thus PHP would not hang until the call is finished. From the PHP manual for system():
If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.
This would split the data gathering from the user interface. You could then work with the gathered local data by several means, for example:
employ an iFrame in the GUI that would refresh itself in some intervals and fetch data from the local stored file (and possibly store it in the database or whatever),
use jQuery to make AJAX calls to get the data and manipulate it,
use some CGI script that would run in the background and handle the database writes too and display the data using one of the above from the DB directly,
dozens more I can't think of now...

jQuery sortables and how to save the current sorting to mysql

Example I want use this sortables - http://interface.eyecon.ro/demos/sort.html
How to save the current layout setting to MySQL? Any clue?
You would have to send the information back to the server, most likely with an AJAX call of some sort. Then the PHP server-side could save it to MySQL. jQuery/Javascript cannot communicate directly with the MySQL database, you have to send the data to PHP first.
So an example might be, whenever the layout changes, make a $.get or $.post call in jQuery that sends information on the new layout to a php file, which process it and updates the database accordingly.

Categories