jQuery delivery of a file with AJAX call - c#

If I have an AJAX call that returns, say, a CSV, how do I get the browser to prompt the user for a download? Below, the ProductsExport will return the CSV in the success data. I just need what I'd replace the // Deliver file to user line with...
$.ajax({
type: "POST",
url: "/Search/ProductsExport",
data: $('#CustomerId').serialize(),
success: function (data) {
// Deliver file to user!!
},
error: function (xhr, textstatus, errorThrown) {
alert('Error');
}
})
My C# code on the back end looks like so:
var aFileContent = Encoding.ASCII.GetBytes(export);
var aMemoryStream = new MemoryStream(aFileContent);
return File(aMemoryStream, "text/plain",
string.Format("{0}.csv", CustomerId));

You cannot as far as I'm aware. You can't use ajax here as a file download.
YEs - its a support datatype as per jQuery but not for a file. You need to link to the file for a non ajax request either via a link or a jQuery get request.
See:
Unable to open download save dialog
and
"datatype" on
http://api.jquery.com/jQuery.ajax/

Alternative solution to your problem is have an AJAX function return an actual URL that will download csv (similar to your C# backendcode). The client side will then launch the URL using window.open(url)

Why does it have to be ajax? Just build your url and do a window.location.href to execute your call. All you seem to be passing it is a customerId, so that should be pretty easy.
Ajax operations are meant to allow a user to stay on the page while operations continue behind the scenes. A file download will keep the user on the page and just download the file, so there's no benefit to using ajax in this siutation. Something like this perhaps:
window.location.href = "/Search/ProductsExport?" + $.param($('CustomerId'))

Related

POST method to send RAW TEXT data and get HTML Response using Jquery AJAX Web Method and check with POSTMAN

I'm Trying to do a POST Request using RAW TEXT.
I want to send POST Request from POSTMAN like, in body Section I've selected RAW(from radio buttons) and Text(from drop-down) and pass below simple string.
01JAINAM120112356598
Now, when we click on send in Postman, Response must come in HTML string "01" on success and "00" on error.
[Type of Request & Response I Need] https://imgur.com/bC26Pw7 (In photo URL is of .php page, but I'll pass my asp.net c# page (.aspx)).
I need to use JQuery ajax code to pass request & get proper response.
Something like,
$.ajax({
url: "RFID.aspx/saveRFIDData",
type: "POST",
dataType: "text",
success: function () {
},
error: function (response) {
alert("Error")
}
});
But, when I call above URL as post method as same shown in Image above, my WebMethod in code behind is not called.
Instead, when I call same ajax call for JSON, my WebMethod is been called.
But, I don't want to pass JSON.
So, Can anyone help me to get it done with "dataType : text" & get HTML string response.
Note : If someone didn't Understand my question. Do comment first, to be more clear rather than DEVOTE this question
It seems to be "Unsupported Media Type" issue and status may be 415. Add supported media type, that might work.

Ajax error - errorThrown in ASP.NET MVC application

I am writing an asp.net MVC application that will compliment another application that I have written. In my old application, I send errors from the controller to the client like so:
return new HttpStatusCodeResult(400, "Whatever went wrong.")
Then, on my client side the ajax error looks a little like this:
error: function (jqXHR, textStatus, errorThrown) {
redAlert(errorThrown);
}
This all works perfectly. Whatever message I put in on the controller side will pop up on the client side.
Now, I have tried to do the same thing with this new application. However, errorThrown has nothing in it every time.
I have no idea where to start looking so any help or guidance will be much appreciated.
Thanks!
EDIT 1
After talking through some stuff with Shyju, it seems that HttpStatusCodeResult is not sending the message back in the header in the new application. Still trying to work this out.
Edit 2
After some testing, I have found that the Custom Error message doesn't get sent through using SSL. Why would this be an issue and how can I solve this? I need to use SSL as the application requires Work Account Authentication.
When your server code returns a 400 bad request response from your web api controller, the message text you are sending will be in the response from the server as
{"Message":"Whatever went wrong."}
Now the $.ajax will use this response and create a js object from that and set it to the responseJSON property of the jqXHR object. So you may simply access that.
$.ajax({
url: 'yourApiEndpoint'
}).done(function (data) {
console.log(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
if (jqXHR.responseJSON) {
alert(jqXHR.responseJSON.Message);
}
});
When you return HttpStatusCodeResult from an MVC controller action method, IIS will return the markup for the 400 page. So the response is basically the HTML markup. The response headers will have the status code and the message and the $.ajax method will set the status message you send from server to the statusText property of the xhr object.
.fail(function (jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText) {
alert(jqXHR.statusText);
}
});

Handling the data portion of a jQuery AJAX call to WCF REST service

Fairly new to jQuery, I have a .ajax call going to a WCF RESTful service and my Uri template on the operation contract is the following:
UriTemplate = "/{appName}/{custCode}/{custUserName}/counter"
My problem is, I have a what is either going to be XML or JSON that I want to save to a database via the service and I'm confused how to get the service to receive the payload without having it as a variable in the Url.
My AJAX call looks like this so far:
$.ajax({
type: "POST",
url: ‘{../{appName}/{custCode}/{custUserName}/counter}’
});
Any help would be appreciated.
If I'm reading your question correctly, I think that you're asking how to send data to that server via ajax.
What you need to do is specify what the data is and add it to the 'data' setting in your ajax request.
So
var myData = "whatever your data is";
$.ajax({
type="POST",
url: ‘{../{appName}/{custCode}/{custUserName}/counter}’,
data: myData
})
You can also specify what to do with the response you get, perhaps letting the user know his/her data was saved or some such.
http://api.jquery.com/jQuery.ajax/ is the list of all settings.

Progress Bar while sending ByteArray to Server through Action Method in MVC 3

I have a byte-array that i upload to the server through action method from javascript (MVC3):
$.ajax({
url: '#Url.Action("Upload")',
type: 'POST',
contentType: 'application/x-amf',
processData: false,
data: ByteArrayData,
success: function (result) {
alert(result);
}
});
I was wondering what is the easiest way to make a percentage progress bar while the bytes are getting sent to the server?
Easiest way would be to Mask the content using javascript or show Javascript progress bar on view, until you get the response back from Server.
My initial (and boring) response is that this would be hard to do, but I'm not wise enough with the HTTP post request to completely be sure if it is or isn't possible. Essentially though you'd have to either know:
Size of posted data
Upload speed
OR
Size of posted data
Data sent each interval (if such a thing even exists?)
I'm not sure you can access either of these combinations with JavaScript. You'd probably need to use some sort of flash uploader for this.

Return tabledata as file with jquery and c# mvc

I would like to use jquery to send Table-data to the server and then get a data.csv file to download
if i navigate to the url in my browser like this:
http://localhost:49400/File/Csv/?Text=qweerty&Filename=asdf
i get promted with a file to download.
This is the action im calling:
public FileResult Csv(FileModel fileModel)
{
return File(Encoding.UTF8.GetBytes(fileModel.Text), "text/plain", string.Concat(fileModel.Filename, ".csv"));
}
and my javascript looks like this:
$("table").click(function () {
$.ajax({
type: "POST",
url: "http://localhost:49400/File/Csv/",
data: {"Text": "qwerty", "Filename": "asdf"}
})
});
The response in firebug is containing the data, but i would like it to ask the user if it wants to download it, is this possible?
You cannot use AJAX to download a file.
Instead, you can just set location to a URL pointing to the file.
As long as the server returns a downloadable file (with a Content-Disposition header), the browser will show a Save dialog and will not replace the page.
If you want to download the file from a POST, you could make a hidden <form> that sends the POST, then submit() the form using Javascript.
you can't deliver file content through ajax call, perhaps find a way to construct URL with your table data as query string and stream the file that way or post-back the whole page and response as a stream

Categories

Resources