before submit and uploadProgress doesnt work in ajax jquery - php

can any one help me in this problem and i try many ways but beforeSubmit and uploadProgrss doesnt work
$.ajax({
url:"include/ajaxPages/admin/insertNewItem.php",
type:"POST",
data:new FormData(this),
processData:false,
contentType:false,
beforeSubmit:function(){
$(this).find(".progress").width("0%");
},
uploadProgress:function(event,position,total,complete){
$(this).find(".progress").animate({
width: complete+"%"
},{
duration:1000
})
},
success:function(data){
console.log(data);
alert("تم الاضافه بنجاح");
$(".loadingViedo").fadeOut();
window.location = document.URL;
}
})

Try this:
var fd = new FormData();
fd.append('rName', $('#upload-resource .upload').attr('data-name'));
fd.append('rfile', $('#upload-resource .upload').attr('data-file'));
$.ajax({
url: 'include/ajaxPages/admin/insertNewItem.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
xhr: function () { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // if upload property exists
myXhr.upload.addEventListener('progress', function (e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
var percent = Math.round(done / total * 100);
//console.log('xhr progress: ' + percent + '%');
$(this).find(".progress").animate({
width: percent +"%"
},{
duration:1000
});
}, false);
myXhr.addEventListener('load', function (e) {
//upload done
});
$('#upload-resource .cancel').show().click(function () {
//cancel upload
myXhr.abort();
});
}
return myXhr;
},
success: function (data) {
//to do for success result
}
});

Related

File uploading with ajax and progressbar

I am trying to do file upload using ajax and the file is getting upload properly but the problem is i want to show the progress of file upload.
<input type="file" onchange="fileupload(this)" name="song" class="form-control" id="file">
<div id="uploaded_image"><progress id="progress" style="width: 100%;" value="0" max="100"></progress></div>
function fileupload(filee){
var form_data = new FormData();
form_data.append("file", filee.files[0]);
$.ajax({
url:root+"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
if(data=='valid'){
$('#uploaded_image').html("Ho gyiii");
}else if(data=='not valid'){
$('#uploaded_image').html("nhi Ho gyiii");
}
}
});
}
How set progress value dynamically?
I found this somewhere and it's not working and i am not able to understand this
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total)*100;
//Do something with upload progress
console.log(percentComplete);
}
}, false);
// Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
// Do something with download progress
alert(percentComplete);
}
}, false);
return xhr;
},
url:root+"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
if(data=='valid'){
$('#uploaded_image').html("Ho gyiii");
}else if(data=='not valid'){
$('#uploaded_image').html("nhi Ho gyiii");
}
}
});
You can try the below example.
Please replace below values to your values
//your div for showing percent
<div class="progress_bar_in"></div>
//start spinner
$.ajax({
type: type,
url: url,
dataType: dataType,
data: data,
contentType: false,
processData: false,
cache: false,
async: true,
timeout: 60000,
success: function (response) {
//stop spinner
$('.progress_bar_in').html('');
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
let percentage = Math.round(percentComplete * 100);
console.log(percentage);
progressBar = `${percentage}`;
if(percentage >= 100){
progressBar = `File reached server and Show some msg till we get response from server`;
}
$('.progress_bar_in').html(progressBar);
}
}, false);
return xhr;
},
error: function (xhr) {
$('.progress_bar_in').html('');
},
});

xhr addEventListener not working in framework7

I am trying to add a progressbar with percentage while uploading image in framework7 project. Inside ajax function I am unable to get inside the xhr: function() {. My code is below:
$$.ajax({
url: apiurl,
data: formData,
type: "post",
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() { // iam not getting here
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
$('.newprogressbar span').html(Math.round(percentComplete * 100));
}
}, false);
return xhr;
},
success: function(response){
result = JSON.parse(response);
},
error: function(xhr, status){
showweballmessages(lang.networkConnectError,1);
}
});

Message (alert) asking for confirmation

I'm beginner in JS.
I have this code:
var fileLimit = parseInt(1);
function refreshFileList() {
$(".dz-preview").remove();
$.ajax({
url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
type: 'get',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
success: function (response) {
$.each(response, function (key, value) {
var mockFile = {
name: value.name,
size: value.size
};
dpzMultipleFiles.emit('addedfile', mockFile);
dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
dpzMultipleFiles.emit('complete', mockFile)
})
},
error: function (response) {
alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
}
});
}
Dropzone.options.dpzMultipleFiles =
{
maxFiles: fileLimit,
clickable: true,
thumbnailWidth: 250,
thumbnailHeight: 250,
autoProcessQueue: true,
dictDefaultMessage: '',
uploadMultiple: true,
paramName: "myFile",
acceptedFiles: ".jpg,.jpeg",
addRemoveLinks: true,
timeout: 50000,
dictRemoveFile: 'Usuń plik',
init: function () {
dpzMultipleFiles = this;
refreshFileList();
this.on("thumbnail", function (file, dataUrl) {
$('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
}),
this.on('completemultiple', function (file, json) {
//$('.sortable').sortable('enable');
});
this.on('success', function (file, json) {
//alert('aa');
});
this.on('addedfile', function (file) {
fileLimit = fileLimit - 1;
});
this.on('drop', function (file) {
fileLimit = fileLimit + 1;
});
this.on("maxfilesexceeded", function (file) {
alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
this.removeFile(file);
});
},
removedfile: function (file) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
type: 'POST',
url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
data: {filename: file.name, id: file.name, type: 'SplashImage'},
success: function (data) {
console.log("File has been successfully removed!!");
//refreshFileList();
},
error: function (e) {
console.log(e);
}
});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
}
};
$(function () {
$(".dropzone").sortable({
items: '.dz-preview',
cursor: 'move',
opacity: 0.5,
containment: '.dropzone',
distance: 20,
tolerance: 'pointer',
update: function (event, ui) {
$(".dz-filename span").each(function (index) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
dataType: 'text',
type: 'post',
cache: false,
data: $(this).serialize(),
success: function (data, textStatus, jQxhr) {
},
error: function (jqXhr, textStatus, errorThrown) {
alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
}
});
});
}
});
});
This is Dropzone.JS. This code work fine.
I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.
How to do it? I need a simple alert with a question in JS
You can add confirm in the remove function :
removedfile: function (file) {
if (!confirm('Are you sure?')) {
return;
}
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
type: 'POST',
url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
data: {filename: file.name, id: file.name, type: 'SplashImage'},
success: function (data) {
console.log("File has been successfully removed!!");
//refreshFileList();
},
error: function (e) {
console.log(e);
}
});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
}
I think what you are looking for is a confirm().
if (confirm('Are you sure?')) {
console.log('confirmed');
} else {
console.log('declined');
}
You can use bootstrap modal for the confirmation that you want to ask.
the link is here

form validation in ajax before submitting form through ajax

Im using ajax to submit a form and inserting the values to the database..I tried many ways but validation error check doesnt come out right.
here is my code
$(document).ready(function() {
$('body').on('click', '#Submit', function(e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'formrelay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
document.getElementById('Message').innerHTML = data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
I tried using submithandler (saw in one of the tutorial) but it did not work..pls help..code below
$(document).ready(function(){
$("#relay_form").validate({
rules: {
f_name: { required : true }
},
submitHandler : function (form) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url:'form_relay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
document.getElementById('Message').innerHTML=data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});
This worked for me..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<!-- red color for error message -->
<style type="text/css">
#hardship_form .error {
color: red
}
</style>
<script>
$(document).ready(function() {
$("#relay_form").validate({
rules: {
f_name: {
required: true
}
},
messages: {
f_name: "Please Enter first name"
},
submitHandler: function(form) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'form_relay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
document.getElementById('Message').innerHTML = data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});
</script>
Thanks Milan

Print Json data into html format

I posted the image in an array from my form using AJAX, and in response I received a JSON data
I received the below code in my console as response;
0"C:\xampp\htdocs\3Dklik\..../1492427792slider_7.jpg"
1"C:\xampp\htdocs\3Dklik\mog/1492427792slider_2.jpg"
2"C:\xampp\htdocs\3Dklik\mo…../public/img/1492427792"
id""
user_id"1"
The following is my AJAX code:
<script type="text/javascript">
$(document).ready(function(e) {
$("#btnsubmit").on('click', function(e) {
e.preventDefault();
var formData = $('#uploadform').serialize();
var files = $("#uploadform")[0];
console.log(files);
$.ajax({
url: '<?php echo $this->url('
upload ');?>',
type: 'POST',
data: new FormData(files),
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
alert("Data Uploaded: " + data);
console.log(data);
},
error: function(result) {
alert("Error");
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
And the following is my PHP code;
public function uploadAction() {
$request = $this - > getRequest();
if ($request - > isPost()) {
$data = array_merge_recursive(
$request - > getPost() - > toArray(),
$request - > getFiles() - > toArray()
);
// echo'<pre>';print_r($data);
}
$image_array = array_slice($data, 2);
//print_r($image_array);
foreach($image_array as $files) {
//print_r($files);
$file_new_name = round(microtime(true)).$files['name'];
$destination = "public/img/".$file_new_name;
$file_name = $files['tmp_name'];
move_uploaded_file($file_name, $destination);
$data[] = __DIR__.('/../../../../../public/img/').$file_new_name;
}
return new JsonModel(array(
'data' => $data
));
}
Basically the JSON data includes the image path, but I wish to display the image in my <div>. How can I achieve this?
you can sen the JSON format like validate.php in you can use;
echo json_encode(arrayvalue);
$("#btnsubmit").on('click', function(e) {
e.preventDefault();
var formData = $('#uploadform').serialize();
var files = $("#uploadform")[0];
console.log(files);
$.ajax({
url: '<?php echo $this->url('
upload ');?>',
type: 'POST',
data: new FormData(files),
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
alert("Data Uploaded: " + data);
console.log(data);
$.each(data, function(i, item) {
alert(data[i].imgName);
});
},
error: function(result) {
alert("Error");
},
cache: false,
contentType: false,
processData: false
});
return false;
});

Categories