Javascript/Jquery to Download File via Post with JSON Data

Handle file download from ajax post

Create a form, use the POST method, submit the form - there's no need for an iframe. When the server page responds to the request, write a response header for the mime type of the file, and it will present a download dialog - I've done this a number of times.

You want content-type of application/download - just search for how to provide a download for whatever language you're using.

Uable to send POST data to JSON file via JQuery/AJAX, Why?

Client side scripting languages are used to send and retrieve data which resides on server side. We can't use them to write/edit data on server side.

For doing so, we have to use server side scripting languages like PHP or ASP or any other which you prefer.

The video you referred was an API written in Core PHP used for retrieving / writing data from / to a json file which resides on server.

In my below code i have used PHP to write submitted data to a json file via jQuery/AJAX.

Check this out..

api/process.php

if (isset($_POST['params'])) {
$params = $_POST['params'];

$oldData = file_get_contents('orders.json');
$tmp = json_decode($oldData);
array_push($tmp, $params);
$newData = json_encode($tmp);

if (is_writable('orders.json')) {
file_put_contents('orders.json', $newData);
echo $newData;
} else {
echo "file is not writable, check permissions";
}
}

index.html

<h1>Jquery  Ajax Tutorial</h1>

<h3>Coffie Orders</h3>

<ul id="orders"></ul>

<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink:  <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
<script src='js/jquery.min.js'></script>
<script src='js/main.js'></script>

js/main.js

let $orders = $('#orders');
let $name = $('#name');
let $drink = $('#drink');

function addOrder(order) {
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}

$('#add-order').click(function(){
let order = {
name: $name.val(),
drink: $drink.val()
};

$.ajax({
type: 'POST',
url: '/api/process.php',
data: { params: order },
success: function(resp) {
addOrder(resp);
},
error: function(){
alert('Error Adding Orders');
}
});
});

$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});

api/orders.json

[
{
"id": 1,
"name": "James",
"drink": "Coffiee"
},
{
"id": 2,
"name": "John",
"drink": "Latte"
}
]

Note: Here, i am not writing id to json file for new orders.

Hope, this piece of code works fine for you. :) :)

Create and download PDF based on JSON sent by AJAX POST request

setting responseType to blob does the trick , add xhrFields: {responseType: "blob"} to your existing code,

          $.ajax({
type: "POST",
url: "<SERVLET_PATH>",
contentType: "application/json",
cache: false,
data: that.parsedEstimator,
xhrFields: {responseType: "blob"},
success: function (data) {
a = document.createElement('a');
var binaryData = [];
binaryData.push(data);
a.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
a.download = "Estimation.pdf";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
});

How do I get JSON data from an external file in jQuery and ensure the data is loaded before the remainder of the script

see documentation on getJson

if you want it should run and other section should wait, you can set 'asysn' : false
but it is not a good idea, since the code after the ajax will wait until it completes.

OR

// check the meaning of done, fail, always
$.getJSON( "url", function() {

}).done(function(){

// your rest of the code

});

or you may try custom trigger event

$(function(){

$.getJSON( "url", function() {

}).done(function(){
$( document ).trigger( "jsonSuccess", [ "bim", "baz" ] );
});

$( document ).on( "jsonSuccess",function(event, var1, var2){
// will execute after the 'getJSON' success
});

// other codes can be execute from here, it will not wait

});

Jquery Ajax asks to download JSON file instead of going into success block

Looks like the below code was the issue. Will need to investigate more as to why -

@using (Html.BeginForm("UploadExcel", "UploadData", FormMethod.Post, new { enctype = "multipart/form-data" }))

I simply replaced it with a regular html form and then added below code to get post the file object in the javascript -

var $file = document.getElementById('inputGroupFile02'),
$formData = new FormData();

if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
$formData.append('file-' + i, $file.files[i]);
}
}

and added the following inside the ajax call -

                data: $formData,
dataType: 'json',
contentType: false,
processData: false,

At the controller, got the file object using

                if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
var _file = Request.Files[file];
}
}

I think there was probably some conflict with the FormMethod.Post and ajax post. I could be wrong. Feel free to correct this and add to what could be the issue.



Related Topics



Leave a reply



Submit