Ajax function not calling php script - javascript

So I'm making a Image gallery site, and I have a bunch of buttons such as approve image, and download image, which call the JS function "runAJAX" and based on the request type, the php is supposed to prefore a specific task. The issue I'm having is that the AJAX function is saying it's successfully run, but the php file is not being run. When I run it, "Request Completed" prints but no txt file is created like it supposed to. Any help would be greatly appreceated. Thank you very much.
// imageID is an int of the image UID
// request is a string that describes the button (approve, download etc.)
function runAJAX(imageID, request) {
// myArr is a JSON array
var myArr = allJSON;
console.log("UID is" + imageID);
for (var i = 0; i < myArr.length; i++){
if (myArr[i].UID == imageID){
switch (request) {
case "approve": myArr[i].approved = "true"; console.log("Approve was set to true"); break;
case "download": console.log("Image will be downloaded"); break;
default: console.log("No action will be done for this request");
} // switch
} // if
} // for
$.ajax({
type: "POST",
url: 'requestAJAX.php',
data: {request: request, newJSON: JSON.stringify(myArr), download: imageID},
success: function(){
console.log("Request Completed: " + request);
window.location.reload(false);
} // success
});
} // runAJAX
requestAJAX.php
<?php
switch ($_POST["request"]) {
case "approve":
// output to checking to see what the request is
touch("AJAXtest.txt");
file_put_contents("AJAXtest.txt", $_POST["request"]);
unlink("test.json");
$stringyJSON = json_decode($_POST["newJSON"], true);
$finalJSON = json_encode($stringyJSON, JSON_PRETTY_PRINT);
$file = "galleryinfo.json";
touch($file);
file_put_contents($file, $finalJSON);
break;
case "download":
// output for checking to see what the request is
touch("AJAXtest.txt");
file_put_contents("AJAXtest.txt", $_POST["request"]);
// Get parameters
$file = $_POST["download"];
$filepath = "UploadedImages/" . $file;
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
exit;
} // if
break:
default:
// output for checking to see what the request is
touch("AJAXtest.txt");
file_put_contents("AJAXtest.txt", "No request made");
echo "No request was made";
}
?>

Related

PHP download not working (download function not called)

I need to export data from a database through a webapp. And when I call the function with ajax post method. The file is created successfully on the server, but after that it is not downloading it, the download function is not called, somehow, or it is not working. I don't know the reason, and I don't get any error messages.
Here is my jQuery function that sets post data for the php:
$(document).ready(function(){
$('#exportCSV').click(function(){
var ajaxurl = 'admin.php?page=site&edit=false',
data = {'export': 'csv'};
$.post(ajaxurl, data, function (response) {
});
});
});
A switch that runs the selected file export function, than tries to download it
switch ($_POST['export']) {
case 'csv':
$query = $_SESSION['query'];
$FName=exportToCSV($conn,$query,$fName);
download($FName);
break;
}
And the download script that is not called, or is not working correctly
function download($file){
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Length: ".filesize($file));
header("Content-Type: application/csv");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
And this is how this "site" is called.
Everything above is in the "somesite.php" file
if(isset($_GET['page'])){
switch ($_GET['page']) {
case 'site':
include("somesite.php");
break;
}
}

Why JS opens a txt file instead of downloading it?

Here is my code:
Server Side:
public function export(){
$arr = array();
if($_POST["type"] == "save"){
$name = "export.txt";
file_put_contents("$name",$_POST["text"]);
$arr["type"] = "link";
$arr["url"] = "http://localhost:8000/{$name}";
}
return $arr;
}
Client Side:
$(document).on('click', '#export', function () {
var names = ["سعید خرمی", "فرید هادوی"];
var namess = names.join('\n');
$.ajax({
type: "post",
url: "/export",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
type: "save",
text: namess
},
dataType: "json",
success: function(data){
var href = data.url;
window.location = href;
}
});
})
When I click on #export (button), it opens that .txt file (instead of downloading it). Something like this:
Noted that I use chrome .. Also it doesn't work in other browsers.
How can I force it to download that .txt file?
Change your success part like this,
success: function(data){
var href = download.php?filename=export.txt;
window.location = href;
}
And in your download.php:
Get the file name from the GET variable filename (say as $file).
Send the headers:
<?php
$file = $_GET['filename']; // get the filename
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: text/plain'); // the appropriate header type for txt file
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
Source: PHP Readfile Documentation

ajax get Excel form php

I am tryinh to get excel form php through ajax call when i load url of specific php gives me the output but when the same php is called via ajax with some ajax value nothing shows up.. am not sure what to do
ajax:
var fromdate= $("#fromdate").val();
var ToDate= $("#ToDate").val();
var Year= $('#Year').val();
var Category=$('#Category_1').val();
$.ajax({
url: "http://localhost/demo.php",
type: "post",
data: {
fromdate:fromdate,ToDate:ToDate,Year:Year,Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
}
});
PHP:
<?php
$conn=mysqli_connect('localhost','root','0000','xxxxx');
$filename = "users_export";
$fromdate = mysqli_real_escape_string($mysqli,trim($_POST["fromdate"]));
$ToDate = mysqli_real_escape_string($mysqli,trim($_POST["ToDate"]));
$Year = mysqli_real_escape_string($mysqli,trim($_POST["Year"]));
$Category = mysqli_real_escape_string($mysqli,trim($_POST["Category"]));
$sql = "Select * from xxxxxxxxxxx where category='$Category'";
$result = mysqli_query($conn,$sql) or die("Couldn't execute query:<br>" . mysqli_error(). "<br>" . mysqli_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$names = mysqli_fetch_fields($result) ;
foreach($names as $name){
}
print ("dasd" . $sep."dasd1" . $sep);
print("\n");
while($row = mysqli_fetch_row($result)) {
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++) {
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Basically there are two problems in your jQuery ajax request:
Sice you are specifying a content-type in your PHP script you have to tell jQuery what to expect from your ajax request using dataType: application/xls in your ajax object.
This is why you don't get any response, because it fails and you have not specified an error callback function to handle the error.
Moreover, in case of success you have to print somehow the content returned from the PHP script with something like $("#selector").html(responsecon);
Here is the updated ajax request:
$.ajax({
url: "http://localhost/demo.php",
type: "post",
dataType: "application/xls", // Tell what content-type to expect from server
data: {
fromdate:fromdate,
ToDate:ToDate,
Year:Year,
Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
$(#"some-container").html(responsecon); // Print the content
},
error: function() {
alert("error");
}
});

call and execute a javascript file from a remote php file

I have an angularjs service that sends a rest api link to a php file, the problem is that , this php file is calling another php file which contains a javascript code. When I execute the code in the service, it executes the php file , but the javascript code is just printed out without being executed. It's been a whole day of research but without any solution. Please can you tell me where the problem is? I have used require 'secondFile.php'; and include 'secondFile.php'; , I have also tried to bring the whole javascript code from the second file to the first file, so that I call the javascript locally, but it always prints the code without executing it.
Here is my code:
The angularjs service function:
var link = 'http://path/to/first.php';
$http.post(link, {idf : newDoc.idf})
.success(function (res){
console.log(res);
}).error(function (err) {
console.log(err);
});
the first php file, which is a remote file
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$method = $_SERVER['REQUEST_METHOD'];
//$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
var_dump($request);
$idf= $request->idf;
$val= $request->val;
switch ($method) {
case 'POST':
insertit($idf, $val);
break;
case 'PUT':
updateit();
break;
case 'REMOVE':
removeit();
break;
}
}
catch(PDOExecption $pe) {
echo "okay";
print "ERROR!".$pe->getMessage();
die();
}
function insertit($idf, $val) {
include 'connect.php';
$dataBilan = array($val);
$stmt = $DB->prepare("INSERT INTO `Test` (val) VALUES (?)");
$stmt->execute($dataBilan);
$last = $DB->lastInsertId();
$idf= $last;
$info_bilan= array(
'val' =>$val
);
$data = array(
'idf'=>$last,
'action'=>'update',
'table'=>'activite',
'data' =>$info_bilan
);
require 'second.php';
echo "okay done inserting";
}
and second.php:
<script src="pouchdb-5.3.1.min.js"></script><script type="text/javascript" language="javascript">
var dbRemote = new PouchDB('http://localhost:5984/Mydatabase');
var myDocs;
var value = <?php echo json_encode($data); ?>;
console.log(JSON.stringify(value));
if((value.idf != null) && (value.idf != 0))
{
console.log("-------here we go----");
dbRemote.allDocs({include_docs: true}).then(function (res) {
myDocs = res.rows.map(function (row) {
return row.doc; });
onUpdate(value);
});
}
}
function binarySearch(arr, docId) {
var low = 0, high = arr.length, mid;
while (low < high) {
mid = (low + high) >>> 1; // faster version of Math.floor((low + high) / 2)
arr[mid].id < docId ? low = mid + 1 : high = mid
}
return low;
}
function onUpdate(value)
{
console.log("couchdb's "+ myDocs.length);
if(myDocs.length !=0)
{
console.log("haha");
var index = binarySearch(myDocs, value.idf);
var doc = myDocs[index];
if(action== "update")
{
dbRemote.put(doc).then (function () {
console.log("Updated! ");
}).catch(function (err) {
console.log(err);
});
}
}
}
</script>
The content of second.php file is just printed out but it's not executed. When I execute first.php everything goes right , but when I execute the service I just see the printed file. Please any ideas?
Example:
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, '/usr/local/bin/php -i');

extjs Hidden form after download not firing success

Scouring the net for how to separate the download data from the success/fail data when doing a download using a standardsubmit in extjs, and can't find anything specific about how to do this.
For example, I have a hidden form that I am using to force a download:
var hiddenForm = Ext.create('Ext.form.FormPanel', {
standardSubmit: true,
height: 0,
width: 0,
hidden: true
});
hiddenForm.getForm().submit({
url: 'downloadtxt.php',
method: 'POST',
success: function(form, action) {
console.log('success');
},
failure: function(form, action) {
console.log('failure');
}
});
and on the server in PHP I have this code:
$file_name = "test.txt";
$file_data = "The text to save in the file";
header("Content-Type: " . "text/plain");
header("Content-Length: " . strlen($file_data));
header("Content-Disposition: attachment; filename=\"" . $file_name . "\"");
$result["success"] = true;
$result["errors"] = array();
$result["data"] = $file_data;
echo json_encode($result);
In this case, the entire contents of the $result array gets put into the download file (effectively buggering the contents, and additionally the success/fail methods never get called in the submit() code. Now, if I change the PHP server code to:
$file_name = "test.txt";
$file_data = "The text to save in the file";
header("Content-Type: " . "text/plain");
header("Content-Length: " . strlen($file_data));
header("Content-Disposition: attachment; filename=\"" . $file_name . "\"");
echo $file_data;
then the downloaded file contains what I expected ("The text to save in the file"), but the success/fail methods still never get called in the submit() code. How is it possible to trigger the success/fail code, but yet not bugger up the contents of the download file?

Categories