I would like to send an image to a php file using AJAX.
Here\'s my JS code:
$.ajax({
type: \"POST\",
url: \"http://website.com/a
If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin
. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you. Why re-invent the wheel?
http://hayageek.com/docs/jquery-upload-file.php
He breaks down the process into four simple steps, that basically look like this:
Look for //1 //2 //3:
<head>
// (1) Load the js files (note that it requires jQuery, which we also load)
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2) Create DIV
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3) initialize plugin
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php
) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile
in the PHP ($_FILES["myfile"]
), and the filename myfile
specified in the jQuery code block.
On the Hayageek web page, study the upload.php
example on the Server
tab.
Note that you can also pass additional variables to the my_php_processor.php
processor file by using dynamicFormData. See this other example:
$("#fileuploader").uploadFile({
url:"my_php_processor.php",
fileName:"myfile",
dynamicFormData: function(){
return {
//my_php_processor.php will receive POST vars below
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
};
},
onSuccess:function(files,data,xhr,pd){
//files: list of files
//data: response from server
//xhr : jquery xhr object
alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
}
});
my_php_processor.php:
<?php
$n = $_POST['newSubj'];
$b = $_POST['newBody'];
$uploadedFile = $_FILES["myfile"]["name"];
//etc.
echo 'This will display in the alert box';
jsFiddle Sample Code - Click on Image Example
If your sending your data using a post, The data property should be a json:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: {img: img}
})
Instead of sending the image, the right approach would be to send image in base64 encoded format. On the server side you'll have to decode the base 64 encoded string and save as an image. Follow this link to get a better insight on how to send encoded image.