I went through dozen of pages with question "How to download file from jQuery", but still didn't find the simple solution.
I have my jQuery with ajax inside:
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
var DownloadableFile = data.message;
//HERE I NEED TO DOWNLOAD FILE
alert("Success! You will be redirect to the Home Page.");
var url = '#Url.Action("Index", "Home")';
window.location.href = url;
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
Here in data.message I'm getting back from Action SaveQBMatter FULL FILE PATH
What I need is simply let to my user download this file before redirecting. Any help please?
Note: I'm using ASP.NET MVC, if this information is needed
Try to use this plugin for downloading the file:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
You can do something like this, upon a successful ajax call, do location.href = data.message; which as you said data.message is the full path to the file. With that, it should download the file without redirecting the browser. Also when you download the file, make sure you have the header force-download.
You can see more about forcing a download here:
http://www.symkat.com/force-download-with-http-headers
Then, do a setTimeout of lets say 1 to 2 seconds, you can tweak the timings to how you like it, to let the download initialize and redirect. So your code would look like this:
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
var DownloadableFile = data.message;
location.href = DownloadableFile;
setTimeout(function() {
alert("Success! You will be redirect to the Home Page.");
var url = '#Url.Action("Index", "Home")';
window.location.href = url;
}, 1000);
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
Try opening the URL in a new window, if not blocked by the users browser:
if (data.status == "Success") {
window.open(data.message, "_blank")
If you have problems with the file opening instead of downloading, you can try sending a content disposition header from ASP like:
Content-Disposition: attachment; filename="filename.extension"
Related
When the users try to exit the page, I want to load a new script into my page.
The script successfully gets adding to the page, but it simply doesn't work properly. Now, if I just put the script into my page from the get-go, not using ajax, it does work. To me, this makes absolutely no sense, but something in my method/jQuery is clearly screwing the script up.
Lines from the JS file which Ajax doesn't seem to like:
document.write('<div id="' + token + '"></div>');
that.div.style.position = 'relative';
Error includes
Uncaught TypeError: Cannot read property 'style' of null
I'm assuming it's related to the script not being loaded onload? :S
This is my code
My Web Method.
[WebMethod]
public string webcamLink(string cat)
{
string script = "<script src=\"thescipt.js\"></script>";
return script;
}
This is my jQuery.
setTimeout(() => {
$(document).on("mouseout", evt => {
if (evt.toElement === null && evt.relatedTarget === null) {
$(evt.currentTarget).off("mouseout");
// An intent to exit has happened
$("#myNav").css("display", "block");
var cat = "cat";
var t = JSON.stringify({
'cat': cat
});
$.ajax({
type: "POST",
url: '/webServices/pop-up.asmx/webcamLink',
data: t,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 15000,
async: true
});
}
});
}, 5000);
function OnSuccess(data) {
$('#cams').html(data.d);
};
And my HTML:
<div id="cams" class="container-fluid"></div>
Does anybody have any idea what I'm doing wrong? I apologise if I'm being silly, quite new to this.
var url = '#Url.Action("UploadFilesToDropBox", "Home")';
$.ajax({
type: "POST",
url: url,
data: postData,
success: function (result) {
if (result == "Success")
{
AfterCreationOfFiles(selected,SelectedFormat);
}
}, dataType: "json",
traditional: true
});
I am using above function to call an ActionResult, On localhost my function runs smoothly. But when i runs it on Server, it gives me the following Error:
The resource cannot be found.
i accidentally added WebApi, May be that is causing the Error?
I want to call an ASP.NET function from jQuery by AJAX with response.
I have file Controll.aspx where is included javascript code. Next I have /Services/ControllService.asmx, where is the function, which I want call from js.
js code:
$(document).ready(function () {
$('#btn_start').on('click', function () {
$.ajax({
type: "POST",
url: "Services/ControllService.asmx/Start",
data: {},
dataType: "json",
async: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (err) {
alert("Error:" + err.toString());
}
});
});
});
But I still getting the error 500.
POST http://localhost:56000/Services/ControllService.asmx/Start 500 (Internal Server Error)
k.cors.a.crossDomain.send
n.extend.ajax
Do you have any hints, what do I need to set e.g. in Web.config?
Many thanks.
SOLVED:
1 - I have defined Start function in ControllService.asmx.cs as static.
2 - I have badly configured data. It has to be named by the same way e.g. "sth".
In javascript it should be:
...
url: "Services/ControllService.asmx/Start",
data: JSON.stringify({ sth: "hahaha" }),
dataType: "json",
...
and in ControllService.asmx.cs -> method Start
public string Start(string sth){}
Many, many thanks for your hints.
I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.
I have some javascript that requires a specific URL to call an ASP.NET web service.
When I run the application locally, the url is something like: http://localhost:123456/ProjectName/Default.aspx
But when I upload the application, the domain will change to:
http://myDomain.com/Default.aspx
What's the best way to capture the current URL path and pass it in as a variable to my javascript? Here is my javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#autoComplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:123456/ProjectName/Default.asmx/SkillsList", //CHANGE THE URL!!
//url: "http://myDomain.com/Default.asmx", //The other URL...
data: "{'like':'" + request.term + "'}",
datatype: "json",
async: true,
success: function(data) {
response(data.d);
},
error: function(result) {
alert("error");
}
});
},
minLength: 2
});
});
</script>
I'm using ASP.NET if that helps at all.
Thanks!
post to relative path
url: "/ProjectName/Default.asmx/SkillsList"
Looks like you're writing out to the aspx page. Given that, you should be able to just have ASP.Net tell you via something like
url: "<%= Request.ApplicationPath%>/Default.asmx/SkillsList"