My browser makes an ajax/json request to the server, which then calls out of several services to get data (taking various lengths of time) and then displays this data in the browser.
I could, wait for the server to complete and return all the data in one big go.
Ideally I would like it to return the data (json) whenever each of the individual calls completes. This way I can display them in the UI and if one of the service calls takes a long time, then the user can still look at the data, without looking at a blank screen.
I think its possible to get an ASP.NET web page or handler to send data back to the requesting client without buffering it.
But clientside, how can I process ajax response before its completed? Is this even possible?
I'm wondering if multipart MIME data type may be useful as well...?
Make a separate controller/function (depending on what backend you're using), and then make separate requests in your javascript. Since Javascript is asynchronous, results will display on your page as each function completes.
.NET pseudocode
public string Foo() {
string returnedJson = getFoo();
return returnedJson;
}
//Same thing for Bar and Bah
Then, in your Javascript (assuming you're using jQuery)
function onFooComplete() {
//In this function, display the data you get back from the server
}
$.get('/foo', function(res) {
onFooComplete(res);
});
For a more robust implantation, look into using a publish/subscribe methodology in your javascript. https://github.com/cowboy/jquery-tiny-pubsub is a very small but useful pub/sub implementation for jquery.
Related
So far when creating AJAX requests I have been posting to a separate PHP file. Is it possible to create a jQuery AJAX request that calls a PHP function rather than posts to a separate page?
If you could send me any examples or documentation would be great.
I believe there's a fundamental misunderstanding of how the technology works here.
AJAX (Javascript), Flash, or any client-sided technology cannot directly call PHP functions (or other languages running on the server).
This is true for going the other way around as well (eg: PHP can't call JS functions).
Client and server codes reside on different machines, and they communicate through the HTTP protocol (or what have you). HTTP works roughly like this:
Client (eg: browser) sends a REQUEST -> Server processes request and sends a RESPONSE -> Client gets and displays and/or processes the response
You have to see these requests and responses as messages. Messages cannot call functions on a server-side language directly 1, but can furnish enough information for them to do so and get a meaningful message back from the server.
So you could have a handler that processes and dispatches these requests, like so:
// ajax_handler.php
switch ($_POST['action']) {
case 'post_comment':
post_comment($_POST['content']);
break;
case '....':
some_function();
break;
default:
output_error('invalid request');
break;
}
Then just have your client post requests to this centralized handler with the correct parameters. Then the handler decides what functions to call on the server side, and finally it sends a response back to the client.
1 Technically there are remote procedure calls (RPCs), but these can get messy.
AJAX requests call a URL (make a HTTP request), not a file, in most cases the URL is translated by the server to point at a file (or a php script in your case), but everything that happens from the HTTP request to the response that is received is up to you (on your server).
There are many PHP frameworks that map URL's to specific php functions, AJAX is just an asynchronous way to access a URL and receive a response.
Said URL CAN trigger the server to call a specific function and send back a response. But it is up to you to structure your URL's and server side code as such.
If you're asking whether you can call any arbitrary PHP function with AJAX the answer is no*, for obvious security reasons (in addition to the technical reasons). You could make a PHP script that does different things depending on what parameter it's given (for example, execute a single function) if you don't want to create multiple separate files.
*Although you could make a script that would execute any arbitrary PHP command coming from the client, but that would be very, very, very unwise.
Short answer is "no" but the real answer is that you can fake it. NullUserException's answer is good. You create a server that will take the function name and its parameters. Then the server executes the function, and returns the value.
This was done a while back via a protocol called XML-RPC. There was also an effort called JSON-RPC that used some JS techniques.
One things that's cool about JS is that you can do things like this:
var base64_decode = create_remote_call('base64_decode');
function create_remote_call(name) {
return function(x) {
jQuery.getJSON('url/server.php',
{func:name,arg:x},
function(d){return d;});
}
}
A call to base64_decode('sarefdsfsaes') will make a ajax request and return the value.
That code probably won't work because it hasn't been tested, but it's a function that produces a function that will call the server, and then return the value. Handling more than one argument requires more work.
All that said... in my experience, it's usually good to make all network communications explicit instead of disguising it as a regular function.
you may achieve the same result using a bridge, like my phery library http://phery-php-ajax.net you can call PHP functions directly from Javascript and deal with the value. The AJAX is bound to DOM elements, so you can manipulate the calling DOM or just use jQuery from the PHP side. An example would be:
Phery::instance()->set(array(
'phpfunction' => function(){
return PheryResponse::factory()->jquery('body')->addClass('whoops');
}
))->process();
and in the javascript side (or HTML)
phery.remote('phpfunction');
the equivalent to the https://stackoverflow.com/a/7016986/647380 from John Kawakami answer, using phery is:
function base64($data){
return !empty($data['encode']) ? base64_encode($data['content']) : base64_decode($data['content']);
}
Phery::instance()->set(array(
'base64' => 'base64'
))->process();
function base64(content, decode, output){
phery.remote('base64', {'content': content, 'encode': decode ? 1 : 0}, {'type':'text'}).done(output);
}
base64('asdf', false, function(data){
console.log(data); // or assign to some variable
});
since AJAX is asynchronous and you can't just return a value from the AJAX call, you need a callback, but this would suffice.
I'm developing a web application and use jQuery to make asynchronous HTTP requests to my API. I have a detail view where you can see a lot of information of a specific object stored in the database. Because there is a lot of information and data that is linked to other objects, I make different calls to my API to gather different information for my views.
In the 'detail view' I have some kind of widgets that show the requested information. For that, I make about 5-7 HTTP GET requests to my API. When using the debugger (both Safari and Firefox), I can see that some requests are blocking other requests and the page takes a lot of time until everything is loaded and shown to the user.
I make a request like this:
$.get("api/api.php?object=myobject&endpoint=someendpoint", function(data) {
// data is JSON formatted
$("#my-widget input").val(data["name"]);
});
And another one e.g. like this:
$.get("api/api.php?object=anotherobject&endpoint=anotherendpoint", function(data) {
// data is JSON formatted
$("#other-widget input").val(data["somekey"]);
});
If the first request takes a little longer to finish, it blocks the second request until the callback function of the first request finished. But why? I thought that those calls are asynchronous and non-blocking.
I want to build a fast web application for a company where the requests are only made inside the local network, so a request should only take about 10-50ms (or even less). But the page takes about 10 seconds to show up with all information.
Am I doing something wrong? Or is there a JavaScript framework that can be used for exactly this problem? Any help is appreciated!
EDIT: As you can see in the screenshot, the requests have to wait some seconds, and if the request is fired, it takes a few seconds until a response comes back.
If I call the URL directly in my browser or do a GET request using curl it is a lot faster.
EDIT2: Thanks #CBroe! The session file write lock was the problem. As long as the session file is locked, no other script can run until the previous script finished. I just called session_write_close() immediately after session_start() and it runs a lot faster now.
Attention: Use session_write_close() only if you don't need to write to the $_SESSION array. Reading is possible after that, but writing not. (See this topic for further details: https://stackoverflow.com/a/50368260/1427878)
My page loads all necessary data from the server at startup via AJAX. This includes user's language settings, various classifiers, some business data etc.
The problem I am facing is that when the user first comes to the page, all these different AJAX calls are kicked off at the same time. This means that on the server side, most of them are assigned different JSESSIONID-s (I am using Spring on Tomcat 8 without any complex configuration). As a result, some of the data is initialized on the server side in one session, but the browser might end up using a different session in the end and does not have access to the data set up by earlier ajax calls.
I wanted to solve this by using a fast synchronous AJAX call in the very beginning so that after it returns and gets a JSESSIONID, all subsequent calls would be made in this original session.
$.ajax("api/language", {
type: "GET",
cache: false,
async: false,
success: function(data) {
//do stuff;
}
});
// more AJAX calls
It works, but I get warning messages that synchronized XMLHttpRequest on main thread is deprecated. Now - I understand the reasons why such a synchronized call is bad for UI in general, but what other options are there available for me if I want to force all AJAX calls to use the same server side session?
I can achieve the same result by using a callback and just placing all the rest of my page initialization code in there, executing it in the 'success' section of the first AJAX call, but that wouldn't that have exactly the same effect as synchronizing on main?
I'd initiate the session when loading the HTML document rather than when requesting something from the API.
Alternatively, trigger the subsequent API calls from the success callback of the first one.
"Hacky" solution
You really give your own solution at the end: wrap everything in an asynchronous AJAX call. It is similiar to the synchronous solution, but this way you can set up a loading animation, or something similar.
"Nice" solution
Another, possible nicer solution. When the user arrives, you can redirect to the starting page of your web application with the generated jsessionid. This can be done with a servlet. I am quite sure that Tomcat can be configured to do this without writing your own code.
Its known that interactions between Javascript and SQL-Databases are not very secure. But most Websites use it cause the Webside doesent reload to show matches in a search.
With PHP it isn't possible to change Page-Contents without a completely Page-Refreshing.
Witch is the right way to get Data from SQL with Javascript without security-neglects.
Aspeccialy for a Searching function with directly matches in a list.
You can use 2 way to get data from db by using js;
1. Ajax:
function refresh() {
$.ajax({
url:"your url",
method: "GET",
data: your_params,
success: function(response) {
$("#specific_div_id").html(response);
}
});
}
You can do this within an interval like;
setInterval(refresh, 5000);
in order to get content in every 5 sec.
2. Websockets
In AJAX, you are requesting in every 5 secs to get updated content from server. Think that, you are not getting content server pushes updated content to you. In other words, server notifies you on any updated data. You can have a look at Socket.io for an example implementation of websockets. When server notifies you, you can take data and put it related html area
As mention in the commentaries, the best way is to use AJAX, which is an acronym that stands for Asynchronous Javascript and XML.
The last part, XML, is a bit misleading. It kept that name because that's what is was first use for. But AJAX can now be use to make HTTP request and interface with any language, including PHP.
Depending on the technology you are built on, there are several implementation available. Chances are you have jQuery installed already. In that case, jQuery Ajax, and particularly jQuery.get() would address your concerns.
If you are using a router on the backend, you can simply call a route, specifying it as the url, first argument of the function. Otherwise, you can directly call a file by using the relative path from the html page the javascript is embedded in.
jQuery.get will return anything you echo within you server script. In other words, anything that is directly rendered on the page. You can use a callback catch the data returned and process it.
Example :
$.get('/path/to/file.php', function (data) {
console.log('Here is the data received from the server!', data)
// Process data here
});
I'm just wondering..is it possible to receive multiple responses from a single ajax call?
I'm thinking purely for aesthetic purposes to update the status on the client side.
I have a single ajax method that's called on form submit
$.ajax({
url: 'ajax-process.php',
data: data,
dataType: 'json',
type: 'post',
success: function (j) {
}
});
I can only get one response from the server-side. Is it possible to retrieve intermittent statuses? Such as:
Default (first): Creating account
Next: Sending email confirmation
Next: Done
Thanks for your help! :)
From a single ajax call, I don't think it is possible.
What you could do is check frequently where the process is (it's what is used for the upload bars in gmail for example). You do a first ajax request to launch the process, and then a series of ajax request to ask the server how he is doing. When the server answers "I'm done", you're good to go, and until that you can make the server respond and say the current state.
There is something called comet which you can set up to "push" requests to client, however it is probably way more than what you are wanting to invest in, time-wise.
You can open up a steady stream from the server, so that it continues to output, however I'm not sure how client-side script can handle these as individual "messages". Think about it like a server that outputs some info to the browser, does more work, outputs some more to the browser, does more work, etc. This shows up more or less in real time to the browser as printed text. It is one long response, but it is still one response. I think ajax only handles a response once it finished being sent, but maybe someone else will know more than me on the topic.
But you couldn't have the server output several individual responses without reloading itself, at least not with PHP, because once you start outputting the response, the response has begun and you can't chop that up without finishing the response, which happens when the script is done executing.
Your best bet is with the steady stream, but again, I'm not sure how ajax handles getting responses in chunks.
Quick Update
Based on the notes for this plugin:
[http://plugins.jquery.com/project/ajax-http-stream]
things don't look promising. Specifically:
Apparently the trend is to disallow access to the xmlhttprequest.responseText before the request is complete (stupid imo). Sorry there's nothing I can do to fix this
Thus, not only can you not get what you want in one request, you probably can't get it multiple requests, unless you want to break up the actual server-side process into several parts, and only have it continue to the next step when an ajax function triggers it.
Another option would be to have your script write it's status at specific points to another file on the server, call it "status.xml" or "status.txt". Have your first ajax function initialize the process, and have a second ajax function that queries this status file and outputs that to the user.
It is possible, but it has more to do with your backend script. As Anthony mentioned there is a tech called comet. Another term I've heard is called "Long polling". The idea is that you delay the time in which your php(insert language of choice) script finished processing.
In php you can do something like this:
while($response !== 'I'm done'){
sleep(1);
}else{
return $some_value;
exit();
}
This code stops your script from completely finishing. sleep(1) allows the script to stop and lets the server rest for 1 millisecond, before it loops back through. You can adjust the sleep time based on your needs. In php the amount of time the script sleeps is not counted agains your server timeout time.
You'll obviously need to make more checks for you code. You'll probably also want to allow for an abort script call. Something like sending a get request to kill the backend script. Maybe on the javascript unload event.
In the tests that I've done. I made the initial ajax call, and when the value was returned, I made another ajax call, that way your back end script wont time out.
I've only played around with this on my local server, so i'm not sure how real world this is, but it works.