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));
}
?>
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();
});
Related
The code below is working fine to upload files to SPO through RestAPI. No feedback is received on file upload progress. An alert is thrown once the upload is complete.
I would like to have a progress bar to display the upload percentage and reload this upload page while clicking OK to the successful alert message.
Kindly assist.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function () {
init();
});
function init(){
$("#btnUploadFiles").click(function(){
var files=$("#inputTypeFiles")[0].files;
uploadFiles(files[0]); // uploading singe file
});
}
function uploadFiles (uploadFileObj) {
var fileName = uploadFileObj.name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary="TEST";
var folderName = "";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&#target='" + targetUrl + "'";
uploadFileToFolder(uploadFileObj, url, function (data) {
var file = data.d;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
departname: $("#departname").val(), //meta data column1
Filename: $("#filename").val(), //meta data column2
ACFTREG: $("#ACFTREG").val(), //meta data column3
Date: $("#datepicker").val() //meta data column4
};
url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";
updateFileMetadata(url, updateObject, file, function (data) {
alert("File uploaded & metadata updation done successfully");
}, function (data) {
alert("File upload done but metadata updating FAILED");
});
}, function (data) {
alert("File uploading and metadata updating FAILED");
});
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
var getFile = getFileBuffer(fileObj);
getFile.done(function (arrayBuffer) {
$.ajax({
url: apiUrl,
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
});
}
function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
$.ajax({
url: apiUrl,
type: "POST",
async: false,
data: JSON.stringify(updateObject),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Type": "application/json;odata=verbose",
"X-Http-Method": "MERGE",
"IF-MATCH": file.ListItemAllFields.__metadata.etag,
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
function getItems() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('L%20-%20MDB%20-%20ACFTREG')/items?$Select=Title&$top=2000",
type: "GET",
headers: {
"accept": "application / json;odata = verbose",
},
success: function(data) {
var results = data.d.results;
var options = "";
for(var i = 0; i < results.length; i++){
options = options + "<option value='" + results[i].Title + "'>" + results[i].Title + "</option>";
}
$("#ACFTREG").append(options);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
$( function() {$( "#datepicker" ).datepicker(
{
changeMonth: true,
changeYear: true
}
);} );
</script>
Select File:<input type="File" id="inputTypeFiles" /><br />
Departname: <input id="departname" type="textbox"/><br />
Date: <input type="text" id="datepicker" autocomplete="off" name="hidden"><br />
Filename: <input id="filename" type="textbox"/><br />
ACFTREG: <select id="ACFTREG" class="select">
<option selected="selected">Select</option><br />
<input type="button" id="btnUploadFiles" value="Upload"/><br />
Inside the $.ajax({}) function, you can add the xhr setting inside the ajax.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
// Place upload progress bar visibility code here
}
}, false);
return xhr;
},
type: 'POST',
//add the rest of ajax settings
check this link for ajax documentation
jQuery/ajax
check this link for example on upload progress
jQuery-upload-progress/example
Explain what is wrong here. First, the run function and its ajax request must be executed. But for some reason the function is executed, and the ajax request is not. It runs right at the very end of the script - after all the functions ... Why is this happening and how to fix it?..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="id_product_create_form" method="post" enctype="multipart/form-data"></form>
<div class="media_preview_wrap">
<div class="addPhoto">
<div class="addPhotoHeader">
<button type="button" class="button product_images_button">Add</button>
<button id="id_submit" type="button">Submit</button>
</div>
</div>
</div>
<input type="file" name="image" style="display: none" required="" class="product_images" id="">
<script>
var files = [];
$('.product_images_button').click(function() {
$('.product_images').click();
});
$('.product_images').change(function() {
handleFiles(this);
});
$('.media_preview_wrap').on('click', '.thumb', function() {
removeFile($(this).data('id'));
});
$('#id_submit').click(function() {
event.preventDefault();
var $form = $('form'),
formdata = new FormData($form[0]),
$button = $('#id_submit');
formdata.append('content', CKEDITOR.instances.id_content.getData());
function run() {
var product_id = null;
$.ajax($form.attr('action'),{
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(data) {
product_id = data.product_id;
}, error: function(error) {
console.log(error)
}
});
return product_id}
product_id = run();
files.forEach(function(file, index) {
var data = new FormData();
data.append('name', file.name);
data.append('gallery_image', file.file);
uploadFile(event.target.action, data)
.done(function(response) {
removeFile(file.id);
})
.fail(function(error) {
console.log(error);
});
});
});
function handleFiles(input) {
var URL = window.URL || window.webkitURL;
var uniqueId = (new Date()).getTime()
for (var i = 0; i < input.files.length; i++) {
var file = input.files[i];
if (file && file.type.startsWith('image/')) {
uniqueId++;
files.push({
id: uniqueId,
file: file,
name: file.name // задел для возможности переименования файла.
});
var img = $('<img src="'+ URL.createObjectURL(file) +'" class="thumb" data-id="'+ uniqueId +'">');
$('.media_preview_wrap').append(img);
img.on('load', function() {
URL.revokeObjectURL(this.src);
});
}
}
$(input).val('');
}
function removeFile(id) {
files = files.filter(function(file) {
return id !== file.id;
})
$('img[data-id="'+ id +'"]').remove();
}
function uploadFile(url, data) {
return $.ajax({
headers: {'X-CSRFToken': '{{ csrf_token }}' },
type: 'POST',
url: url,
data: data,
processData: false,
contentType: false,
cache: false
});
}
</script>
<style>
.thumb {
width: 150px;
height: auto;
opacity: 0.9;
cursor: pointer;
}
.thumb:hover {
opacity: 1;
}
.product_images {
display: none;
}
</style>
The initial problem is likely due to some browsers having a global event object while others don't.
You are likely getting an error that event is undefined and that would prevent the remaining code to run
Use the argument of the event handler function which always passes in an event object:
$('#id_submit').click(function(event) {
// ^^^
event.preventDefault();
Once that issue is solved... you need to realize that $.ajax is asynchronous and you can't use the new value of product_id until first request completes in the success callback
See How do I return the response from an asynchronous call?
I am trying getting the images stored at folder, but the when i am calling the images give 404 because of this:
http://localhost/xxxx/new/item/77/public/images/item/77/2.jpg
i don't no how to remove "new/item/77/" and get the image to the correct folder:
My javascript
$(".dropzone").dropzone({
init: function() {
myDropzone = this;
$.ajax({
url: 'image/get',
type: 'post',
data: {request: 'fetch'},
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name, size: value.size};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
}
});
My route
Route::post('new/item/{id}/image/get','ItemController#fileGet');
My Controller
public function fileGet(Request $request){
$fileList = [];
$targetDir= 'public/images/item/77/';
$dir = $targetDir;
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
$file_path = $targetDir.$file;
if(!is_dir($file_path)){
$size = filesize($file_path);
$fileList[] = ['name'=>$file, 'size'=>$size, 'path'=>$file_path];
}
}
}
closedir($dh);
}
}
echo json_encode($fileList);
exit;
}
What i expect is
http://localhost/xxxx/public/images/item/77/2.jpg
Or if any one knows a better way to get the files stored in the dropzone.js
Thnaks!
$(".dropzone").dropzone({
init: function() {
Dropzone = this;
$.ajax({
url: APP_URL + '/image/get',
type: 'post',
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name, size: value.size};
Dropzone.options.addedfile.call(Dropzone, mockFile);
Dropzone.options.thumbnail.call(Dropzone, mockFile, APP_URL+"/"+value.path);
Dropzone.options.complete.call(Dropzone, mockFile);
});
}
});
}
});
I am trying to upload and preview the image using jQuery Ajax. But it is reloading page whenever I am choosing image file only. One thing I noticed here is that, it is not reloading the page if I am choosing files other than image file. I have checked for the solution online and added all the possible solutions suggested for this i.e contentType: false and event.preventDefault(); but it is still not working as expected
HTML Code is as below
<form id="createCategory">
<label>Name</label>
<input name="Name" />
<br />
<label>Description</label>
<input name="Description" />
<br />
<label>Image</label>
<input id="inpImageURL" name="ImageURL" type="hidden" />
<input id="inpImageUpload" name="Image" type="file"/>
<div class="thumb">
<img id="imgUploadImage" src="#" alt="your image" />
</div>
<br />
<button type="submit">Save</button>
</form>
jQuery Code is as below
$("#inpImageUpload").change(function (event) {
debugger;
event.preventDefault();
var element = this;
var formData = new FormData();
var totalFiles = element.files.length;
for (var i = 0; i < totalFiles; i++) {
var file = element.files[i];
formData.append("Photo", file);
}
$.ajax({
type: 'POST',
url: '/Shared/UploadImage',
dataType: 'json',
data: formData,
processData: false,
contentType: false
})
.done(function (response) {
debugger;
alert('ajax was called success');
//console.log(response);
//if (response.Success) {
// //$("#imgUploadImage").attr("src", response.inpImageURL);
// //$("#inpImageURL").val(response.inpImageURL);
// alert('ajax was called success');
//}
})
.fail(function (XMLHttpRequest, txtStatus, errorThrown) {
alert("Failure AJAX Call");
});
});
ASP.Net MVC code is below
public class SharedController : Controller
{
public JsonResult UploadImage()
{
JsonResult result = new JsonResult();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
try
{
var file = Request.Files[0];
var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
file.SaveAs(path);
result.Data = new { Success = true, ImageURL = string.Format("/Content/images/{0}", fileName) };
}
catch (Exception ex)
{
result.Data = new { Success = false, Message = ex.Message };
}
return result;
}
}
I have this function wherein I can update my input fields, I have a fetch.php that fetches data from my sql.
So this is my input fields --> [Sample Pic - Input Fields][1]
Then when I click update it returns this --> [Sample Pic - Updating Input Fields][2]
My problem is whenever I update it returns all of the data in the fields except the date and time? How can I fix this?
Below are my codes. TYVM.
<div class="col-sm-2">
<input type="datetime-local" name="date_submitted" id="date_submitted" class="form-control" placeholder="Date Submitted" style="width: 120%;" />
</div>
<script>
$(document).ready(function() {
addDocu();
function addDocu() {
var action = "select";
$.ajax({
url: success: function(data) {
alert(data);
addDocu();
}
});
} else {
alert("All Fields are Required");
}
});
$(document).on('click', '.update', function() {
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {
id: id
},
dataType: "json",
success: function(data) {
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.remarks);
}
})
"select.php",
method: "POST",
data: {
action: action
},
success: function(data) {
$('#code').val('');
$('#doc_kind').val('');
$('#date_submitted').value('');
$('#remarks').val('');
$('#action').text("Add");
$('#result').html(data);
}
});
}
$('#action').click(function() {
var docCode = $('#code').val();
var docKind = $('#doc_kind').val();
var dateSubmitted = $('#date_submitted').val();
var docRemarks = $('#remarks').val();
var id = $('#docu_id').val();
var action = $('#action').text();
if (docCode != '' && docKind != '' && dateSubmitted != '') {
$.ajax({
url: "action.php",
method: "POST",
data: {
docCode: docCode,
docKind: docKind,
dateSubmitted: dateSubmitted,
docRemarks: docRemarks,
id: id,
action: action
},
success: function(data) {
alert(data);
addDocu();
}
});
} else {
alert("All Fields are Required");
}
});
$(document).on('click', '.update', function() {
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {
id: id
},
dataType: "json",
success: function(data) {
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.remarks);
}
})
});
</script>
if(isset($_POST["id"]))
{
$output = array();
$procedure = "
CREATE PROCEDURE whereDocu(IN docu_id int(11))
BEGIN
SELECT * FROM officesectb WHERE id = docu_id;
END;
";
function convert ($rem) {
$rem = trim($rem);
return preg_replace('/<br(\s+)?\/?>/i', "\n", $rem);
}
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL whereDocu(".$_POST["id"].")";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$rem = $row["remarks"];
$output['code'] = $row["code"];
$output['doc_kind'] = $row["doc_kind"];
$output['date_submitted'] = $row['date_submitted'];
$output['remarks'] = convert($rem);
}
echo json_encode($output);
}
}
}