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)
Related
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.
I been learning php and ajax from w3schools but I have come across a simply question for which I cant find an answer to.
To request something from a php file I use a xmlhttpRequest object and specify the url (of that php file). Does this mean one php file for one request only? Let's say on a webpage there are a user log-in box and a comment box, I would need two php files to take the requests? I always thought the server side will have one main file that handle all the requests, each request from client will have a ID to specify what the request is and send back the necessary data to client. So what is the right?
I read a lot of material online, but everything is just basic example with just one request and one response.
You can use the same file for multiple requests. You can supply parameters along with the AJAX request, either by including them in the URL after ? (they'll be available in $_GET and $_REQUEST) or by using the POST method and sending them as form data (they'll be available in $_POST and $_REQUEST). You can use the Javascript FormData API to encode this properly; see the documentation here. Using the jQuery library can simplify all of this.
One of the parameters can then be a command or operation code, and the script can take different actions based on this.
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...
Facebook has introduced a ticker which shows live news scrolling down. How can I have this same time of functionality on my site? I don't care to use an iframe and have it refresh because it will A flicker and B make the page loading icon come up (depending on browser). How can this be done?
For this you'd want to fetch the data you're looking for with AJAX every X seconds.. Also known as polling.
Here's the break down: Every X seconds, we want to query our database for new data. So we send an asychronous POST to a php page, which then returns a data set of the results. We also declare a callback function (native to jQuery) that will be passed the data echo'd from our PHP.
Your PHP:
if (isset($_POST['action'])){
if ($_POST['action'] == 'pollNewData'){
pollNewData();
}
}
function pollNewData(){
$term = $_POST['term'];
$sql = "select * from TABLE where TERM = '$term'";
$result = get_rows($sql);
echo json_encode(array('status'=>200, 'results'=>$results));
}
Your front end javascript:
setTimeout(pollForNewData, 10000);
function pollForNewData(){
$.post('url/ajax.php',{
action: 'pollNewData',
term: 'your_term'
}, function(response){
if (response.status == 200){
$.each(response.results, function(index, value){
$("#container").append(value.nodeName);
});
}
}, 'json');
}
What essentially is going on here is that you will be posting asynchronously with jQuery's ajax method. The way you trigger a function in your PHP would be by referencing a key-value item in your post depicting which function you want to call in your ajax request. I called this item "Acton", and it's value is the name of the function that will be called for this specific event.
You then return your data fetched by your back end by echo'ing a json_encoded data set.
In the javascript, you are posting to this php function every 10 seconds. The callback after the post is completed is the function(response) part, with the echo'd data passed as response. You can then treat this response as a json object (since after the function we declared the return type to be json.
Pretty much the only way you can do it is with some sort of Asyncronous javascript function. The easiest way to do it is to have javascript priodically poll another http resource with that information and replace the current content in the dom with the new content. Jquery and other javascript frameworks provide AJAX wrappers to make this process reasonably simple. You aren't limited to using XML in the request.
It's a good idea to make sure that even without javascript enabled that some content is available. Just use the javascript to 'update it' without having to refresh the page.
You can do this kind of ticker using Ajax... using AJAX you can poll a URL that returns JSON/XML containing the new updates and once you get the data, you can update the DOM.
you can refer this page for introduction to Ajax.
Ajax is the best method but that's what everyone else already mentioned. I wanted to add that although I agree ajax is the best method, there are other means too, such as Flash.
There are two approaches possible for obtaining updates like this. The first is called push and the second is called pull.
With push updates, you rely on the server to tell the client when new information is available. In your example, a push update would come in the form of Facebook telling your site that something new happened. In general, push schemes will tend to be more bandwidth friendly because you only transmit information when something needs to be said (Facebook doesn't contact your site if nothing is going on). Unfortunately, push updating requires the server to be specially configured to support it. In other words, unless the service you are asking for updates from (ex. Facebook) has a push update service available to you, you cannot implement one yourself. That's where pull techniques come in.
With pull updating, the client requests new information from the server when it deems necessary. It is typically implemented using polling such that the client will regularly and periodically query the server to see what the latest information is. Depending on how the service is oriented, you may have to do client-side parsing to determine if what you receive as a response is actually new. The downside here is of course that you likely will consume unnecessary amounts of bandwidth for your polling requests where no useful information is obtained. Similarly, you may not be as up-to-date with new information as you would like to be, depending on your polling interval.
In the end, since your site is web-based and is interfacing with Facebook, you will likely want to use some sort of AJAX system.
There are a few hybrid-ish approaches, such as long polling via Comet, which are outlined rather well on Wikipedia:
Push technology: http://en.wikipedia.org/wiki/Push_technology
Pull technology: http://en.wikipedia.org/wiki/Pull_technology
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.