I have an Ajax-Upload script that works fine. Now I want add an progressbar or something else. How can I implement something like that in my script below:
$('body').on('change', '#uploadFile', function() {
// Post-Data
var data = new FormData();
data.append('file', this.files[0]);
data.append('uid', $("#uploadFile").attr('data-uid'));
// Ajax-Call
$.ajax({
url: "uploadUserpic.php",
data: data,
type: "POST",
processData: false,
contentType: false,
success : handleData
});
});
function handleData(data) {
$("#messagePic").html(data);
//do some stuff
}
Not possible with $.ajax, You need a XMLHttpRequest object.
Try this:
var data = [];
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
// For Upload
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
// For Download
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
type: 'POST',
url: "/echo/html",
data: data,
success: function (data) {}
});
http://jsfiddle.net/GvdSy/
Related
let formData2 = new FormData();
formData2.append('_token', vm.response._token);
formData2.append('file', vm.response.content[i].path);
formData2.append('type', vm.response.content[i].type);
$.ajax({
async: false,
url: "page/file/create/upload/"+vm.response.topic_id,
type: "POST",
data: formData2,
cache: false,
dataType: 'json', // what to expect back from the PHP script
contentType: false,
processData: false,
xhr: function() {
var xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open('POST', this.url, false);
if (xhr.open) {
console.log("xhr port open");
}
if (xhr.upload) {
xhr.upload.addEventListener('progress', this.onProgress);
console.log("xhr.upload");
}
return xhr;
// console.log(xhr);
},
success: function (title) {
console.log(" file upload in controller recieves: "+title);
},
})
}
point : 1 > this is a function written in "methods" in a vue page (file uploading practice project with laravel v5.5 + vue 1.0)
point : 2 > from my controller file is uploaded smoothly , has no issue with that.
point :3 > now i want to impletement a progressbar which shows me the uploading %
have tried xhr:function but do not know to fetch the uploading %...
now my xhr function is look like this.. if i get the value of percentage. i will bind that with my progressbar value. but i can not get any upload %
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
console.log(xhr);
xhr.open('POST', this.url, false);
if (xhr.open) {
console.log("xhr port open");
}
if (xhr.upload) {
var percentage = 0;
xhr.upload.addEventListener('progress', function(e) {
if(e.lengthComputable) {
percentage = e.loaded/e.total;
percentage = parseInt(percentage * 100);
// Do what ever you want after here
console.log("percentage:"+percentage);
}
}, false);
}
return xhr;
// console.log(xhr);
},
You can try this code below, it works in my side:
xhr : function() {
var xhr = jQuery.ajaxSettings.xhr();
if(xhr.upload) {
if(xhr instanceof window.XMLHttpRequest) {
var percentage = 0;
xhr.upload.addEventListener('progress', function(e) {
if(e.lengthComputable) {
percentage = e.loaded/e.total;
percentage = parseInt(percentage * 100);
// Do what ever you want after here
}
}, false);
}
}
return xhr;
}
Basically, I was using xhr = jQuery.ajaxSettings.xhr() and xhr.upload.addEventListener progress to compute its progress percentage.
Hope this works.
Finally it's working for me. happy me :)
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log("% :" + percentComplete );
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
How to add a progress event listener to a prototype Ajax request ?
I didn't find anything in the prototype doc about this ..
I found some example using jQuery but not with prototype.
new Ajax.Request('/some_url', {
method:'get',
onSuccess: function(transport) {..},
onFailure: function() {..}
});
using jQuery:
$.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;
//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
console.log(percentComplete);
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){..}
});
Here's an example that I use in my code for doing AJAX file uploads
new Ajax.Request('backend.php',{'method':'get','onCreate':function(t){
t.transport.upload.onprogress = function(event){
if(event.lengthComputable)
{
console.log((event.loaded / event.total * 100 | 0)+'%');
}
}
},'onSuccess':function(result){
console.log("success")
}});
I'm trying to use a self invoked function to do an ajax call.
Later I want to use the response to populate a data property inside Vue, but for some reason I'm not able to do that.
Here is my code so far
//chiamata Ajax a servizio
var getData = (function(){
var req = $.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response)
{
result =JSON.parse(response);
}
});
return {
getResponse:function(){
return req.success;
}
}
}());
var modello = getData.getResponse();
My goal is to pass modello as data in Vue.
Here the VUE:
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:modello
},
methods:{
},
beforeMount(){
this.modello = modello;
}
})
What have I done wrong?
Instead you can perform the ajax call in the created() lifecycle hook and set the data property modello to the response there like this:
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:null
},
methods:{
},
created(){
var self = this;
$.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response){
self.modello = response;
}
});
},
})
Here is the jsFiddle
If you want to seperate the logic:
var getData = function(){
return $.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response){
console.log(response);
}
});
};
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:null
},
methods:{
},
beforeMount(){
var self = this;
getData().then(function(response){
self.modello = response;
}, function(error){});
}
})
here is the updated fiddle
thanks to Bert Evans for pointing out my mistake
$.ajax({
url: "",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
dbInsert(elem['itemCode'], elem['description'], elem['price']);
});
},
error: function(request, error) {
alert(error);
}
});
I have the above type of different ajax calls with different urls. How can I run each Ajax call, one after another?
You can do something like this.
$('#button').click(function() {
$.when(
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('one is done')
}
}),
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('two is done')
}
})
).then( function(){
alert('Final Done');
});
});
fiddle
Keep track of the urls still to send, and have the success inline function of one ajax request go and call the next.
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
... do what you want with the data ...
if (urls.length > 0) runNextAjax();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
}
});
};
// Start the sequence off.
runNextAjax();
The above code acts on the data as it arrives, if you want to cache it all and act on it all at the end, store each result in an array, then process the array in a function that gets called at the end:
var dataAccumulator = [];
var displayAllData = function() {
for (int i = 0; i < dataAccumulator.length; ++i) {
var data = dataAccumulator[i];
... process the data into HTML as before ...
}
};
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
// Store the data we received
dataAccumulator.push(data);
if (urls.length > 0) runNextAjax();
else displayAllData();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
else displayAllData();
}
});
};
// Start the sequence off.
runNextAjax();
Fiddle: http://jsfiddle.net/gpTpK/
The issue I am having is that the title variable is not updated/changed when the $.ajax is executed, I know that the ajax call is working as I have tried replacing the line
title = $(xml).find("title").text();
with
console.log($(xml).find("title").text());
and sure enough it does return the title however when using the orginal line the variable title doesn't change
I have tried and it does work putting the ajax call outside (function($){})(jQuery);
(function($) {
$.fn.getPost = function(options) {
var $this = $(this);
var defaults = {
method: "html",
blogID: "",
postID: "",
done: null
};
var options = $.extend(defaults, options);
var title;
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/724793682641096478/posts/default/3551136550258768001",
dataType: "xml",
dataType: 'jsonp',
success: function(xml) {
title = $(xml).find("title").text();
}
});
return $this.each(function() {
if (options.done) {
options.done.call(undefined, title);
}
});
};
})(jQuery);
I have tried the below and i have also tried wrapping the ajax in a function such as getTitle(){ajax code here with return title;}
(function($) {
$.fn.getPost = function(options) {
var $this = $(this);
var defaults = {
method: "html",
blogID: "",
postID: "",
done: null
};
var options = $.extend(defaults, options);
var title;
getAjax();
return $this.each(function() {
if (options.done) {
options.done.call(undefined, title);
}
});
function getAjax() {
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/724793682641096478/posts/default/3551136550258768001",
dataType: "xml",
dataType: 'jsonp',
async: false,
success: function(xml) {
title = $(xml).find("title").text();
}
});
}
};
})(jQuery);
sorry, I have spent ages trying to figure it (I didn't ask out of laziness :P), regardless here's the solution for those interested :)
(function($) {
$.fn.getPost = function(options) {
var $this = $(this);
var defaults = {
method: "html",
done: null
};
var options = $.extend(defaults, options);
var title;
var sorf;
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/724793682641096478/posts/default/3551136550258768001",
dataType: "xml",
dataType: 'jsonp',
success: function(xml) {
title = $(xml).find("title").text();
sorf = 1;
},
error: function(){
sorf = 0;
},
complete: function() {
returnvals(sorf);
}
});
function returnvals(sorf) {
if(sorf){
//success
return $this.each(function() {
if (options.done) {
options.done.call(undefined, title);
}
});
}else{// failure}
}
};
})(jQuery);