jquery datatables : load real time progress bar - javascript

A normal ajax real time progress bar loads like this,
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
var pro = (e.loaded / e.total) * 100;
$('.progress-bar-anim').css('width', pro + '%').attr('aria-valuenow', pro);
}, false);
return xhr;
},
type: "POST",
dataType: 'json',
url: "data.php",
data: {"username": username, "password": password},
success: function(msg) {
if (msg.status == 'success') {
window.location = "dashboard.php"
} else {
hide_progress();
}
}
});
I want to load a real time progress bar in jquery datatables while the server response is being received.How should I go about it ?

Create the table in your success method:
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
function handleData(data) {
table = $('#table').DataTable( {
"data": data,
....
}

Related

'parsererror' error In MYSQL Axaj Django upload in chunks

I want to upload a file in chunks, and it works on SQLite but i wont work with MYSQL, and it uploads the file only till 10mb/11mb. Debug false/true gives me the same error
JS:
$.ajax({
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
if (self.file.size < self.max_length) {
var percent = Math.round((e.loaded / e.total) * 100);
} else {
var percent = Math.round((uploadedChunk / self.file.size) * 100);
}
$('.progress-bar').css('width', percent + '%')
$('.progress-bar').text(percent + '%')
}
});
return xhr;
},
url: '/create-post',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
contentType: false,
data: formData,
error: function (xhr) {
alert(xhr.statusText);
},
success: function (res) {
if (nextChunk < self.file.size) {
// upload file in chunks
existingPath = res.existingPath
self.upload_file(nextChunk, existingPath);
} else {
// upload complete
$('.textbox').text(res.data);
alert(res.data)
}
}
});
}};
Views:
https://imgur.com/a/FThSXAO
All of this gives me
parsererror
Nothing else...

Prevent script from duplicating?

I'm having this problem with Ajax where each time data is sent, the script gets duplicated and it makes my audio overlap or play multiple times.
$.ajax({
url: 'fetch.php',
method: 'POST',
data: { limit: limit, start: start },
cache: false,
success: function (data) {
$('#load_quotes_recent').append(data);
if (!$.trim(data)) {
action = 'active';
} else {
action = 'inactive';
}
if (window.location == 'https://www.example.com/') {
$('.icon-wrapper').on('click', function () {
var postid = $(this).data('id');
$post = $(this);
$.ajax({
url: 'fetch.php',
type: 'post',
data: {
'liked': 1,
'postid': postid
},
success: function (response) {
var audio = new Audio('../sounds/pop.mp3');
audio.pause();
audio.currentTime = 0;
audio.play();
}
});
});
}
}
});
I was wondering if there was a way to prevent the script from duplicating itself so that the audio won't overlap?
The reason why I have it like this is because if I were to put the script in fetch.php Ajax will think I still have data left once I've reached the end even though I do not.
It would be great if there was a way to "replace" the same script instead of duplicating them.
Why not just initialise the audio separate from the AJAX, then only have it play when needed?
var audio = new Audio('../sounds/pop.mp3');
$.ajax({
url: 'fetch.php',
method: 'POST',
data: { limit: limit, start: start },
cache: false,
success: function (data) {
$('#load_quotes_recent').append(data);
if (!$.trim(data)) {
action = 'active';
} else {
action = 'inactive';
}
if (window.location == 'https://www.example.com/') {
$('.icon-wrapper').on('click', function () {
var postid = $(this).data('id');
$post = $(this);
$.ajax({
url: 'fetch.php',
type: 'post',
data: {
'liked': 1,
'postid': postid
},
success: function (response) {
audio.pause();
audio.currentTime = 0;
audio.play();
}
});
});
}
}
});

How to prevent function from running if data error is returned

I have an AJAX request which shows a modal window with a progress bar when the data is computable but if there is an error I would like the error to be returned and the modal window to stay hidden.
$(document).ready(function(){
$(function () {
var pleaseWait = $('#pleaseWaitDialog');
showPleaseWait = function () {
pleaseWait.modal('show');
};
hidePleaseWait = function () {
pleaseWait.modal('hide');
};
});
var $myForm = $('.form')
$myForm.on('submit', function(event){
event.preventDefault();
var form = $(event.target)
var formData = new FormData(form[4]);
$.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
},
});
});
});
I have tried moving the showPleaseWait function under the if(data.error) statement but this doesn't work.
How do I keep the modal window hidden if the response is (data.error)?
EDIT:
And this removes the HTML of the page and shows the JSON response instead:
success: function(data){
if (data.success) {
window.location.href = data.url;
}
error: function (jqXHR, exception) {
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
}
},
Your function is the "succes" property of the ajax object.
As shown in the doc, there is a "error" property to handle ajax error, here is the signature :
error(xhr,status,error)
Use it like you do with the succes property :
$.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
},
error: function(xhr,status,error){
// Do something
}
});
I hope it solved your issue !
$.ajax() doc
I think you are using Jquery 3.0
so try this
var jqxhr = $.ajax({
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
showPleaseWait(); // <--------------- This runs even when view returns error
console.log('Percentage uploaded: ' + (e.loaded / e.total))
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%');
}
});
return xhr;
},
type: 'POST',
url: form.attr('action'),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this),
success: function(data){
if (data.success) {
window.location.href = data.url;
}
if (data.error) {
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
}
},
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
$("#top").html(data.error.title).addClass('form-field-error');
$("#div_id_title").removeClass('form-group');
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

jQuery Ajax file upload with progress hangs

I'm using jQuery to upload files. Everything worked fine, until I've added xhr: function () {...} code to track file upload progress. Now it just hangs after Start loading image.... If I remove this block from $.ajax, file upload works.
function showProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('.meter').attr({'width': percentComplete + '%'});
}
}
console.log('Start loading image...')
$.ajax({
url: '/uploadimage',
type: 'POST',
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', showProgress, false);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
},
//Ajax events
beforeSend: function (xhr) {
// CSRF...
},
success: function (data) {
// do smth
},
// Form data
data: formData,
cache: false,
contentType: false,
processData: false
});
What I'm doing with upload progress wrong? Thanks.
Did you get this resolved? Are you using the upload templates provided or using your own custom markup?
The following works for me:
<script type="text/javascript">
$(document).ready(function () {
$('#btnContinue').prop('disabled', true);
$('#fileupload').fileupload({
url: '#Url.Action("UploadChunk", "Upload")',
maxChunkSize: 1048576,
}).addClass('fileupload-processing')
.bind('fileuploadalways', function (e, data) {
if ($('#fileIds').val().indexOf(';' + data.result.id + ';') == -1) {
var pre = $('#fileIds').val() == "" ? ';' : '';
var append = $('#fileIds').val() + pre + data.result.id + ';';
$('#fileIds').val(append);
}
})
.bind('fileuploaddone', function (e, data) {
$('#btnContinue').prop('disabled', false);
});
$.ajax({
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
});
});
</script>
I do have an issue with my setup, but you should be able to reference my code for what you are trying to achieve.
Submit Additional Form Data without setting formData

Categories