JQuery AJAX post issue while uploading the EXCEL file - ajax

My code snippet is below
function uploadFile(file, action){
var fd = new FormData();
fd.append('file_data', file);
$.ajax({
type: 'POST',
data: fd,
processData: false,
url: reload_url,
contentType: false,
async: false,
cache: false,
complete: function (xhr, status) {
if (status != 'success' ) {
console.log("Complete",xhr.response, status, file.name);
}
},
error:function(data){
console.log("Failed ",data);
alert("Failed to upload file");
},
timeout: 30000,
});
}
While I am posting the data with less file size(< 1MB) then it is working , But if the file is > 3MB then it is failing with error sig : net::ERR_CONNECTION_RESET
And the status response is : "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load
Can anybody please help on this issue.

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

Sending url using ajax on codeigniter

I have this Ajax script where I pass a link to the data variable link, but I
get a 412 error.
$(function() {
$(".check-multi").change(function() {
$.ajax({
type: "POST",
url: "<?php echo site_url('adm/updateproperty'); ?>",
async: true,
data: {
link: $(this).data('link')
},
success: function(msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
});
});
I have tried
link: encodeURI($(this).data('link'))
And
link: encodeURIComponent($(this).data('link'))
as is suggested on other threads but I still get the 412 error message.
Hope this will help you :
you have added newline character to json data that is why you got error
Do like this :
var link = $(this).data('link');
data: {"link" : link},
/*----OR do this -----*/
data: {"link" : $(this).data('link')},
instead of this :
data: {
link: $(this).data('link')
},
Whole code should be like this :
var link = $(this).data('link');
/*console.log(link)*/
$.ajax({
type: "POST",
url: "<?php echo site_url('adm/updateproperty'); ?>",
async: true,
data: {"link" : link },
success: function(msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
For More :https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412
Please change your code in data options. Use this way
data: {"id": ID},
i.e. store the value in a variable and send that variable in data option. If we assume
ID=$(this).data('link');`
Then the code will be as follows:
$(function() {
$(".check-multi").change(function() {
$.ajax({
type: "POST",
url: "<?php echo site_url('adm/updateproperty'); ?>",
async: true,
data: {"id":ID},
success: function(msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
});
});
Please check it.

Uploading file using AJAX request

I'm trying to upload a file using AJAX. I tried to do it using formData() object as well. How can I add a file to following Ajax request?
$.ajax({
url: '/api/add_new_pair/',
method: "POST",
type: 'POST',
FILES: {
'image' : file,
},
data: {
'csrfmiddlewaretoken': csrftoken,
'text': text,
},
}).done(function(response){
console.log(response);
}
You can access the multipart(multimedia) data(header along with data in base64 format) in request.FILES and other data in request.POST
var data = new FormData();
data.append('csrfmiddlewaretoken', '{{csrf_token}}');
data.append('image', $('#image-id').files[0]);
$.ajax({
type: "POST",
url: "/save_design/",
contentType: false,
data: data,
async: true,
cache: false,
processData: false,
beforeSend: function() {
},
success: function(t) {
},
complete: function() {
},
error: function(t) {}
}),
}

Refreshing a AJAX call

I have an AJAX call in cordova application.I have checked the availability of internet connection before actual call. But some times in mobile internet connectivity is lost for few seconds after the call is made and thus device does not read any reply from web-service. It goes to error part of Ajax call. I wants to make this Ajax call again so that DOM should get created
call AJAX function is
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if(isOnline == false)
{
alert('Internet is not running. Please reconnect and try');
return 0;
}
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
// alert(JSON.stringify(response));
errorFunction(response);
}
});
}
If you want to retry after an error, you can just re-call your function recursively, or do something like this to prevent too many retries:
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if (isOnline == false) {
alert('Internet is not running. Please reconnect and try');
return 0;
}
function tryAjax(retryCount) {
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
if (retryCount > 10) {
errorFunction(response);
} else {
tryAjax(retryCount + 1);
}
}
});
}
tryAjax(0);
}

File not getting uploaded at server

I am getting this following error. i am trying to upload the file to the server.can somebody please suggest something
Error - Failed to load resources: The server responded with a status of 405 method not allowed
</article>
<script>
function sendFileToServer(formData,status)
{
var uploadURL ="http://localhost/upfile/file/"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);
$("#status1").append("File upload Done<br>");
}
});
status.setAbort(jqXHR);
}
contentType: 'multipart/form-data',
processData: false,
type: 'POST'
make sure you check your contentType

Resources