Goal:
Created client.ashx by copying existing and working product.ashx and renaming into client.ashx
Modified client.ashx to handle similar logic to product.ashx
I did the above since I don't know how to create an .ashx from scratch in visual studio community. I didn't see a file option for .ashx after the Add/New Item ...
The goal is to upload client images using client.ashx.
File product.ashx uploads product images.
My jscript call to product.ashx works as usual, although when I call the new client.ashx it seems to call product.ashx rather than client.ashx
Sample call to client.ashx
$.ajax({
type: "POST",
url: "/handlers/client.ashx",
data: formData,
global: false,
success: function (result) {
var response = JSON.parse(result);
var success = response.Success;
if (success) {
window.location.replace(window.location);
}
else {
ChangeStatusMessage(response.Message, false, true);
}
},
processData: false,
contentType: false,
error: function (result) {
ChangeStatusMessage("An unknown error occurred while trying to upload the image. Please reload the page and try again", false, true);
}
});
Related
I am using jqgrid, and I need to upload files from two different inputs using one ajax file upload call. I can upload one file using the fileElementId, but is there any way to upload two files simultaneously?
function uploadFiles(dfcId) {
$.ajaxFileUpload({
url: '/DigitalFileCabinet/UploadFile',
type: 'POST',
dataType: 'json',
secureuri: true,
async: false,
data: { id: dfcId },
fileElementId: "file1",
success: function (response, status) {
//success code
},
error: function (data, status, e) {
if (status === 'success')
return;
else
return alert('Failed to upload PDF!');
}
});
};
I have tried the following method, which uses an array to get two file elements at once and upload, but it didn't work.
https://www.programmersought.com/article/194562558/
I want to be able to drag and drop files into multiple folders on a server, I am using jquery to pass to HttpHandler but I can't pass the save location to webhandler. I would like to send the path from jquery in the request is there a way to incluse that when the data for file transfer is passed.
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
Maybe something like this:
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType: false,
processData: false,
data: data,
filepath: document.getElementById("<%=listDrop.ClientID%>");
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
and then retrieve the path in the webhandler to pass as save location?
I have tried this $.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
filepath:JSON.stringify("~/uploads/")
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
}); But I have question about the declaration of the data type for the files I will be uploading when creating the get and set in asp. filepath is a string but what data type are the files.
although i am answering from my mobile, i tried my best to keep the things intact and use ful. If required, Please format it accordingly.
I am not going to write entire code here, just algo.
1. Identify the parameter to be passed. If its only path of multiple folders then you can create an array of objects in javascript for the same. See tge example
var listOfFolder = new string[];
listOfFolder[0]="path of first dir";
:
:
listOfFolder[n]="path of nth dir";
var data = JSON.stringify(listOfFolder);
2. pass this data in data attribute of jquery ajax. 3. Grab this path in Process Request event and deserialize.
4. Do whatever you want.
I have read some post here related but any one could help me out so far, I'm now trying upload a file selected in a input file in client side, then calling a server method using jquery ajax call, please how I'm doing it:
Sever Side Method:
[WebMethod]public static void UploadDetailImageFromClient(string filename, string caption, string itemid, string inspid) {
HttpPostedFile file = HttpContext.Current.Request.Files["ContentPlaceHolder1_uploadBtn"]; if (file != null && file.ContentLength > 0) //See the id here include ContentPlaceHolder as I'm using a MasterPage, here is where I'm never getting the file, it comes NULL
{
string fname = Path.GetFileName(file.FileName);
if (!System.IO.File.Exists(Path.Combine("images/", fname))) {
file.SaveAs(HttpContext.Current.Server.MapPath(Path.Combine("images/", fname)));
}
}
}
Client Side:
<td><asp:FileUpload ID="uploadBtn" runat="server" accept=".png,.jpg,.jpeg,.gif"/></td>
This is the function I invoke to call the server method:
function uploadnewpicture() {
jQuery.ajax({
type: "POST",
url: "FormInspectionsMidPoint.aspx/UploadDetailImageFromClient",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ filename: filename, caption: caption, itemid: itemid, inspid: inspid }),
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function (data) {
jQuery("#ContentPlaceHolder1_uploadBtn").val("");
jQuery("#ContentPlaceHolder1_txtImageDetailCaption").val("");
alert("Picture uploaded successfully");
}
});
}
Please note that I'm calling this javascript function from a input button on click event which is inside a jQuery dialog box. This is why I'm using an ajax call to keep the dialog box on as well as read the value in the input file from the client side as well. I am also using enctype="multipart/form-data" in the form.
I hope someone has had same scenario and can help me. Thanks.
I have faced the Same Situation in my project. You can create a form data object in client side and add the file object to that form data object and pass to the controller. And receive the selected file from request in server side.
Client Side:-
var data = new FormData();
data.append("file", file);
Server Side:-
HttpPostedFileBase file = Request.Files["file"]
var req = $.ajax({
type: 'GET',
cache: false,
url: 'loc.aspx?count=' + str,
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
data:'{}',
success: function (data) {
alert(data.responseText);
}
});
req.fail(function (data) {
TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
});
the above code used to work right in jsp, now i am trying to use in asp.net c#, any way I am getting correct data in error block which i want it in success block. Even data.d is not helping,
If i write something like alert(data) i am getting the complete html, I need just the response text, When i use like this data.responseText, I am getting undefined. Someone help pls.
Thanks
Code below should work fine. I've added some comments where you are doing a mistake
var req = $.ajax({
type: 'GET',
cache: false,
url: 'loc.aspx?count=' + str,
dataType: 'html',// as you return a simple html dataType:json will throw an error as jquery will not be able to parse received string
contentType: "application/json; charset=utf-8",
async: false,
data:'{}',
success: function (data) {
alert(data);// data is not an XHR object. it is a processed response. In your case - simple string with HTML which, of course, has no method responseText
}
});
req.fail(function (data) {
TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
});
In .fail function you have data.responseText because in this case XHR object is passed as a first parameter (See this). At the same time, first parameter of success callback is a clean data received with request. If without details, you can think that data == xhr.responseText in success callback. See success property description in this section
upd
As appeared, problem is not only with JS. I guess you have a simple .aspx page which is called with ajax. There are two solutions:
1) Use webservice instead. It will be better because it does not go through complete page load cycle and should be executed faster. And it will not produce unused HTML
2) aspx page will output some HTML by default. Before you return a response for ajax request, you should clear response (so HTML which is already generated will not be sent to a server), write your response and immediately end it:
Response.Clear();
Response.Write("hello");
Response.End();
This way you should receive only hello in success.
Simply put I want to call public static methods decorated with WebMethod attribute inside my code-behind C# file from jquery.ajax to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'(
I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client)
Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?
After much deliberations I found the problem. I was using jquery's editable plugin. This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
success: function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error: function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
so it was sending the things as simple html and to use this with page methods we need to setup the things so that it sends as json. So we need to add something to the settings like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: 'json', //Data Type
contentType: 'application/json; charset=utf-8', //Content Type
//....other settings
};
So I put two new properties in settings dataType and contentType and changed above to this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: settings.dataType,
contentType: settings.contentType,
//....other settings
};
Now another problem arised :( it was sending data (from submitdata property) as normal query-string which asp.net does not accept with json requests. So I had to use jquery's json plugin and change the way data is sent in ajax using following test on dataType:
if (settings.dataType == "json") {
if ($.toJSON) {
submitdata = $.toJSON(submitdata);
}
}
and it works like breeze!!!
Russ Cam posted this link in response to another question (so if this helps, go up vote his answer ;)):
Using jQuery to directly call ASP.NET AJAX Page Methods
Dave Ward has a series of posts that use jQuery directly with ASP.Net PageMethods, no MS Ajax UpdatePanel required. In particular this post will get you started.
I am not sure but i think WebMethods are accessible only through asp.net AJAX. I may be wrong though, because we dont use it that way at all. We do it in a slightly different way.
We have built a aspx page which accepts all our AJAX requests and passes them to the subsequent methods.
Server side code
If Not (Request("method") Is Nothing) Then
method = Request("method")
username = HttpContext.Current.User.Identity.Name.ToString
Select Case UCase(method)
Case "GETPROJECTS"
Response.ContentType = "text/json"
Response.Write(GetProjects(Request("cid"), Request("status")))
Exit Select
end select
end if
Client Side code [using jquery]
$.ajaxSetup({
error: function(xhr, msg) { alert(xhr, msg) },
type: "POST",
url: "Ajax.aspx",
beforeSend: function() { showLoader(el); },
data: { method: 'GetProjects', cid: "2", status:"open"},
success: function(msg) {
var data = JSON.parse(msg);
alert(data.Message);
},
complete: function() { hideLoader(el); }
});
Hope this helps.