My script works like that :
I make an AJAX call to a PHP script
The PHP script process a lot of data and writes the result to a .csv file (via fopen/fwrite/fclose)
When the PHP is done, I want my AJAX to open a download pop-up with the resulted file from the call
The last part is the problem here. When I try to make the user download the file, it just returns a 0 byte file.
The problem doesn't come from my PHP script since the file on the server is correctly modified and is the result of the data processing.
I've tried window.open, window.location, appending an anchor with download attribute, download.js, delaying the download, server permissions, etc. Nothing works.
I don't want to go the blob way since it's a lot of server-side data processing, and even if I could, I'm still really wondering why the heck I always get a 0 byte file
My AJAX call :
$.ajax({
url : './dataProcessing.php',
type : 'POST',
dataType : 'text',
success : function(result, status){
console.log(result); //Result being my file path
console.log(status);
window.open(result, '_self'); //One of the many things I've tried
},
error : function(result, status){
console.log(result);
console.log(status);
}
});
My PHP globally consists of :
<?php
$filename = 'myFile.csv';
$resource = fopen($filename, 'w');
//fwrite some lines
fclose($resource);
echo $filename;
?>
Related
So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");
I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});
I'm just working on an openvz script to run some VM's at home.
Anyway, I have been working on some js and ajax functions to send post requests, all ending up in an innerHTML section.
However, when the command is run, the result of the command is merged into a one line result, I would like to keep the original formatting because some vzctl commands produce very long outputs.
I originally had this working with PHP and a live result of the command would be outputted into the web browser.
I would like to keep the result on the same line and if possible, have it like my old setup with a sort of live console feed.
This used to work because I was just using php, but now I have AJAX on front of the php, and it removes the formatting.
CTID NPROC STATUS IP_ADDR HOSTNAME 101 21 running - -
The above is a sample output of vzlist when run with ajax, and the bottom without, how can I fix this?
CTID NPROC STATUS IP_ADDR HOSTNAME
101 21 running - -
Also is it possible to put the ajax output into a buffer like I had with php?
<?php
$cmd = 'sudo '.$_POST["command"].' 2>&1';
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
while (!feof($proc))
{
echo fread($proc, 4096);
# flush();
}
?>
Current PHP file with live console.
function whoami () {
$.ajax({
url:"virt.php", //the page containing php script
type: "POST", //request type
data: "command=vzctl start 101",
success:function(result){
document.getElementById("test").innerHTML =(result);
}
});
}
function ls () {
$.ajax({
url:"virt.php", //the page containing php script
type: "POST", //request type
data: "command=vzlist",
success:function(result){
document.getElementById("test").innerHTML =(result);
}
});
}
Current html with ajax.
Sorry for the long read, thank you.
You can try adding html and filesystem line breaks when you create the data for result.
When generating it, I assume in php, you would place the following just after where you would like the break.
"<br>\r\n"
You may already be generating the newlines, if so you could wrap your output in nl2br(). This will create html <br> elements in place of newlines. See nl2br.
I want download the file from server (I knew that we can't use AJAX, and serve is Servlet) and which dynamically generate according to the parameters.
Now I have the parameters in format JSON, like:
{"limitTo":"name","searchFor":["AAA","BBB","CCC"],...}
So, how can we send the request to the server with those paraleters? Do we need create some inputs?
Thanks, I found the solution which uses dojo/request/iframe, without window.open
And the code likes :
require(["dojo/request/iframe"], function(iframe){
// cancel the last request
iframe._currentDfd = null;
iframe("something.xml", {
handleAs: "xml",
data : "your json"
}).then(function(xmldoc){
// Do something with the XML document
}, function(err){
// Handle the error condition
});
// Progress events are not supported using the iframe provider
});
And then we can see download window.
Here is an article about dojo/request/iframe
I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');