I'm trying to build a uploader using AJAx. I want to use AJAX rather than a form and Iframe as I want the default CSS styles to be in play with the response.
The issue is, that my PHP is on a remote server. I'm using Shopify and they don't allow me to use their server for PHP, so I have it on a different server. For some reason, It's not working. Here is my code:
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
<script type="text/javascript">
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "http://myserver.com/upload.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
crossDomain: true,
success: function(){
alert("file successfully submitted");
},
error: function(){
alert("okey");
}
});
});
All I'm getting with this is the error message. I am following the code outlined in this response: https://stackoverflow.com/a/38450277/6442152
I also tried using this code using xmlhttprequest:
$(':file').change(function(){
var file = this.files[0];
name = file.name;
size = file.size;
type = file.type;
if(file.name.length < 1) {
}
else if(file.size > 100000) {
alert("The file is too big");
}
else {
$(':submit').click(function(){
var formData = new FormData($('*formId*')[0]);
$.ajax({
url: 'script', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // progressbar
}
return myXhr;
},
// Ajax events
success: completeHandler = function(data) {
/*
* Workaround for Chrome browser // Delete the fake path
*/
if(navigator.userAgent.indexOf('Chrome')) {
var catchFile = $(":file").val().replace(/C:\\fakepath\\/i, '');
}
else {
var catchFile = $(":file").val();
}
var writeFile = $(":file");
writeFile.html(writer(catchFile));
$("*setIdOfImageInHiddenInput*").val(data.logo_id);
},
error: errorHandler = function() {
alert("Something went wrong!");
},
// Form data
data: formData,
// Options to tell jQuery not to process data or worry about the content-type
cache: false,
crossDomain: true,
contentType: false,
processData: false
}, 'json');
});
}});
This also got me the error message and then it said 404 file not found
I added this header to my PHP also and it doesn't work:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');