Send file as a response from ajax request - javascript

I have a javascript function that sends the name of the audio file on my server to a php script using jquery get. It looks like this:
function getAudioClip() {
var x = document.getElementById("clips").value;
$.get( "get_audio.php", { filename: x } )
.done(function( data ) {
loadAudioClip(data);
});
}
The function loadAudioClip(data) displays the waveform of the audio file given as data. I want to make get_audio.php return the audio file with the file name x, so I can use it to display the waveform using my loadAudioClip(data) function.
Edit: I figured out that maybe I can get a file directly instead of using php, like this
function getAudioClip() {
var x = document.getElementById("clips").value;
$.get( "audio/" + x , function( data ) {
loadAudioClip(data);
});
}
Is that possible? x is a filename(ex. MyRecording02.wav).

Opening an audio file with PHP will be slow process. Maybe you can check the existence of the file with PHP, and then if file exists, simply do something like this:
header("Location: $filename");

Related

Load yaml file using javascript and get the data in the yaml file

I am creating a function to load a yaml file via javascript and however I am stuck on how to get the data from the yaml file where I will subsequently use the data to fill up labels in my HTML page.
Here is my progress for the javascript so far:
<script>
// YAML file to Javascript object
$.get( 'yaml/cars_loan.yaml', function( text ) {
var obj = jsyaml.load( text );
console.log( obj );
});
</script>
*This is the updated correct codes
Set the $.get() datatype parameter to be text. jsyaml needs yml type text data to load.

JavaScript array to PHP via AJAX

I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...
But what i get is something like this:
a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...
I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?
The JS code is as follows:
window.onbeforeunload = function() {
var jsonString = JSON.stringify(tabela);
$.ajax({
type: 'POST',
url: 'process.php',
data: {
text1: jsonString
}
});
}
And the PHP side is this:
$text1 = json_decode(stripslashes($_POST['text1']));
$string_data = serialize($text1);
file_put_contents("your-file.txt", $string_data);
The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize.
If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.

JS $.get or $.getScript pass data to file

I want to pass data to the js file. however cant get is to work.
js='article.js';
function loadjs(js){
$.get(js,{ name: "test" });
}
article.js
alert(name);
if i do alert('test'); i get a response from the file so i know it works.
also cant use globals.
is there a simple way to send the data to the file and show it?
EDIT to clarify
(yes i can use angelar but i dont)
Onload it triggers 'pagina' with all short of variables. (its dynamic).
all the 'php/html' files are loaded.
and you get what you can see in the link. example
hoverever when i click on a row i want function pagina(); to load the content of the row so far so good. however to show the data that i want. I want to send a ID to the JS file and use a $.post (php) in the JS file to get data json. if i set a ID in $.post id=1 directly its works.
so to not let it be more confusing. i want to send a id to a js file JS $.get or $.getScript.
function pagina(menu,frame,vars,crum,js,togglezoeken,voorwaarden){
'use strict';
if(!menu){$('#frame').show();}
if(menu){
$('#loader-zoeken').hide();
$('#loader-bijwerken').hide();
$('#loader-pagina').show();
$('#menu').hide();
$('#frame').empty();
$('#menu').load(menu+vars,{noncache: new Date().getTime()}, function() {$('#menu').foundation();});}
if(crum==1){$('#breadcrumbs').load('/opbouw/frames/breadcrumbs.php?'+vars,{noncache: new Date().getTime()}, function() {});}
$('#frame').load(frame+vars+'&crum='+crum,{noncache: new Date().getTime()}, function() {
if(togglezoeken){$('#uitgebreidzoeken').toggle();}
if(crum==1){$('#breadcrumbs').show();}else{$('#breadcrumbs').hide();}
if(js){
$.get( js,{ name: "test" });
}
else{
$('#loader-pagina').hide();
$('#menu').show();
$('#frame').show();
}
//if(voorwaarden==1){popup('/opbouw/frames/voorwaarden.php','','/opbouw/js/voorwaarden.js');}
$('#frame').foundation();
});
}
You can't do it that way. $.get is used for AJAX/HTTP(s) requests and your file in that way won't accept the data sent to it.
To achive this you have to use a server-side endpoint on your article.js.
Lets say:
function loadjs( js ) {
$.get(js, { name: "test" });
}
And you make a call of loadjs function:
loadjs('article.js');
On your server you have to have an server-side endpoint directing to a request: /article.js:
You can achieve this by using PHP or express for node.js:
router.get('article.js', function(req, res, next) {
res.json( req.query.data );
});
Or in PHP (note in Apache you have to use mod_rewrite and enable it with .htaccess or in your virtual host configuration):
$req = $_SERVER['REQUEST_URI'];
if($req == 'article.js') {
echo json_encode(array('data' => $_GET['data']));
exit(0); // end the script here
}
In either way used from above you have effectivelly sent a data to your script / endpoint and you can handle it further.
Although your loadjs function just sends a request and doesn't handle a response, you can do the following with a callback function in $.get:
$.get(js, { name: "test" }, function(data) {
alert(data); // you will alert the data from the JSON response
});
Sadly, you haven't described what you actually need and this is as far as I can help you with so far.

Opening a JSON file from javascript

I have a C# functoin in my MVC application that returns a JSON representation of a csv file. I am trying to catch that in javascript and open the file. Basically I want the browser do its thing and let the user decide if he want to open it, save it or cancel. I am unable to get that popup to ask me to open the file. Below are the functions
C# Function
[HttpPost]
public ActionResult ExportToCsv(string fileContents, string fileName)
{
fileContents = fileContents.Replace("-CARRIAGE-", "\r\n");
return Json(new { url = File(Encoding.UTF8.GetBytes(fileContents), "text/csv", fileName) }); ;
}
This is the javascript where I am making the ajax call to the function
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
$.ajax({
url: "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.csv",
type: 'Post',
success: function (result) {
window.open(result.url);
}
});
});
I know I am missing something. Can someone please help.
EDIT
After reading through all the potential answers and comments, this is what I am trying to achieve. So if my code is all horribly wrong please let me know.
I have a grid and I have an export to excel button. I have a method that converts the data i want into comma delimited text in javascript itself. I need to present this to the user as a downloadable csv file. For this I was creating the File object using the controller method. The previous incarnation was a Get method and I faced limitations due to querystring length restrictions. So I tried converting it to a POST method and it is not working.
This is the previous version of the code that works for smaller amounts of data
Javascript
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
window.location.href = "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.csv";
});
C# Function
[HttpGet]
public ActionResult ExportToCsv(string fileContents, string fileName)
{
fileContents = fileContents.Replace("-CARRIAGE-", "\r\n");
return File(Encoding.UTF8.GetBytes(fileContents), "text/csv", fileName);
}
Hope this now gives you all more context. Basically I needed to convert my GET method to a POST method and use it from Javascript.
If you use ajax, you're expected to handle the result in code. But you can't trigger a file download (directly) that way.
Instead, create a (hidden) form and post it to a (hidden) iframe (by giving the iframe a name and specifying that as the target of the form), making sure that the response specifies the header Content-Disposition: attachment. That will trigger the browser to offer to save the file. Optionally in the header you can suggest a filename for the file by adding ; filename="fname.ext" to the header value. E.g. Content-Disposition: attachment; filename="fname.ext".
The client-side looks something like this:
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
var frame = $('iframe[name="formreceiver"]');
if (!frame.length) {
frame = $('<iframe name="formreceiver"></iframe>').appendTo(document.body).css("display", "none");
}
var form = $("#senderform");
if (!form.length) {
form = $('<form id="senderform"></form>').appendTo(document.body);
}
form = form[0]; // Raw DOM element rather than jQuery wrapper
form.target = "formreceiver";
form.action = "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.csv";
form.method = "POST";
form.submit();
});
The server side is just a standard form response with the Content-Disposition header.
I've used this technique for years, with browsers from IE6 onward. My usual setup already has the iframe in the markup (rather than creating it as above), but other than that this is basically what I do.
Note that it's important you're doing this in response to a button click by the user. If you weren't, there would be popup-blocker issues.
You can't save binary files using ajax - it's restricted due to security reasons. If you'd like the user to save the file - return a binary stream from your controller as you post the data back in JSON format (ie if the user wants to save it).
I've done a similar thing here: How to properly create and download a dynamically generated binary *.xlsx file on .net MVC4?
Maybe save it as a json file instead and load in the current page's DOM. Although I though I am confused, don't you just have a JSON response containing a URL to your CSV file is which is just that a CSV file, not a JSON representation of CSV?
$("#btnExport").click(function (event) {
event.preventDefault();
var csv = table2csv(noteTypeTable, "full", "Table.dataTable", "noteTypes");
$.ajax({
url: "/Admin/Admin/ExportToCsv/?fileContents=" + csv + "&fileName=NoteTypes.json",
type: 'Post',
success: function (result) {
var myDummyElement = $('<div>'); //dummy div so you can call load
myDummyElement .load('result.url #myJson');
}
});
});
<div id="myJson"></div>
[HttpPost]
public ActionResult ExportToCsv(string fileContents, string fileName)
{
//change fileName to be a .json extension
fileContents = fileContents.Replace("-CARRIAGE-", "\r\n");
return Json(new { url = File(Encoding.UTF8.GetBytes(fileContents), "text/csv", fileName) }); ;
}

write a javascript var="some text" into a pre loaded but empty txt document

I'm creating a dynamic playlist for a music player I've put together. The playlist is going to sit in an external .txt document. I'll use an example. I have a variable:
playlist="track_1"
on the page is a button
<button onclick="add_track()">
in the script in the head
function add_track()
{
playlist=playlist+" track_2"
...What I need here is some way to put the playlist variable into a txt doc
}
The buttons will be generated by php to include the name of the track to add to the playlist variable string. Document.write is perfect for this function as it replaces everything with the content of the variable; unfortunately it replaces the document the button is in not an specified external file.
Well you could create a JSON object in a file and save it as file1.json
{ "playlist" : "track1" }
and the use
$.getJSON("file1.json", function(data){
var playlist=data.playlist+" track_2"
});
of course this works only when you read it, to write to the .json file you should use PHP or whatever you use server side
You cannot write anything on a file with javascript. You'll need a server side solution.
Eg: You could have an ajax call to a php script that writes something in a txt file
You need to use PHP to write/append into files. You can use jQuery.ajax() function to call a PHP script to write/append into file:
jQuery('#buttonId').live('click',function(event) {
$.ajax({
url: 'write-file.php',
type: 'POST',
dataType: 'json',
data: {
playlist: "track_1"
},
success: function( data ) {
for(var id in data) {
alert( data[id] );
}
}
});
return false;
});
write-file.php (something like this)
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
fwrite($fh, $_POST['playlist']);
fclose($fh);
// echo status here in json format
If you want write the playlist on the client side you can use the html5 filesystem api.
http://www.html5rocks.com/en/tutorials/file/filesystem/
Depending on what you actually want to do, you could open a new browser window with a data URI, containing your text:
window.open('data:,' + encodeURIComponent(playlist));
The user only has to save the document then. The size of playlist ist limited by the allowed URI length though.
Here is an example: http://jsfiddle.net/UjzsG/
Thanks for all the help, first time I've asked a stupid question and got a really good answer. Turns out I'm a bit thick, don't need the PHP now but I will later when I want to save a playlist. Realised to make a dynamic playlist I can keep the array it lives in as a string in a variable, add tracks to the string then call eval(playlist) in each function that reads the list.
var playlist = 'var tracks = new Array("track_00","track_01"';
var end_bit = ');';
var playlist_full = playlist+end_bit;
Then to add stuff
function AddTrack()
{
playlist=playlist+'"track_02"';
}
And to read it
function ReadTrack()
{
playlist_full = playlist+end_bit;
eval(playlist_full)
document.getElementById("current_track").innerHTML=tracks[2];
}
Again cheers for all the advice.

Categories

Resources