The Form:
<form action="upload-document.aspx" onsubmit="sendAndClose();" method="post" enctype="multipart/form-data">
<input name="fileToUpload" id="fileToUpload" type="file" />
<input type="submit" name="submit" value="Send" />
</form>
The AJAX:
function sendAndClose() {
currentUrl = location.protocol + '//' + location.host + location.pathname;
var data = new FormData();
var file = $("#fileToUpload")[0].files[0];
data.append("name", file.name);
data.append("size", file.size);
data.append("type", file.type);
data.append("file", file);
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
}
The Code-Behind:
[WebMethod]
public static bool Persist(object data)
{
return true;
}
when the form is submitted, it runs the ajax and goes straight to the error callback before entering the webmethod. can anybody tell me why?
also, after the 'var file' I had an alert to show the files name, size, etc... so it gets the file, the problem is that ajax is refusing to comunicate with the code-behind.
I had a similar problem that was solved by adding this parameter in the ajax function :
traditional: true
So try this code for your AJAX call :
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
traditional: true,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
You cannot invoke a webmethod like http://localhost:40899/upload-document.aspx/Persist
. The currentUrl is incorrect.
Following on from my question in the comments section I would add that your public static bool Persist...
method MUST be in the page (ASPX) and not a user-control (ASCX).
This is because the page (ASPX) is "visible" to the outside world via a URL whereas a user-control (ASCX) is only used on the server to build up the page not a URI in its own right, and therefore not accessible to external callers.
If you need to call the method in the user-control you will need to move your Persist
method (with WebMethod
attribute) to your page (ASPX) and then make a call from that method into your user-control (ASCX).