Blueimp multiple fileupload response parsing is wrong - ajax

I have a problem with blueimp multi upload after files are getting uploaded.
When the table is getting repopulated on ajax response than in the table I have for all uploaded files the same delete link and thumbnail. If I reload the page than everything is ok.
Checking under network the response I see that for all checked images comes back the response separatly, but my server sends already uploaded images in a json
here is my code
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
xhrFields: {withCredentials: true},
url: '/documents/users/' + $('#profile-data').data('user-id'),
dataType: 'json',
context: $('#fileupload')[0],
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
}
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
//here I get the response
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
How can be fixed this bug?

Related

csrf-token mismatch error in laravel on server

I'm using this code to submit data through ajax in laravel
$('#submit').submit(function (e) {
e.preventDefault();
let formData = new FormData(this);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
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);
if (percentComplete === 100) {
}
}
}, false);
return xhr;
},
url: $(this).attr('action'),
type: "POST",
data: formData,
dataType:'JSON',
contentType:false,
cache: false,
processData: false,
but getting csrf token mismatch when i upload my code on live server.
Any solution is highly appreciated Thanks
I see you are fetching the token from the HTML page metatag, make sure your HTML page is not being cached by an intermediate/browser between accesses (try opening with two different browsers and checking the token, refreshing with f5 and force reloading too).
Another common issue is multiple HTML pages being loaded simultaneously (frames? maybe a 404 file that returns your default page, refreshing the token for your session). This is hard to find, check the network tab of your browser dev tools and inspect each response.
I don't think it's the case, but sometimes the case makes difference X-CSRF-Token if a proxy is "cleaning up non whitelisted headers".

Laravel cant submit ajax forms appended by javascript

I have implemented infinite scroll that appends html in the exact same manner as the static item with forms (inclusive csrf), but the dynamic forms that has been appended seems to be submitting without ajax and failing when pressing the submit button.
I get this error on the appended forms in console log:
Resource interpreted as Document but transferred with MIME type application/json:
The ajax submit.
$('.cart_add').on('submit',function (event) {
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data) {
console.log("item has been added to cart");
event.preventDefault();
}
});
});
Edit I noticed that the jquery doesn't select the dynamically appended forms
Try setting your content type. The content type is the type of data sent to the server. In this case, you are sending data to the server which is interpreted as a Document (html) but is sent as json. This is because the browser is trying to infer what type of data your are sending becuase you did not explicitly state it.
Use the contentType to set it.
contentType: "text/html"
So your call should look like this:
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: "text/html",
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data) {
console.log("item has been added to cart");
event.preventDefault();
}
});

Error in ajax retrieving data

I wanted to retrieve data using ajax, when open the url in browser it showing data but when i execute this url in ajax code error msg function is running however data is showing in browser.
url: "http://live.nayatel.com/?json=1"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://live.nayatel.com/?json=1",
cache: false,
success: onSuccess,
error: onError
});
});
its a wordpress site and i used a plugin to retrive its data working in browser but not giving response text.
I have two suggestions, since I am not that sure about your problem.
a) Try changing
success: onSuccess,
to
success: function(data, status) {
onSuccess(data, status);
},
b) If that fails, try adding
crossDomain: true,

How to include header in ajax request?

I need to include a header with a refresh token in an ajax call to the YouTube api. I am trying to send a delete request, to delete a movie I have on my account. This is my ajax call that fire on button click
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your requst');
}
});
I am receiving a 401 (unauthorized) erorr on return and it seems that I need to include my access token in the call. I was playing around with the google api playground looking at the request and response and this is what shows as the 'Request' being sent out
DELETE https://www.googleapis.com/youtube/v3/videos?id=3242343&key={YOUR_API_KEY}
Authorization: Bearer "access token"
X-JavaScript-User-Agent: Google APIs Explorer
Now from that request it looks like the there are headers that are being sent with the request, which hold the access token. This must be why I am getting a 401 error. How can I include those headers into my ajax request, so that my access token is passed along with the request? Thanks
I was able to pass along a header using this code below:
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID +'&key=api_key_here',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer access_token_here');},
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your request');
}
});
You can use beforeSend method and request.setRequestHeader. Take a look at the official documentation here.
P.S. should I post it as a comment?
Try add the paramenter data.
jQuery.ajax({
type: 'DELETE',
data: 'key=' + {YOUR_API_KEY},
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your requst');
}
});

Ajax request data is cached

I have an ajax function that loads within a setInterval as follow :
setInterval(function(){updateChart()}, 5000);
var updateChart = function(){
$.ajax({
url: './script.php',
type: 'post',
dataType: 'json',
cache: false,
data: {'candlesData':candlesData},
success: function(data) {
//alert(data);
//console.log("two");
//console.log(data);
gotData(data);
delete data;
delete candlesData;
},
error: function(xhr, desc, err) {
//console.log(xhr);
//console.log("Details: " + desc + "\nError:" + err);
}
}).done(function() {
});;// end ajax call
}
My browser memory gets SIGNIFICANTLY bigger over time. I tried to diagnose and found out that the POST request in the AJAX data (candlesData) is cached everytime... You can see this in the screenshot (retained data column).
I tried everything to clear the cache but it is not working.
Snapshot of retained data
I fixed this problem.
And I confirm that ajax post doesn't store cache...
The problem was that I had a javascript object which was recreated every time with setInterval function. I used :
objectName.destroy()
that get triggered everytime it reload the function and it resolved the problem.

Resources