Run javascript function then post for download - php

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.)

Related

How to use ajax to execute php function that will push a file to the browser?

I'm trying to write a method in a php class that will use ajax to execute a php function that will push a file back to the browser.
It seems like its trying to write the file to the modx log, getting a lot of binary garbage in there.
Here is the method:
public function pushDocuments($formdata){
$data = $formdata['formdata'];
$file = MODX_PROTECTED_STORAGE . $data['target'];
$file_name = basename($file);
if (file_exists($file)) {
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
};
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => array(),
);
$output = $this->modx->toJSON($output);
return $output;
}
and here is the jquery:
$('.btn-get-document').click(function(){
var target = $(this).attr('data-target');
var postdata = {"snippet":"DataSync", "function":"pushDocuments", "target": target}; // data object ~ not json!!
console.log('target = ' + target + postdata );
$.ajax({
type: "POST",
url: "processors/processor.ajax.generic/",
dataType : "json",
cache : false,
data: postdata, // posting object, not json
success: function(data){
if(data.status == 'success'){
console.log("SUCCESS status posting data");
}else if(data.status == 'error'){
console.log("error status posting data");
}
},
error: function(data){
console.log("FATAL: error posting data");
}
});
});
it's running through the scripts and giving a success in the console [because I am forcing success] but no file is prompted for download and the binary garbage shows up in the modx log
What am I doing wrong?
In order to download a file, you'd have to use JS to redirect to the file's location. You can't pull the file contents through AJAX and direct the browser to save those contents as a file.
You would need to structurally change your setup. For instance, your PHP script can verify the existence of the file to be downloaded, then send a link to JS in order to download the file. Something like this:
if ( file_exists( $file )) {
$success_message = array(
'file_url' => 'http://example.com/file/to/download.zip'
);
}
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => $success_message
);
Then modify the "success" portion of your AJAX return like this:
success: function( data ) {
if ( data.status == 'success' ) {
location.href = data.success_messages.file_url;
} else if ( data.status == 'error' ) {
console.log( 'error status posting data' );
}
},
Since you're directing to a file, the browser window won't actually go anywhere, so long as the file's content-disposition is set to attachment. Typically this would happen if you directed to any file the browser didn't internally handle (like a ZIP file). If you want control over this so that it downloads all files (including things the browser may handle with plugins), you can direct to another PHP script that would send the appropriate headers and then send the file (similar to the way you're sending the headers and using readfile() in your example).
#sean-kimball,
You might want to extend MODX's class based processor instead:
https://github.com/modxcms/revolution/blob/master/core/model/modx/processors/browser/file/download.class.php
It does the download from any media source and also access checking if you want.
Its implementation on manager side is:
https://github.com/modxcms/revolution/blob/master/manager/assets/modext/widgets/system/modx.tree.directory.js#L553
Back to your case, these examples might bring you some ideas.
JS Example:
$.ajax({
type: "POST",
// read my note down below about connector file
url: "assets/components/mypackage/connectors/web.php",
dataType : "json",
cache : false,
data: {
action: 'mypath/to/processor/classfile'
}
success: function(data){
},
error: function(data){
console.log("FATAL: error posting data");
}
});
Processor example:
<?php
require_once MODX_CORE_PATH . 'model/modx/processors/browser/file/download.class.php';
class myDownloadProcessor extends modBrowserFileDownloadProcessor {
// override things in here
}
return 'myDownloadProcessor';
For this, I also suggest you to use MODX's index.php main file as the AJAX's connector so the $modx object in processor inherits the access permission as well.
http://www.virtudraft.com/blog/ajaxs-connector-file-using-modxs-main-index.php.html

ajax send data to "test.php", and then open "test.php" directly to show the result

I want to send an array from javascript to php via ajax function.
And I don't want show the result as callback, but immediately open the target php file and show the images.
I mean, I want open the php file directly on the server side.
I think this is quite simple, but I just have no idea.
My javascript looks like:
var stringArray = new Array("/images/1.jpg", "/images/2.jpg", "/images/3.jpg");
$.ajax({
url: 'test.php',
data: {stringArray:stringArray},
success: function() {
window.open('test.php'); // It opens test.php in a window but shows nothing!
},
});
the test.php file:
$stringArray = $_GET['stringArray'];
foreach($stringArray as $value) {
echo "<img src=" . $value . "></img>";
}
Thanks for any help!
Likely the window.open command is being called without the POST data needed.
Now, I don't know what you want to do here but, why send an Ajax request when you don't really want to make use of it?.
Edit: just to make it a bit clearer, you seem to be calling the php file with no data trough POST. There is no clean way of opening a window in JS with POST data, just try GET for no critical information. Let is know how it goes.
As I can see, You are sending data by post method and accessing in test.php
but when u open file via window.location it doesn't get POST data hence no data get populated
You can achieve it via $_SESSION.
in test.php
session_start();
if(!empty($_POST['stringArray'])) {
$_SESSION['stringArray'] = $_POST['stringArray'];
}
$stringArray = (isset($_SESSION['stringArray']) && $_SESSION['stringArray'] != '') ? $_SESSION['stringArray'] : $_POST['stringArray'];
foreach($stringArray as $value) {
echo "<h3>" . $value . "</h3>";
}
Hope this will work for you...
you should write
var stringArray = new Array("apple", "banana", "orange");
$.ajax({
type: 'post',
url: 'test.php',
data: {stringArray:stringArray},
success: function(message) {
window.open(message); // It will open a window with contents.
},
});
I doesn't show the output because when you open the page on the callback you are not sending anything through to the test page through the post variable. Why you would want to do this I don't know. Send the information through the url, get.

How to read Excel File data in php while sending it via jquery

This is my jquery code which sends data to php file -
jQuery("#btn_upload").click(function(){
var exceldata = jQuery("#form_imput_field").serialize();
var url = "phpfilepath/get-data-from-excel/exceldata/" + exceldata;
if( exceldata != "" )
{
jQuery.ajax({
url: url,
type: 'post',
success: function(data)
{
alert(data);
}
})
}
else
{
alert("I am in else");
}
});
My PHP Method -
public function get-data-from-excel()
{
//Get All Parameter data
$params = $this->_getAllParams();
echo "<pre>";print_r($params);die;
}
How can I read Excel data from this ? To create Excel I used PHP EXCEL previously but could get it to use in read as I dont know how to split data from this stream.
Current alert output - MAX_FILE_SIZE=134217728
If you are trying to submit a <input type="file"/> tag using JQuery and AJAX bad news, you can't do that with JQuery alone. You need to use a plugin to archieve that. For example iframe-post-form.
Once you have the excel file in your server (stored in some temporal dir for example) you should be able to read it using PHPExcel.php

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

Posting data with curl - actually refreshing to the next page

I'm trying to send post data between pages with Post. Not a form - like I may be passing validation error between pages or something (using it in several places).
The cURL is executing fine, but it's just tacking on the new page at the bottom. How can I execute a cURL Post and load the following page?
So my goal is to send data between pages. I do not want to use GET or cookies as I do not want to rely on the user, and I'd prefer not to use $_SESSION as it is not so much directly about a session as sending private data between pages.
Thanks
$ch = curl_init($some_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'myvar=something');
curl_exec($ch);
curl_close($ch);
I doubt the code has any relevance, as it's about performing a task not code syntax (there may be one in this example but you'll have to trust me it's not the code that's buggy as it's retrieving fine).
You could separate your $_SESSION superglobal into arrays describing both the current user/session and any errors that your form has created. For instance,
$_SESSION = array(
'user' => array(), // user data goes here
'errors' => array() // validation data goes here
);
if (!$_POST['myvar'] == 'something') {
$_SESSION['errors']['myvar'] = 'You must specify a value for <code>myvar</code>';
}
You would then be able to output errors on subsequent pages using a call something like this:
if (isset($_SESSION['errors'])) {
foreach($_SESSION['errors'] as $error) {
echo '<li>' . $error . '</li>';
}
}
Why are you using cURL? Why not just use AJAX:
$(function() {
// Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',
data: 'var1=value1&var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});
Using ajax for exec
$(function() {
/
data: 'var1=value1&/ Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});

Categories