Call a function when data is transfered to php file - php

I am here to ask that is there any settings argument in jQuery ajax() which let us to call a function when data has transferred to php file successfully not when the data has transferred and php file parsed the code and returned a value.
I have following code:
$.ajax({
..
..
..
success: function(data) {
// do something
}
});
But I want it like:
$.ajax({
..
..
..
onTransfer: function() {
// do something like show a div saying "Done".
},
success: function(data) {
// do something
}
});

You only get 1 answer from server side, what's wrong with success? If your process takes too long then you could return from script as soon as it get's started and show 'Processing your request' as result for success:
<?php
ob_end_clean(); // discard everything
header("Connection: close"); // send Connection close
ignore_user_abort(true); // ignore user abort
set_time_limit(0); // no time limit
ini_set("memory_limit","200M"); // setup a memory usage needed
ob_start(); // start output buffer
header("Content-Length: 0"); // send lenght 0
ob_end_flush(); // end and flush
flush();
// continue your script
Your script will continue to run while you receive a success answer from it.

You might use it like this
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
For more details please check following link
http://api.jquery.com/jQuery.ajax/

Related

ajax post then get file to use

I am new on php, and I am writing a code which allows me to send some data to php then doing some exec(), and then get the process output back to use(e.g. post one web page).
$.ajax({
url: 'some.php',
type: 'POST',
data: someData,
async: false,
success: function (html) {
$('#showonscreen').html(html);
},
cache: false,
contentType: false,
processData: false
});
and on php part is like
<?php
/*something like $cmd here*/
exec("$cmd $target_file $Output_fileName $upper $lower");
echo "<br/>done";
?>
after that exec() generates a output file (e.g image)with that Output_fileName under the root folder.
My question is can I get(or load?) this file directly back client side to use?(in success part?) Or I need a $.get to request from server again to get that file?
So, on client side, it works like, they upload a image, then click button to process it, then the result image is store under server root, then grab from it to show on the web page.
any help
On Server Side
First its good if you capture o/p like below
exec('your_command 2>&1', $outputAndErrors, $return_value);
Then
if (!$return_value) {
// Ok lets decide what next
} else {
// Ooops some problem error handling
}
As you mentioned if you are dealing with image then
echo base64_encode(file_get_contents($your_file_generated));
for plain text you can just
header('Content-type: text/plain; charset=utf-8');
echo file_get_contents($your_file_generated);
// OR
echo readfile($your_file_generated);
On Client Side
$.ajax({
..
..
success: function (server_response) {
$('#showonscreen').html('<img src="data:image/png;base64,'+ server_response +'"/>');
},
..
..
});

Why isn't my Ajax call Asynchronous

I'm using JQuery and AJAX to call a slow function in a PHP file, but I don't get a response until the PHP function is complete. I can't figure out why, despite 2 days of searching. I've shrunk it down to two test files, that exhibit exactly the same behaviour. My php function is thus, in a file called "ajaxfuncs.php":
<?php
Class AjaxFuncs{
public function __construct() {
$this->testbuffer ();
}
function testbuffer(){
echo 'Starting Test Buffer Output. There should be a 2 second delay after this text displays.' . PHP_EOL;
echo " <br><br>";
echo '<div id="testdata" class="testdata">0</div>';
// The above should be returned immediately
flush();
// Delay before returning anything else
sleep(2);
for ($a = 0; $a < 3; $a++) {
echo '<script type="text/javascript">document.getElementById("testdata").innerHTML="' . (int)($a + 1) . '"</script>';
flush();
// Delay for 1 second before updating the value
sleep(1);
}
}
}
$AjaxFuncs = new AjaxFuncs();
?>
The above works if I open the "ajaxfuncs.php" file in the browser. It does exactly as I'd expect, and the output updates every second until complete. So I know I've buffering sorted on the server.
But when I call it using the following $.ajax it's not right. I've put everything except the php for the ajax function into another php file called "testindex.php" for convenience. This is it:
<?php
header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-store, must-revalidate");
header ("Pragma: no-cache");
header("Expires: Mon, 24 Sep 2012 04:00:00 GMT");
?>
<body>
<a>Test Page. Wait for it...</a>
<div id="maincontent">
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
console.log ('Document Ready');
function callajax(){
var ajaxfilepath = "ajaxfuncs.php";
return $.ajax({
url: ajaxfilepath,
data: {action: 'testbuffer'},
type: 'get',
cache: false,
dataType: "text",
beforeSend: console.log('Starting Ajax Operation')
})
.done(function(result){
processajaxcalloutput(result);
})
.always(function(){
console.log(' Ajax Internal Complete Detected');
})
.fail(function( jqXHR, textStatus ) {
console.log( "Ajax Request failed: " + textStatus );
});
}
function processajaxcalloutput(result){
var message = 'Processing Ajax Response' ;
console.log(message);
$("#maincontent").append(result);
}
callajax();
});
Everything works without error. Console is clear - no errors (I'm testing with Chrome & Firefox). But I can't seem to get a response until the entire PHP function is done. I've tried everything I can find, in particular hundreds of different things to force caching off, but to no avail. Any help is much appreciated. Thanks.
Update:
So based on the feedback so far, it's clear the call is asynchronous and the code is fine, but asynchronous does not mean I'll get a continuous stream of output data from the php function as it executes. Instead the entire response will be returned at the end of the execution. Rather than divert this question into one about streaming, I'll leave it at this until I resolve the streaming issue.

ajax post request to php $_POST vars empty

I have a nginx rewrite rule that redirects an img src attribute to a php page. Within this php page I'm trying make a GET request, which on success makes a POST request to the same page, sending the data returned from the GET request as the data. Why is the $_POST data empty in the php script? If I hardcode $name = "http://path/to/my/img.png" in the php script the image renders correctly.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
var_dump($_REQUEST);
//if(isset($_POST['val'])) {
// open the file in a binary mode
$name = $_POST['val']; // ALWAYS EMPTY
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
//echo fpassthru($fp);
header("Location: $name");
exit;
//}
?>
<html>
<head>
<script type='text/javascript' src='/steal/steal.js'></script>
<script type="text/javascript" src="/plugins/jquery/json2.js"></script>
<script type="text/javascript">
steal('jquery/dom/fixture').then(function(){
$.fixture("GET /event/{code}", function(original, settings, headers){
return [200, "success", { "img_url":"http://path/to/my/img.png" }, {} ]
})
var strObj = <?php echo json_encode($_REQUEST); ?>;
var str = strObj.q;
var eventCode = str.split('/')[1];
$.ajax({
url: "/event/"+eventCode,
success: function(data) {
var imgUrl = data.img_url
$.ajax({
type: 'POST',
contentType: 'json',
data: {val:imgUrl},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
}
});
}
});
});
</script>
</head>
<body>
</body>
</html>
Alright, you've taken things a few steps beyond what is possible.
When the user hits this image in their email, a request is sent to your server asking for that image. None of that javascript is going to make it back to the user because the <img> tag is expecting an image, not an html document. You can tack things on to the outgoing request via something like
<img src="http://yourwebsite.com/tracker.php?val=someimage.png">
and your script will be able to get val out of $_GET but you won't be able to make a POST request for this image from inside an email.
All that $_REQUEST data you're getting at the top there? That's where you get all your email tracking data from. Everything you can get out of there and $_GET is all you're getting.
Afterwards, you need to give them back an image. So heres how you do that.
$val = $_GET['val']; // assuming val contains an image
header('Content-Type: image/png');
readfile('/path/to/your/images/'. $val);
Please be super aware that you need to sanity check $val to make sure its only containing images that you want to be able to see. A potentially malicious user could see this and put something like tracker.php?val=/etc/passwd or something similar and then you've got PHP trying to read your password file. Making sure that images exist and can even be read can be done with the is_readable() function.

how to call a php function from javascript using ajax?

i know this question was probably asked 1 million times, but for the 1.000.001 time :)
i need to call a php function from JavaScript. And i am having a bit of an argument on if ajax will do it.
i don't want to send any data just a ajax call that will call and run that function.
here is what i have so far:
$.post('functions/test.php', function() {
console.log("Hooray, it worked!");
});
is this gonna run the test.php ?
thanks
It definitely runs the test.php, to check it you may do sth. on succes
$.ajax({
type: "POST",
url: "ajax/test.php",
success: function(data) {
alert(data);
}
});
But what's the purpose of sending if no data is send?
Most likely, yes. I can't guarantee it because I don't do jQuery.
This, however, will definitely run it no problems (except versions of IE so old you shouldn't care about them):
var a = new XMLHttpRequest();
a.open("GET","functions/test.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
console.log("Hooray, it worked!");
// optionally, do stuff with a.responseText here
// a.responseText is the content the PHP file outputs, if any
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
Yes the test.php script will run, and you can grab the output from the test.php script like this (if you want to):
$.post('functions/test.php', function(data) {
//the `data` variable now stores the server response (whatever you output in `test.php`)
console.log("Hooray, it worked!");
});
In JQuery you can do:
$.post('functions/test.php', function(data) {
alert(data);
});
Whatever is returned in test.php will be put into the variable "data"
So you can do any php functions you need to in test.php and send the output back.
I always use
jQuery.ajax("url.php");

EXTJS Ajax request and Content-Disposition attachment

I want to get a watingmessage in extjs while loading a link. The response is a binarycode, which I want to downlad. The link is for example "test.php".
function loadurl(link){
Ext.MessageBox.wait('Loading ...');
Ext.Ajax.request({
url: link,
callback: function(options, success, response){
Ext.MessageBox.updateProgress(1);
Ext.MessageBox.hide();
if (success) {
// response : my attachment
}
else {
}
},
scope: this
});
}
{
...
//functioncall
loadurl('test.php');
}
I also tried in test.php.
<?php
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $content;
?>
But it doesnt work. If I just load the link it works, but without waiting message.
In the ExtJS Documentation there is a class called LoadMask which is designed to show a loading 'spinner' along with a short message. In your case, you would use it like this:
function loadurl(link){
var mask = Ext.LoadMask(Ext.getBody(), {msg:"Loading..."})
mask.show();
Ext.Ajax.request({
url: link,
callback: function(options, success, response){
if (success) {
// response : my attachment
}
else {
}
//do whatever work we need to do, then hide the mask
mask.hide()
},
scope: this
});
However, if, for whatever reason, the callback comes back almost immediately, then it is possible that the mask will not be visible because your file loaded too fast. If this is an issue, you could force a delay by putting your Ajax request inside a setTimeout.

Categories