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 +'"/>');
},
..
..
});
Related
I want use AJAX to ask PHP to read a file and return data. The problem is, PHP can read the file but AJAX cannot get the data.
$.ajax({
type: 'GET',
timeout : 1000,
url : '../tools/test2.php', //read file and echo
dataType : 'json',
cache : false,
beforeSend: function() {
$("#demo2").val('loading..')
},
success : function(data) {
$("#demo2").val('message:' + data) //this never can run
}
});
//test2.php
<?php
header("Content-type:text/html");
$fileName = "./testFile.txt";
$file = fopen($fileName, "r");
echo fgets($file);
fclose($file);
?>
You said:
dataType : 'json',
And then you said:
header("Content-type:text/html");
So jQuery tried to parse your HTML as JSON, failed and ran the error handler (which does nothing because you didn't write one) instead of the success handler.
Fix your dataType (you can just remove it so that jQuery will respect the Content-Type header) or rewrite the PHP so it returns JSON instead of HTML.
(If you are actually returning plain text (since you have a .txt file) then say Content-Type: text/plain).
So I have a page where the user will hit the "export" button and I want to run a javascript function and get the data I need for the export and then call a php script to get the data from my database and force a download. Right now the problem is, I can run the javascript and then I call a post to my script, but nothing is downloaded. I am assuming it is because I am not actually moving the window to the php file, I am simply calling the script. can anyone help me out?
javascript: ids is an array that I need to pass to get the information. This is inside the function taht I call when the user hits the "export" button.
$.ajax({
type: "POST",
url: "exportLeads.php",
data: { 'idArray' : ids }
});
php: I used this Export to CSV via PHP quetsion. The function are implemented properly and I get no errors. There is just no file that is prompted for download.
$data = mysql_query($query) or die($query.mysql_error());
$results = array();
while($line = mysql_fetch_array($data, MYSQL_ASSOC)){
$results[] = $line;
}
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($results);
die();
You cannot download files with ajax. You can use window.location.href to redirect user to the file location, but whatever, i suggest you to read this, someone has a better answer for you :)
Download a file by jQuery.Ajax
or you can also use something like this
in your javascript
$.post( "exportLeads.php", { 'idArray' : ids }, function( response ) {
if ( response.error === 0 ) {
window.location.href = response.location;
}
}, "json" );
and in your php file
<?php
if ( $has_error ) {
echo json_encode( array( "error" => 1 ) );
}
else {
echo json_encode( array(
"error" => 0,
"location" => "link_to_file"
) );
}
?>
Got no time to write code, but in few words, you need:
Execute JS to call server side via ajax.
Generate file, put it to the server drive with some random name. Remember that name to session. Send some response to client.
When client gets response, redirect user with JS to some page where PHP code checks if there is some filename in session, and if there is, reads this file, deletes it and its name from session.
You could go for window.location.href in your success function:
$.ajax({
type: "POST",
dataType: "json",
url: "exportLeads.php",
data: { 'idArray' : ids },
success: function(data) {
if (data.success) window.location.href = "/link-to-your-download-script";
}
});
You would have to change the response to json_encode and split the functionality into two scripts, one for the export and one for the download script (with a unique id or sth.)
I'm trying to test an ajax call on post by doing the following just for testing purposes, but for some reason the call is never successful. I've been searching around and there isn't much that I could find that would explain why this isn't working.
$.ajax({
type: "POST",
url: "file.php",
success: function(data) {
if(data == 'true'){
alert("success!");
}
},
error: function(data) {
alert("Error!");
}});
file.php contains the following:
<?php
return true;
?>
Can someone please point me in the right direction. I realize that this may seem simple but I am stumped. Thank.
return true will make the script exit. You need:
echo 'true';
Firstly check your paths. Is file.php residing in the same folder as the file that your javascript is contained in?
If your path is incorrect, you will get a 404 error printed to your javascript console if you are using chrome.
Also you should change your php to:
<?php
echo 'true';
Once your path is correct and your php is amended you should be good to go.
Have you tried by accessing to the file directly and see if it outputs something?
return true shouldn't be use in that case (or any other, it's better to use exit or die), everything get by a AJAX call is hypertext generated by server side, you should use (as they pointed you before echo 'true';)
You could also try a traditional AJAX call XMLHttpRequest (without JQuery) if problem persists, and then check if there is any problem between the request and server..
EDIT: also, do not check by comparison, just make an alert to 'data' to see what it gets.
In addition to the echo 'true' suggestion, you can also try to alert the actual data that's returned to ajax. That way you can see if you have the proper value/type for your if statement.
success: function(data) {
alert(data);
}
try this, the new ajax syntax
$.ajax({ type: "POST", url: "file.php" }).done(function(resp){
alert(resp);
});
Here is correct way:
$.ajax({
type : "POST",
url : "file.php",
success : function (data) {
/* first thing, check your response length. If you are matching string
if you are using echo 'true'; then it will return 6 length,
Because '' or "" also considering as response. Always use trim function
before using string match.
*/
alert(data.length);
// trim white space from response
if ($.trim(data) == 'true') {
// now it's working :)
alert("success!");
}
},
error : function (data) {
alert("Error!");
}
});
PHP Code:
<?php
echo 'true';
// Not return true, Because ajax return visible things.
// if you will try to echo true; then it will convert client side as '1'
// then you have to match data == 1
?>
I'm trying to send a base64 image generated on one server and sent to a PHP file on another. So far all I'm getting cross origin errors on the client side and the server with the PHP file doesn't seem to receiving anything.
Here's the code:
Server 1 JS :
function shareDesign() {
$('#twitter').on('click', function() {
//console.log('?image='+encodeURIComponent(canvasExport)+'&designName=test')
$.ajax({
type: 'POST',
url: 'http://mysite.com/share_page.php',
dataType: 'text',
data: {
image : canvasExport ,
designName:'test'
} ,
success: function(data) {
console.log(data);
}
})
})
}
Server 2 PHP:
$image = $_POST['image'];
$designName = $_POST['designName'];
$sHTML_Header = "<html><head><title>SHare design test</title></head><body>";
$sHTML_Content = '<div id="test"><img src="'.$image.'"/> This design is called : '.$designName.'</div>' ;
$sHTML_Footer = "</body></html>";
echo "parseResponse({'status' :'success'})";
Addition:
I need this to work on mobile, is this possible? Also I do not have any server control on the JS server it's on adobe business catalyst.
I have a simple checkbox, on click it sends XHR to PHP page , php processes correctly and I use json_encode($response) to return. But instead of a simple true or false I get the source code for the page and it is causing a "parsererror" of course.
ajax call as follows
$.ajax({
type: "post",
url: "myprocessor.php",
dataType: 'json',
data: { "id" : idnumber, "action": "makeLive", "isLive" : "1" },
beforeSend: function(data) {
$("#ajaxInProgress").addClass('progress');
},
success: function(data) {
$("#status").removeClass().addClass((data.error === true) ? 'error' : 'success').text('Success! Appraiser is NO LONGER Live ').slideDown('slow');
},
error: function(data) {
$("#status").removeClass().addClass('error').text(' - Changing the Live status for this appraiser to "Not Live" has failed - APPRAISER IS STILL LIVE IN SYSTEM, please try again').slideDown('slow');
},
complete: function(data) {
$("#ajaxInProgress").removeClass('progress');
setTimeout(function() {
$("#status").slideUp('slow').removeClass();
},2000);
}
});
The php I post to is as follows:
if (isset($_POST['action'])) {
if($_POST['action']=='makeLive') {
$checkappraiser=mysql_query("SELECT * FROM table WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_numrows($checkappraiser)>0) {
$livesetting=mysql_result($checkappraiser,0,"live");
$livesetting=!$livesetting;
$runSql = mysql_query("UPDATE table SET live='$livesetting' WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if(!$runSql) {
$return['error'] = true;
} else {
$return['error'] = false;
}
}
}
echo json_encode($return);
}
Any suggestions would be great.
I am getting the proper data passed
I am getting the correct data updated in DB
My response is coming back as a parser error because it is trying to parse the source code as a json array.
Just a quick check, do you put <?php at the beginning of your php file?
That, or you're doing something wrong in your webserver, not passing files through to php correctly. Does hitting the php file directly load the source or the result?
If you hit page.php, does it load the same thing as if you hit page.phP or pHP, etc? It matters to web server filters, depending on the web server...
If you use tomcat for java, for example... you can turn off case sensitivity for finding files, but it does not turn off case sensitivity for mapping files to filters or servlets, so .jsp would load the jsp servlet, but .jsP would not.