I have created a webmethod and the method just send a Excel file as webresponse.When i run only the webmethod it works fine as want
My webmethod is following:
public void Export_ex(string elem)
{
string elements = elem;
HttpContext.Current.Response.ContentType = "data:application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Print.xls");
HttpContext.Current.Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
HttpContext.Current.Response.Write("<head>");
HttpContext.Current.Response.Write("<div>");
HttpContext.Current.Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf- 8\">");
HttpContext.Current.Response.Write("<!--[if gte mso 9]><xml>");
HttpContext.Current.Response.Write("<x:ExcelWorkbook>");
HttpContext.Current.Response.Write("<x:ExcelWorksheets>");
HttpContext.Current.Response.Write("<x:ExcelWorksheet>");
HttpContext.Current.Response.Write("<x:Name>Report Data</x:Name>");
HttpContext.Current.Response.Write("<x:WorksheetOptions>");
HttpContext.Current.Response.Write("<x:ValidPrinterInfo/>");
HttpContext.Current.Response.Write("</x:Print>");
HttpContext.Current.Response.Write("</x:WorksheetOptions>");
HttpContext.Current.Response.Write("</x:ExcelWorksheet>");
HttpContext.Current.Response.Write("</x:ExcelWorksheets>");
HttpContext.Current.Response.Write("</x:ExcelWorkbook>");
HttpContext.Current.Response.Write("</xml>");
HttpContext.Current.Response.Write("<![endif]--> ");
HttpContext.Current.Response.Write("</head>");
HttpContext.Current.Response.Write(elements);
HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
}
but when i call it from javascript function by ajax calling nothing happened. My ajax method is following :
var str = "something"
var data = { elem: str };
$.ajax({
type: 'POST',
url: "ImageSaving.asmx/Export_ex",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
mimeType: 'application/vnd.ms-excel',
success: function (response) {
var show = response.d;
},
failure: function (msg) {
alert("Error occur, could not load the service.");
}
});
I could not understand where i am getting wrong?? Any suggestion regarding this?
For security reasons, you cannot download file from client side. I advice to use a hidden button server side and simulate the click from another button client side.
Regards.
Related
I'm streaming a dynamically generated PDF from the server to the frontend. The PDF will display with no issues in Chrome, but generates this error in IE11.
DOCTYPE expected. Consider adding a valid HTML5 doctype: "!DOCTYPE
html"
The PDF is dynamically generated and returns a GUID on success which is then used in the AJAX success to open a link to the new PDF.
On the front end:
$.ajax({
url: "myURL",
method: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: The data used to create the PDF on the server,
success: function (result) {
window.location.href = "newURL?fileIdentifier=" + result;
},
error: function (error) {
console.log(error)
}
On the code behind:
var pdfFilePath = string.Format("{0}\\{1}.pdf", tempWorkPlanDirectory, fileIdentifier);
var fileBytes = File.ReadAllBytes(pdfFilePath);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "inline; filename=\"" + fileName + ".pdf\"");
Response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
First of all, I have already read this answer, which is to do the Cross-Domain Ajax GET request with php proxy. But what I need is a Ajax POST request.
So in my project, long time ago. Someone wrote this php file and together the ajax call in JavaScript, those are mean to solve the cross origin problem and which works really good! So I never think about to understand this, because I basiclly just need to change the url in the JavaScript and don't need to understand how this Ajax call works together with php.
PHP:
<?php
$nix="";
$type=$_GET['requrl'];
if ($_GET['requrl'] != $nix) {
$file = file_get_contents($_GET['requrl']);
}
elseif ($_POST['requrl'] != $nix) {
$file = file_get_contents($_POST['requrl'], false, $_POST['data']);
}
else {
$file = "false type";
}
echo $file;
?>
JavaScript:
var url = "https://XXXXXXXXXXXXXX";
url = encodeURI(url);
var useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
var ajaxProperties = {
type: 'GET',
data: data,
url: ajaxUrl,
cache: false
};
res = jQuery.ajax(ajaxProperties).done(function(res) {
// do something with the result here
})
So what I need to do is just take the same ajax GET request (copy and paste in JS) and just replace the url every time ==> job done!
Now, the first time I need to do a ajax POST request to send a xml file to the server, the server will do some calculate on it and give me a response.
I tested first with the POSTMAN and everything works fine, but when I switch to my real project. I become the Cross origin problem. So I think If I could do something to the already existing php and js, so I can solve the cross origin problem.
I tried this in my JavaScript but I got only the "false type" as antwort
function sendWPSRequest(xml) {
var url = "https://XXX.XXX.XXX.XXX:XXXX/wps";
useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url, data: xml} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "text",
contentType: "application/xml",
data: data,
success:function (response) {
console.log('POST success: ', response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("POST", textStatus, errorThrown);
}
});
}
Can someone help me a little bit to understand what the php is doing here and what should I do to modify the php and JS.
I have a simple bootstrap page with a button and when the button is clicked the modal opens up.
the question is the modal content or the modal body should be filled with wcf data, both the webpage and the wcf json data will be hosted in IIS can anyone please help me how to achieve this?
Thanks in advanceenter image description here
What you need to do is to make a ajax call in jquery that will call the WCF method. Below is how you call the service.
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
function WCFJSON() {
var userid = "1";
Type = "POST";
Url = "Service.svc/GetUser";
Data = '{"Id": "' + userid + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; varProcessData = true;
CallService();
}
// Function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceSucceeded(result) {
if (DataType == "json") {
$("#ModalBody").html(result)
}
I have a simple web api controller which I can navigate to through the url and it will download the .csv file. Now I am trying to write some jQuery where if you click the button it will download it but I am missing something.
public HttpStatusCode Get(string id)
{
var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id);
var response = HttpContext.Current.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv");
response.Write(reportString);
return HttpStatusCode.OK;
}
This code definitely works and I can go to the URL to prompt the download.
$('.js-btn-download-content').click(function (event) {
var currentLanguage = getCulture();
var url = baseUrl + 'report/get/' + currentLanguage;
event.preventDefault();
$('.loadingContent-download').fadeIn(200);
$.ajax({
headers: {
Accept : "text/csv; charset=utf-8",
"Content-Type": "text/csv; charset=utf-8"
},
url: url,
dataType: "text/csv",
success: function (data) {
$('.loadingContent-download').fadeOut(200);
// Not sure about code below
//var xmlDoc = $.parseXML(data);
//var $xml = $(xmlDoc);
//var $title = $xml.find("200");
//if ($title) {
//$('.contentDownloaded-download p').html('Content donwloaded!');
//$('.contentDownloaded-download').show();
//} else {
//$('.contentDownloaded-download p').html('Download failed! Please try again.');
//$('.contentDownloaded-download').show();
//
}
});
$('.js-btn-confirm').click(function () {
$('.contentDownloaded-download').fadeOut(200);
});
});
As you can see, here is some javaScript that I've been using in the app to handle an OK being returned. However the browser won't download the file when this script fires. Any ideas?
In your Get(string id) method, return the HttpResponseMessage instead of just the HttpStatusCode. Also, ASP.net Web API does not ensure the state of HttpContext.Current.Response (without some wizardry code). You can do something like, change the signature to Get(HttpRequestMessage request, string id) and then call request.CreateResponse(statusCode, data).
I am trying to build a marquee that reads from a remote rss feed. The ajax request was failing due to what I can only assume are cross domain restrictions. Here is my code:
$(function () {
$.ajax({
url: 'http://www.theleafchronicle.com/section/news01&template=rss_weblogs&mime=xml',
dataType: 'xml',
type: 'GET',
success: function (xml) {
$(xml).each(function () {
var title = $(this).find("title").text();
var des = $(this).find("description").text() + ' - ';
var wrapper = "<span class='single-feed'></span>";
$(".feed-container").append($(wrapper).html(des));
});
},
error: function (err) { }
});
});
This code failed, so I instead tried downloading the xml locally and it worked. My only concern now is how can I download this code via batch file or possibly a .net executable? I have tried the System.Net.WebClient.DownloadFile method and it brings back a page instead of the intended xml.
class Program
{
static void Main(string[] args)
{
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadFile("http://www.theleafchronicle.com/section/", "theleafchronicle.xml");
}
}
You can use wc.DownloadString(url) or wc.DownloadData(url) depending how you prefer the response.