Download CSV Via AJAX Post - php

Hi there Stackoverflow. I am trying to call a PHP script via AJAX that will create and download a CSV file. I know this isn't normally supposed to be done, however I would like to do it this way.
My ajax below returns the csv data as shown by this output:
$.ajax({
type: "POST",
url: "<?=site_url('front_office/get_csv/')?>",
data: {hashed_center_ids : hashed_center_ids, print_data : print_data},
dataType: "text",
success: function(response) {
console.log(response)
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
window.open(uri, 'test.csv');
}
});
The problem is that using the lines
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
window.open(uri, 'test.csv');
does not download the file as a CSV. But rather it give it no extension with the name "download". Does anybody know how can I make it so it downloads with the .csv extension? Thanks.

I can't comment, so: You can change the name of the csv by adding following to the header
filename=whatever.csv

Related

Upload image via Ajax

Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax.
They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.
I don't want to change all the function and go trough a submit if it's not necessary.
I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file.
And the ones that i found that looked simple where in flash...
Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.
Thank's in advance mates ;)
//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();
$.ajax({
url: "/save_changes",
dataType: "json",
data: data,
method:"POST",
success: function (response) {
if(!response.status){
toastr_error(response.desc);
$( "#submit_confirm" ).prop( "disabled", false );
$("#"+response.camp).focus();
}else{
toastr_success(response.desc);
}
}
});
}
client side
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
});
server side
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
You can achieve this in simpler way using "ajaxSubmit".
Include jquery.form.js on your page and submit your form.
$(form).ajaxSubmit({
url: url,
type: "POST",
success: function (response) {
// do what you need with response
});
It sends all form data including file on server then you can handle these data in regular manner.

jQuery POST not working - seems it should be

It's been a while since I've played with jQuery, so I'm wondering what I'm missing here.
I've set up a php page that writes a test txt file when the jQuery calls it.
The txt file is being written, so jQuery is finding the php page, but then displays my error alert, not my success one, so something is not working.
My php:
$testfile=$_SERVER["DOCUMENT_ROOT"].'/test.txt';
$file5 = fopen ($testfile, "w");
fwrite($file5, 'testy');
fclose ($file5);
exit();
My jQuery:
var g = {
r: 1
};
$.ajax({
type: "POST",
url: "/test.php",
cache: false,
data: g,
success: function (data) {
alert('yay');
},
error: function (data) {
alert('nay');
}
});
Anything obvious I'm missing?
Thanks for taking a look.
I think the problem is on the url you are requesting. Its hard to tell without know the type of error or without knowing your folder structure or if you are using any PHP framework. Please, write details
Try this--
url: "test.php",

Reading blob data using PHP and JavaScript

I have an application where a user is allowed to save some text data into a MYSQL database through a web interface. In addition, they can also attach a file to this text and I save this into a blob field. The file types that get attached are simple .txt files.
I am able to save this data into the database but I am having trouble retrieving it. This is what I am doing to retrieve it right now:
//Events that take place when trying to retreive an attached file
function getFile(rowid){
//Make an AJAX Request to fetch the file
$.ajax({
type: 'get',
url: 'point-of-contact.php',
data: 'page=attachment&row='+rowid,
dataType: 'text',
success: function(data) {
console.log (data);
}
});
}
The AJAX request above leads to the following PHP code:
$attachments = $poc -> getPOC($_GET['row']);
header('Content-type: text/plain');
echo $attachments;
The problem I face is that when I console log the data received from the AJAX request I get this:
How do I go about getting the data in simple text format?
Could it be that the way I am uploading the file to the database is incorrect? This is how the file is uploaded to the DB:
//File upload code
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
//Hide the save button
$("#save-button-1").hide();
//Make the AJAX request
$.ajax({
type: 'post',
url: 'point-of-contact.php?page=add',
data: 'point_of_contact=' + $("#textarea1").val() + '&point_of_contact_attachment=' + file,
success: function(data) {
$('#done-1').show();
setTimeout(function() {
$('#done-1').fadeOut();
}, 2500);
$('.loader').fadeOut();
}
});
There is problem in your upload section. The line
var file = fileInput.files[0];
assignes file object into file variable. Later, when you add it to
"point_of_contact_attachment="
it gets converted to string. So you will have
"point_of_contact_attachment=[object file]"
And that is it.
try pointing the browser directly to the file instead of using ajax.
Like this
document.location = point-of-contact.php?page=attachment&row='+rowid;
Since it is not a file the browser can read, it will just download it.
However you will still need to get the TXT via ajax, because document.location redirect to the user to a plain text page.

Calling PHP function when link is clicked

I have a PHP function
function ExportExcel()
{
// code
}
and a link on the page Download in Excel
<a>Download in Excel</a>
So what I want is when users clicks on that link, PHP function would be called and data will be downloaded in excel.
I may need to Ajax for that. How do I go about doing that ?
You could possibly just use a GET statement, so it would look something like this...
HTML
Download in Excel
PHP
function ExportExcel()
{
// code
}
if($_GET['init'])
{
ExportExcel();
}
here is the function i implemeted recently:
$('#toexcel').live("click",function() {
$.ajax({
url: "toExcel.php",
data: "sql="+encodeURIComponent(sql),
beforeSend: function(){
$("#wait").show();
},
complete: function(){
$("#wait").hide();
},
success: function(response){
window.location.href = response.url;
}
});
});
where sql variable actually stores sql query to the server,
and then toExcel.php if getting passed sql, submitting it to the server and outputs the result using PHPExcel() object.
EDIT
i think i understood what you trying to achieve. your ExporExcel() function already outputs the results you need, right? is so, then you can do it as follow:
$('#toexcel').click(function() {
$.ajax({
url: "toExcel.php", // should contain and _call_ you ExportExcel() function
beforeSend: function(){
$("#wait").show(); // this is loading img to show
},
complete: function(){
$("#wait").hide(); ;// this is loading img to hide once complete
},
success: function(response){
window.location.href = response.url;
}
});
});
first let me make sure you know php is only parsed when the page is first being distributed. If you click a link on the page, it has no idea the php function on the same page exists because the function only existed server-side while the code was being parsed. That being said, you can easily make a separate page called download.php and call your function on that page. Then your link can just link to that page.
If you want your custom download page to return to the user as an excel file, you can use custom php headers to convince the browser that it is downloading an excel file. (you'd have to specify the MIME type for excel files)
edit:
this would cause a download to start of an excel file created by your function call and activated by your link click. You don't need any JS or JQuery for this.
edit2:
here's example code for the download file to get you started
<?php
header("Content-type: application/excel");
print($data); /* print out the contents of the excel file here */
exit();
?>
If you do it like this, your php page will not redirect from your original page, but will bring up a download box from the browser instead. If your using csv files instead of xls files, you'll need to change the mime type.
you can handle the request in your js scrpit file
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
Just provide link of that excel file in href of anchor , browser will download automatically
If your file form DB then providelink of excel.php , and in excel.php do processing of getting excel file and creation of it .
read this artical..do like that

Posting Ajax data to Controller function?

In my PHP/jQuery application, I have a javascript file, in which I can call an external PHP file (post_data.php) like this:
$.ajax({
type: "POST",
data: "some data",
url: "post_data.php",
Now, instead of calling php file, i would like to call a CodeIgniter contoller function Data/post_data, so how can I call that function instead of post_data.php?
The javascript file in which i would like to call is located:
root/js/test.js
while the function is located here:
root/application/controllers/data/post_data
The ajax need to have a full url:
$.ajax({
type: "POST",
data: "some data",
url: "http://www.yourdomain.com/urpath/post_data"});
The reason is the Javascript file that call the Ajax is not aware of the server location of the .php file. So, by using the absolute path you make sure that your call will be done. Also, to test it before using the Javascript file, copy and paste the url into your browser. If no 404 error is displayed, than you have your good path.
To add to Doaks response, you can also do it like this
$.ajax({
url: "<?php echo site_url('data/post_data'); ?>",
type: "POST",
data: data,
You can use $.post() JQuery function it's more simple and optimized for POST request. Also for routing, you can set just controller and method. It's enought.
$.post("admin/newphone", {
phone: $('input[name="phone"]').val()
},
And link to JQuery docs http://docs.jquery.com/Post

Categories