Reputation: 1
i'd like to know how can i use $_POST and $_FILES using ajax, i'm trying to upload an image and insert a value on my database with post.
i've tried but it doesn't work.
index.html
<div class="form-group">
<label> img </label>
<input type="file" name="img" id="img" />
<input type='hidden' id='value' value='<?=$_GET["p"]?>' />
</div>
ajax.js
$(document).ready(function() {
$('#upload').click(function() {
var value = $('#value').val();
var img = $('#img').val();
var string= 'value=' + value + '&img=' + img;
$.ajax({
type: "POST",
url: "ajax.php",
data: string,
dataType: "json",
success: function(data) {
var success = data['success'];
if (success == true) {
console.log('success');
} else {
console.log('error');
}
}
});
return false;
});
});
ajax.php
<?php
if(isset($_POST["value"]) && isset($_FILES["img"])) {
echo json_encode(array("success" => true));
} else {
echo json_encode(array("success" => false));
}
?>
Upvotes: 0
Views: 33
Reputation: 43
The best approach is convert image to base64 first. This conversion is done in the change listener.
var files = []; $("input[type=file]").change(function(event) { $.each(event.target.files, function(index, file) { var reader = new FileReader(); reader.onload = function(event) { object = {}; object.filename = file.name; object.data = event.target.result; files.push(object); }; reader.readAsDataURL(file); }); }); $("form").submit(function(form) { $.each(files, function(index, file) { $.ajax({url: "/ajax-upload", type: 'POST', data: {filename: file.filename, data: file.data}, success: function(data, status, xhr) {} }); }); files = []; form.preventDefault(); });
Upvotes: 1