I want to upload a image with a description like:
data = '{"filename":"' + myfilename + '", "file":"' + file + '", "description":"' +
description + '"}';
$.ajax({
type: "POST",
url: "filehandler.ashx",
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading file!");
}
});
how can I do it? I can't read file as HttpPostedFile in generic handler.
context.Request.Form also doesn't have any keys.
I'm sorry, If I not posted fully what I did in question. Anyway I got it to work.
var data = new FormData();
data.append("name", filename);
data.append("file", file);
In generic handler
HttpPostedFile file = context.Request.Files["file"];
string fileName = context.Request.Form["filename"];
Using FormData Objects
you cant post files with ajax you have to post it in a iframe to have the same result
this is what I did
var form = "#myform";
var url = "http://post.it/";
var iframeName = 'iframePost' + (new Date()).getTime();
$('<iframe id="'+iframeName+'" name="' + iframeName + '" style="display:none;"/>').appendTo('body');
$(form).attr('target',iframeName)
.attr('action',url)
.attr('enctype','multipart/form-data')
.append('<input type="hidden" name="_iframe" value="' + iframeName + '" />');
form.submit();
to have a callback let the iframe return a script with something like
window.parent.callBack(data);
Related
Fiddled with every imaginable combination of webapi controller and jquery ajax script which, when debugging, does make a get call to the controller, but it won't parse the data (in debug, the data is there!). PostMan and typing URL into browser works perfectly, so I believe there is (yet another) trick to get jquery.ajax to work.
the WebAPI controller method (which works):
namespace SearchWebsite.Controllers
{
public class MoreInfoController : ApiController
{
private string DBConnStr;
public MoreInfoController()
{
DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem_Data.DBConnStr = DBConnStr;
}
[Route("api/getmoreinfo/{lid}")]
[HttpGet]
public async Task<IHttpActionResult> GetMoreInfo(string lid)
{
var retval = new AppCore.MoreInfo();
if (lid.Length == 36)
{
if (IsGUID(lid))
{
retval = await LiveItem_Data.GetMoreInfoAsync(lid);
}
}
return Ok(retval);
}
}
}
And I get the expected results when I call it via postman or the browser, like so:
https://localhost:44371/api/getmoreinfo/2A116FF3-E6C8-4EE3-88E5-99001DCCE36A
The jquery ajax method:
$(".popInfo").bind("click", function (e) {
var ListID = $(this).parent().parent().find('[id*=hidlid]').val();
$.ajax({
type: "get",
url: "../../api/GetMoreInfo/" + ListID,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
try {
var mi = jQuery.parseJSON(data);
var img = "";
if (mi.IMGLNK != "") { img = "<img src='" + mi.IMGLNK + "' class='img-responsive' />"; }
var title = "<a href='redir?lid=" + ListID + "' target='_blank' >" + mi.NAME + "</a>";
var btnV = "<a href='redir?lid=" + ListID + "' target='_blank' class='btn btn-success' ><span class='glyphicon glyphicon-shopping-cart'></span> Visit Website</a>";
var btnR = '</span> Report Problem';
var details = "<p><p>SKU: " + mi.SKU + "</p><p>MPN: " + mi.MPN + "</p><p>UPC: " + mi.UPC + "</p><p>Ship Weight: " + mi.WT + " lbs</p><p>Last Updated: " + formatJSONDate(mi.MD) + "</p></p>"
$('#moreinfo').find('.modal-title').html(title);
$('#moreinfo').find('.modal-body').html(img + '<p class="descr">' + mi.DESC + '</p>' + details);
$('#moreinfo').find('#btnVisit').html(btnV);
$('#moreinfo').find('#btnReport').html(btnR);
$('#moreinfo').off().modal('show');
} catch (e) {
alert("ERROR:" + e + " data: " + data + " mi: " + mi);
}
},
error: function (err) {
alert("error: " + err);
}
});
});
the try catch and alerts are for troubleshooting, however even though the data is in the data variable while stepping through and debugging, the "data" becomes undefined immediately after using parseJSON(), and, naturally, the variable "mi" is undefined as well and the error I trapped is "SyntaxError: Unexpected token u in JSON at position 0 data: [object Object]".
I'm at a loss as how to remedy this issue. (note: I am in the process of converting old ASMX services into MVC5 WebAPI 2.1 services, so DotNetCore answers won't work as it's a completely different beast, as is MVC4 and below)
The table rows are generated at page load using ajax as shown below.
$.ajax({
url: '/consultation/GetPrescHistoryList',
type: 'POST',
data: $('#frmPrescHistoryTable').serialize(), // it will serialize the form data
//dataType: 'json',
success: function (data) {
var rowNo = 0;
for (var i = 0; i < data.length; i++) {
rowNo += 1;
$("#LoadPrescHistoryTable tbody").append("<tr Class='odd gradeX'>" +
"<td>" + rowNo + "</td>" +
"<td>" + data[i].description + "</td>" +
"<td>" + data[i].UserName + "</td>" +
"<td><button type='button' class='repeat btn btn-default' data-id='" + data[i].dgid + "'>Repeat</button></td>" +
"</tr>");
}
alert('LoadPrescHistoryTable has been loaded.');
},
error: function () {
alert('Ajax Submit Failed ...');
}
}); // end ajax
var baseUrl = '#Url.Action("GetPrescDetailsObj", "consultation")';
$("#LoadPrescHistoryTable tbody").on('click', '.repeat', function () {
location.href = baseUrl + '?dgid=' + $(this).data('id');
});
I wanted so that when i click on repeat button in the table row, the details from the chosen id will display in a label and textbox in the same page. How can i replace the location.href in order to not redirect the data, but to simply show the data that was called to the textbox and label?
$('#btnPrescRepeat').on('click', function (e) {
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: '/consultation/GetPrescDetailsObj',
type: 'POST',
data: $('#frmBtnPrescRepeat').serialize(), // it will serialize the form data
dataType: 'json',
success: function (data) {
$('#PHOtherInstruction').val(data.remarks);
$('#tradename').val(data.tradename);
},
error: function () {
alert("something seems wrong");
}
}); // ajax
}); // #btnPrescRepeat
Below is the controller which is used to pass the objects back to the view, one in textbox and another in label.
public ActionResult GetPrescDetailsObj(string dgid)
{
PrescriptionVM Prescription = new PrescriptionVM();
PatientLookupVM Patient = new PatientLookupVM(Prescription);
Patient.LoadDrugObj = Prescription.GetDrugObj(dgid);
dynamic data = new
{
tradename = Patient.LoadDrugObj.tradename,
remarks = Patient.LoadDrugObj.remarks
};
return Json(data, JsonRequestBehavior.AllowGet);
}
When i click the repeat button, the page is replaced with an array of data that i called. Can anyone please tell me what am i doing wrong?
I am using jquery Ajax for downloading PDF file, I generate PDF on runtime and download it,
This is my Ajax call
$.ajax({
async: "false",
type: "POST",
url: "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date),
success: function (result) {
}
});
and this is what I am doing in ActionResult
public FileContentResult DownloadFile(int userId, string date, int rptType)
{
var userInfo = UserBLL.GetUserByID(associateId).Name;
var dtFileDate = Convert.ToDateTime(date);
var pdfStream = GeneratePDFStream(userId, date);//Generating Stream
if(date < DateTime.Now)
{
return File(pdfStream, "application/pdf", string.Format("MyReport{0}{1}.pdf", userInfo.Name, dtFileDate.ToShortDateString().Replace("/", "")));
}
return null;
}
but its returning
Sorry, an error occurred while processing your request.
How can I download the file with Ajax call? Please note that I can't use jquery FileDownload but I can do without Ajax call, Kindly suggest
I also tried with this,but same error
var url = "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date);
window.open(url);
Instead of ajax call, just try using Iframe as(demo code) :
var url = "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date) ;
var $dialog = $('<div></div>')
.html('<iframe style="border: 0px; " src="' + url + '" width="850px" height="100%" scrolling="no"></iframe>')
.dialog({
autoOpen: false,
modal: true,
height: 625,
width: 850,
title: 'YourPdfFile'
});
$dialog.dialog('open');
Hi friends i have a form in which there are some text boxes, drop downs and as well as image . I am using knock out js to save the form details. And i am using uploadify plugin to upload my image to a local folder .I have implemented all this things but when it comes to saving the values till now i used a aspx code behind . For uploading purpose we had to choose ashx. So it will be like two server side postings going to happen!!
So i would like to save my data in ashx page rather than aspx.
But i am confused where exactly to start my upload..please some one help me with this!!!
i am saving my values in a save button event like below!!
self.AddEvent = function (args) {
// Here--> $('#file_upload').uploadify('upload');
ajax.Post("../Scripts/uploadify/UploadHandler.ashx", JSON.stringify({ objEnt: args }), false).success(function (data) {
if (data.d[0] > 0) {
// or Here--> $('#file_upload').uploadify('upload');
alert('success');
}
and my fileupload setting s are:
$('#file_upload').uploadify({
'swf': '../Scripts/uploadify/uploadify.swf',
'uploader': '../Scripts/uploadify/UploadHandler.ashx',
'method': 'post',
'formData': { 'someKey': Filename },
'buttonText': 'Browse',
'auto': false,
'folder': 'upload',
'fileTypeExts': '*.jpg;*.jpeg;*.gif;*.png',
'onSelect': function (file) {
var ext = file.name.split('.').pop();
$("#filename").val(Filename + '.' + ext);
},
'onUploadSuccess': function (file, data, response) {
if (response == true) {
$("#eventGrid").jqxGrid('updatebounddata');
}
}
});
It is not possible to call self.AddEvent in 'onUploadsuccess' in my situation...!!!
Please suggest me some best way to store my data and image at same time in ashx handler.
ashx:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var data = context.Request;
var sr = new StreamReader(data.InputStream);
var stream = sr.ReadToEnd();
var javaScriptSerializer = new JavaScriptSerializer();
var asd = javaScriptSerializer.Deserialize<RootObject>(stream);
string Newname = context.Request.Form["someKey"];
BAL Bl = new BAL();
string[] args = new string[2];
//AddEvent method will add my data into database add return response "Success"//
args = AddEvent(asd.objEnt);
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string ext = Path.GetExtension(PostedFile.FileName);
string savepath = "";
string temppath = "";
temppath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
savepath = context.Server.MapPath(temppath);
string fileName = Newname + ext;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);
PostedFile.SaveAs(savepath + #"\" + fileName);
context.Response.Write(temppath + "/" + fileName);
// context.Response.Write(args);
context.Response.StatusCode = 200;
}
}
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader': 'Upload.ashx',
'swf': 'uploadify/uploadify.swf',
'script': 'Upload.ashx',
'cancelImg': 'images/cancel.png',
'folder': '../Upload',
'multi': true,
'buttonText': 'select picture',
'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
'auto': false,
'onUploadStart': function () {
}
});
$.ajax({
type: "POST",
url: 'WebServiceAdmin.asmx/SaveData',
data: "{'p':'" + datam+ "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (d) { $('#FileUpload1').uploadify('upload', '*'); },
error: function () { }
});
I have a Generic Handler (DownloadHandler.cs) which serves as both generating a pdf and downloading a pdf. When generating I use a jQuery ajax call and when downloading I use a form element which is submitted. The problem is that the form element cancels the generate request and therefore the "success" event never gets called (See image below).
Generate code (Gets called from a button):
$.ajax({
type: "POST",
url: "/DownloadHandler.ashx",
data: {
GeneratePdf: true
},
success: function (result) {
console.log(result);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
Download code (Gets called from a button):
var data = { "GeneratePdf": false }
var inputs = '';
$.each(data, function (key, value) {
inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
$('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>').appendTo('body').submit().remove();
DownloadHandler:
public void ProcessRequest(HttpContext context)
{
if (!String.IsNullOrEmpty(context.Request["GeneratePdf"]) && Convert.ToBoolean(context.Request["GeneratePdf"]))
{
Thread.Sleep(3000);
context.Response.Clear();
context.Response.Write("GENERATING");
context.Response.Flush();
}
else
{
Thread.Sleep(3000);
FileInfo pdfFile = new FileInfo(#"C:\1.pdf");
context.Response.Clear();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfFile.Name);
context.Response.AddHeader("Content-Length", pdfFile.Length.ToString());
context.Response.ContentType = "application/octet-stream";
context.Response.WriteFile(pdfFile.FullName);
context.Response.Flush();
}
}
public bool IsReusable
{
get
{
return false;
}
}
I just added a Thread.Sleep to demonstrate the generation of the pdf. Am I missing something or should I use some other method?
Maybe you can try targetting a tiny dynamic iframe on your page with your form. Something like :
var data = { "GeneratePdf": false }
var inputs = '';
$.each(data, function (key, value) {
inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
var f = $('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>');
var iframe = $('<iframe src="about:blank"/>') // should be made tiny/transparent with some css
.appendTo('body');
iframe.contents().find('html').append(f);
f.submit().remove();