php echo something between 2 functions after an AJAX call - php

I am looking for a way to get an echo (or anything else) between 2 functions, the first being called via Ajax.
Here is what I am doing :
I upload via Ajax a video to the server where it is temporary stored.
then pass the video to a private function that send it to youtube via the API and after, unset the video on the server.
My question : between the 2 functions, is there a way to get from the PHP script something that can be handled by the client to inform him of the progress ?
I tried :
to send JSon
to update a session checked by JS while the Ajax call
flush() and ob_flush()
but always, data is returned at this end of the 2nd function (when I don't need anything anymore), as if, while the call and all that is after, PHP was unable to say something
I 'd like :
function upload()
{
//uploading
if(ok)
{
//echoing something there (the main goal)
goYoutube();
}
}
private function goYoutube() {
//etc...
}
and what I have is :
function upload()
{
//uploading
if(ok)
{
goYoutube();
}
}
private function goYoutube()
{
//etc...
//echoing something there (the bad bad bad useless thing)
}
It is with CodeIgniter and I don't have the hand on the server.
I don't need code, just an idea (which will be greatly appreciated)
Of course, something like "don't lose your time guy, it can't be done" is ok !
Thanks.

PHP is a server side language and I don't think it'll output something until the script finished executing. If I were you I would try to split those functions in two separate AJAX request.
The first request gives the user the answer that everything is ok (or something like "please wait") and the second request makes the call to the YouTube API.

You could do this by establishing a websocket connection and sending events from the server to the client. I usually do this in nodejs using socket.io. I see there is a similar option for PHP: elephant.io
So the order of things would be:
Establish websockets connection with server (before sending video)
In the clientside, listen for the event you will receive and do whatever update there.
Do the video upload.
In the serverside, send a websockets event where you would place you "echo"
Take a look at it, I really think it will do.

Related

Multiple php return values with jquery $.post

I dont really know how to ask this which is why I am asking it here. So if I was using some code like this:
$.post("/data/something.php", {stuff: 'hi'}, function(data){
$('#box').html(data);
});
Normally if you have php like this you only get 1 result:
<?php echo $_REQUEST['stuff'] ?>
I was wondering if there is any way for the php to send a bit of data, then a little bit more later without it just sending all of it at once like so:
<?php
echo 'Foo';
//Do stuff that takes time
echo 'Bah';
?>
There are 2 ways to accomplish this.
The first uses a standard workflow with the flush command (http://php.net/manual/en/function.flush.php). This means that you can do:
echo "Starting...\n"
flush();
// do long task
echo "Done!\n"
HOWEVER: This often won't work. For example, if your server uses deflate, the Starting likely won't get sent until the request is finished. Many other factors can cause this too (proxies, browser behaviour).
The better option is to use a polling mechanism. Your main script would write its progress to a file (with some session ID related filename), then delete that file when done. You would then add a second script to report the progress in this file (or completion if the file has been deleted) and your JavaScript would send an AJAX request to this checker script (maybe every second or two).
In PHP
<?php
echo 'Foo';
echo '||||';
echo 'Bah';
?>
In Javascript
var responses = data.split('||||');
//you will get
//Foo in responses[0]
//Bar in responses[1]
I expect that php has no problem doing that (as detailed by #Dave). The complicated part, is for javascript to retrieve the first part of the data, before the transmission completes...
I think what you are asking is answered here: Is it possible for an AJAX request to be read before the response is complete?
The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.
and...
So finally, yes it is possible, no it is not easy.

HTTP get request communication js to PHP doesn't return a result?

So I have a little js program running in a HTML5 canvas and I have a little http get request function in my js. The function itsself works(tested it with quite a few examples on the internet and it worked), but my own webserver doesnt return the right stuff when a request is sent to it.
my PHP looks like this:
<?php echo VVV::getUser()->userID ?>
When I open it in my browser it returns me the correct values the getUser()->userID returns. However when I send a Http request from my js it gets an empty result, however it works when used on various testing pages in the internet, so it must be my PHP or my server that cause this problem. any ideas?
This sounds like a cross-domain AJAX request problem. To solve this you really have just two options:
Have PHP make the cross-domain request. So whatever site that uses your AJAX will make a request to it's own server (like to its own ajax.php script) which then makes a request to your server and then returns it to the client.
Try to use something like easyXDM JavaScript library for cross-domain AJAX requests and see if that helps.
Here is a little sample for a simple cross-domain request (JSONP style):
1) On your server side, change the response to something like:
<?php echo( 'callbackFunc(' . VVV::getUser()->userID . ');' ) ?>
2) On the client side do something like:
function callbackFunc( userId )
{
// Do something with the userId
}
// Create a script tag which will load the call to the callback function
// with the user ID generated by the PHP code.
var s = document.createElement( "SCRIPT" );
s.src = "http://yourserver/yourpath/yourscript.php?maybesome=params";
document.body.appendChild( s );
The code loaded from your server will call callbackFunc() with the user ID.

Creating jQuery AJAX requests to a PHP function

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.

Using Ajax to Send Data Back to the Server

I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.

Displaying POST Data with jQuery?

I'm using a flash webcam to take a picture. It works great and spits back a URL via POST.
I'm coding in PHP and would like to display this POST data once it is recieved, the problem is that I dont re-load the page.
I've looked around and I'm not sure to dynamically load this array of data.
Where should I be looking? jQuery?
Ah, Figured it out. The Flash thing I have has a built in callback function, so I just have to append the data from there!
jQuery is not able to read any sort of request data other than that which appears in the URL (GET). You will need to use PHP (or some other server-side language) to handle the response created by the FLash application.
Due to the fact that you're using Flash for the process you are at somewhat of a disadvantage because unless the Flash application has some sort of JavaScript "PhotoUploaded" event notification, your page won't be notified that Flash has just submitted a picture to your server which needs to be retrieved and inserted. If you can modify the Flash application to make an external JavaScript event then you can proceed as Frankie has described in his answer; otherwise, if modifying the Flash application is not an option, then another solution would be to have your page send a request to the server every so often (5-10 seconds or so maybe), to check if there is a photo for it to display yet.
The simplest way to setup polling with your server in this fashion would be to make sure that each photo upload from Flash has a unique, pre-determined identifier that your page knows at initial load. You would then simply ping your server every few seconds with an AJAX request and pass it that unique identifier in order to find the right image should one exist.
Basic example:
function GetPhoto() {
$.get('/getphoto.php?ID=1541XJ55A6', function(response) {
if(response.ImageUrl !== "") {
$(".profile-image").attr("src", response.ImageUrl);
if(getPhotoTimer !== undefined) {
clearInterval(getPhotoTimer);
}
}
});
}
$(document).ready(function() {
var getPhotoTimer = setInterval("GetPhoto()", 10000); // every 10 seconds
});
Flash calls javascript each time it spits back the URL.
Javascript contacts server (php) and gets content
Javascript injects content onto page
Like this (flex code):
// attach a function to the completeHandler
private function completeHandler(evt:Event):void {
javascriptComplete();
}
// declare the function that will call the javascript function
private function javascriptComplete():void {
var javascriptFunction:String = "galeryUploadComplete("+Application.application.parameters.opt+")";
ExternalInterface.call(javascriptFunction);
}

Categories