I'm trying to do a file upload using AJAX but I get a 403 server response... but when I do the same thing as a non-AJAX request, it works fine. Here is my HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>
<script type="text/javascript">
function importFileAJAX() {
fileData = $('#importfileAJAX').prop('files')[0];
formData = new FormData();
formData.append('file', fileData);
$.ajax({
method: "POST",
url: "testimportfiles.php",
data: formData,
processData: false
}).done(function(xml) {
alert( $(xml).find('result').text());
}).fail(function(jqXHR, errorText, exceptionText) {
alert("Error: " + jqXHR.responseText);
});
}
</script>
</head>
<body>
AJAX: <input id="importfileAJAX" type="file" />
<button onclick="importFileAJAX();">Import Files</button>
<hr />
<form action="testimportfiles.php" method="post" enctype="multipart/form-data">
Non-AJAX: <input type="file" name="file" id="file">
<input type="submit" value="Import Files" name="submit">
</form>
</body>
</html>
My php file (testimportfiles.php
) is just this:
<?php
header('Content-Type: text/xml');
print("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>");
print("<result>0</result>");
print("</root>");
The second method works just fine, but the first method returns a 403 error from the server. Is this a configuration issue with my server, or am I just doing something wrong in my code?
Thanks!
EDIT: I'm leaving this question unanswered in case there's a better way, but I've solved my problem using AjaxFileUpload.js, which mimics an AJAX request by dynamically creating a form and targeting the response to a dynamically-created iFrame. The server response is then copied from the iFrame.
I'm still curious if a true AJAX transaction is possible (i.e., something that doesn't require a browser window or iFrame as a target for the server response), but this will work for me in my current project.
authenticating
onbackend
withcookies
?authorization issue
as response code403
simply says The server understood the request but refuses to authorize it