jQuery ajax collision issue - javascript

I have been coding an ajax request and i have a problem with it.
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
//var formData = $(addonUploadForm).serialize();
//var formData = new FormData($(this)[0]);
var formData = new FormData($('#addonUploadForm')[0]);
$.ajax({
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
xhr: function() { },
cache: false,
contentType: false,
processData: false // marked line of error
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});
That is my code and on the marked line there is a missing , and this code works fine apart from doesnt display the request on the page and it instead just takes me to the ajax url but if i put the , in it does nothing when i submit the form no errors, no nothing.

Probably this line causes the error:
xhr: function() { },
without an xhr object you cannot send an ajax request.
So leave out this line.
Also you need to put the "," in at your marked line.
Your url opens because if you leave out the "," the function will throw an error and your e.preventDefault() won't work.
Also I would leave out these lines:
contentType: false,
processData: false
And you should probably escape the html content in this line:
$(addonUploadFormMessages).html(data.responseText);
Hope this helps.

I fixed it i had 2 versions of jquery runnning with noconflict and they where 1.11 and 1.4, and 1.4 was last loaded before this. So i had to change my no conflict to var jq1 = jQuery.noConflict(true); and then my ajax code to
var addonUploadForm = $('#addonUploadForm');
var addonUploadFormMessages = $('#addonUploadForm-messages');
$(addonUploadForm).submit(function(e) {
e.preventDefault();
var formData = new FormData($('#addonUploadForm')[0]);
jq1.ajax($(addonUploadForm).attr('action'), {
type: 'POST',
url: $(addonUploadForm).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
$(addonUploadFormMessages).removeClass('error');
$(addonUploadFormMessages).addClass('success');
$(addonUploadFormMessages).html(response);
$('#addonTitle').val('');
$('#addonDescription').val('');
$('#addonFile').val('');
grecaptcha.reset();
},
error: function(data) {
$(addonUploadFormMessages).removeClass('success');
$(addonUploadFormMessages).addClass('error');
grecaptcha.reset();
if (data.responseText !== '') {
$(addonUploadFormMessages).html(data.responseText);
} else {
$(addonUploadFormMessages).html('<div class="alert alert-danger fade in out">×<strong>Error!</strong> An error occured and your message could not be sent.</div>');
}
}
});
});

Related

Submitted URI too large - using POST method

I am submiting a ajax request using POST method and I had got the error 414: Submitted URI too large
I had already search a possible solution to my issue but I could not resolve the issue.
There is my ajax request:
$('form[name=editClinic]').submit(function(e) {
e.preventDefault();
var url = "includes/news.php";
var form1 = $('#editClinic');
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: url,
data: formData,
async: true,
success: function (data) {
var response = data.split("||");
if(response[0] == "true"){
$.notify(response[1],"success");
}
},
error: function(chr, desc, err){
$.notify(response[1],"error");
},
cache: false,
contentType: false,
processData: false
});
});
The URL that is creted is the following one:
http://localhost/Repositories/som/administrador/noticias-editar.php?countryBanner=1&datepicker=1969-12-31+04%3A00+PM&highlight=1&typeBanner=Small&category=Tips&editor=FAMO%3ASWISS&og_img=57&title_US_EN=How+to+choose+the+right+chair%3F&subTitle_US_EN=Find+out+the+right+one+for+you.&desc_US_EN=%3Cp%3EWorking+in+an+office+usually+involves+spending+a+lot+of+time+sitting+in+a+chair.+So+how+can+you+choose+the+right+one+for+you%3F%3C%2Fp%3E%3Cp%3EThe+number+of+people+working+in+offices+is+growing.+Most+of+them+will+spend+a+whole+day+sitting+in+a+chair%2C+working+in+front+of+a+computer+screen.%3C%2Fp%3E%3Cp%3EHowever%2C+this+position+is+detrimental+to+your+health.+Back+problems+arising+from+the+amount+of+time+spent+in+that+position+has+become+a+common+complaint.%3Cbr%3E%3C%2Fp%3E%3Cp%3EHow+can+you+avoid+such+problems%3F%3Cbr%3E%3C%2Fp%3E%3Cp%3ETo+avoid+the+emergence+of+back+problems%2C+preventive+action+must+be+taken.+One+form+of+action+is+to+be+careful+with+your+posture.+But+equally+important+is+the+choice+of+an+ergonomic+chair%3B+it+should+respond+to+the+demands+of+your+body+and+spine%2C+and+supports+and+promotes+good+posture.%3Cbr%3E%3C%2Fp%3E%3Cp%3EWhat+features+should+the+chair+have%3F%3Cbr%3E%3C%2Fp%3E%3Cp%3E1.+It+should+be+adjustable+%E2%80%93+In+terms+of+sitting+height%2C+arm+length%2C+and+inclination%2C+among+others.+The+greater+the+adjustment+options%2C+the+greater+the+likelihood+that+it+will+be+compatible+to+your+needs.%3Cbr%3E%3C%2Fp%3E%3Cp%3E2.+Keep+back+support+in+mind%E2%80%93+If+you+spend+many+hours+sitting%2C+it+is+important+that+the+chair+accommodates+the+curvature+of+your+spine.%3Cbr%3E%3C%2Fp%3E%3Cp%3E3.+Take+upholstering+into+account+%E2%80%93+The+material+of+the+chair+should+be+sufficiently+padded+to+be+comfortable+for+long+periods+of+time.+A+leather+covering+is+more+resistant+but+a+covering+in+fabric+is+healthier+because+it+breathes+better.%3Cbr%3E%3C%2Fp%3E%3Cp%3E4.+Try+different+chairs+%E2%80%93+Don%E2%80%99t+just+read+about+features+of+the+chair+before+you+buy+it.+It+is+important+to+actually+try+out+various+chairs%2C+sitting+in+them%2C+to+see+which+best+suits+your+needs.%3Cbr%3E%3C%2Fp%3E%3Cp%3ESo+now+the+next+time+you+need+to+buy+one+you+know+how+to+choose+the+best+one+for+your+health.%3C%2Fp%3E&idTrans_US_EN=37&title_US_ES=%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F&subTitle_US_ES=Encuentra+el+m%C3%A1s+adecuado+para+ti.&desc_US_ES=%3Cp%3ETrabajar+en+una+oficina+es+una+tarea+que%2C+normalmente%2C+requiere+pasar+mucho+tiempo+sentado+en+una+silla.+%C2%BFExiste+alguna+forma+para+elegir+la+silla+m%C3%A1s+adecuada+para+usted%3F%3C%2Fp%3E%3Cp%3E%C2%A0En+los+d%C3%ADas+de+hoy%2C+el+n%C3%BAmero+de+personas+que+trabajan+en+oficinas+ha+crecido.+La+mayor%C3%ADa+de+ellas+pasa+el+d%C3%ADa+entero+sentadas+en+una+silla%2C+trabajando+delante+de+una+pantalla.%3C%2Fp%3E%3Cp%3ESin+embargo%2C+%C3%A9sta+es+una+posici%C3%B3n+que+no+es+muy+buena+para+su+salud.+Comienza+a+ser+frecuente+el+aparecimiento+de+problemas+en+la+columna+por+causa+del+tiempo+que+se+pasa+en+esta+posici%C3%B3n.%3Cbr%3E%3C%2Fp%3E%3Cp%3E%3Cb%3E%C2%BFSe+pueden+evitar+estos+problemas%3F%3Cbr%3E%3C%2Fb%3E%3C%2Fp%3E%3Cp%3EPara+evitar+el+aparecimiento+de+estos+problemas%2C+deben+tomarse+algunas+actitudes+preventivas.%C2%A0+Una+de+ellas+es+tener+cuidado+con+su+postura.+Pero+tambi%C3%A9n+es+muy+importante+la+elecci%C3%B3n+de+una+silla+ergon%C3%B3mica.+Una+silla+capaz+de+responder+a+las+exigencias+de+su+cuerpo+y+de+su+columna%2C+y+adem%C3%A1s+que%C2%A0+le+ofrece+el+soporte+y+promueve+una+buena+postura.%3Cbr%3E%3C%2Fp%3E%3Cp%3E%3Cb%3E%C2%BFC%C3%B3mo+debe+ser+su+silla%3F%3Cbr%3E%3C%2Fb%3E%3C%2Fp%3E%3Cp%3E1.+Debe+permitir+ajustarse+a+su+medida+%E2%80%93+a+su+altura+del+asiento%2C+de+los+brazos%2C+la+inclinaci%C3%B3n%2C+entre+otros.+Cuanto+mayor+sea+la+posibilidad+de+los+ajustes%2C+mayor+es+la+probabilidad+de+que+sea+compatible+con+sus+necesidades.%3Cbr%3E%3C%2Fp%3E%3Cp%3E2.+Tenga+en+cuenta+el+soporte+para+su+espalda+%E2%80%93+si+pasa+muchas+horas+sentado%2C+es+importante+que+la+silla+acompa%C3%B1e+la+curvatura+de+su+columna.%3Cbr%3E%3C%2Fp%3E%3Cp%3E3.+Tenga+en+cuenta+el+material+%E2%80%93+el+material+de+la+silla+debe+tener+la+consistencia+suficiente+para+ser+c%C3%B3moda+durante+largos+periodos+de+tiempo.+El+revestimiento+en+piel+es+m%C3%A1s+resistente%2C+pero+en+tela+es+m%C3%A1s+saludable+porque+permite+una+mejor+transpiraci%C3%B3n.+%3C%2Fp%3E%3Cp%3E4.+Experimente%2C+pruebe+diferentes+sillas+%E2%80%93+no+lea+apenas+las+caracter%C3%ADsticas+de+la+silla+antes+de+comprarla.+Es+importante+sentarse+en+diferentes+sillas+para+saber+cu%C3%A1l+es+la+que+mejor+se+adapta+a+sus+necesidades.%3C%2Fp%3E%3Cp%3ELa+pr%C3%B3xima+vez+que+tenga+que+comprar+una+silla%2C+ya+sabe+c%C3%B3mo+elegir+la+que+es+mejor+para+su+salud.%3Cbr%3E%3C%2Fp%3E&idTrans_US_ES=38&title_US_PT=%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F&subTitle_US_PT=%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F&desc_US_PT=%3Cp%3E%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F%3Cbr%3E%3C%2Fp%3E&idTrans_US_PT=39&cmdEval=editNews&idNews=16&bot=
Can anyone help me?

AJAX call gets a “400 bad request”

I am new to jquery, i am getting 400 bad request (i find in browser console).
$("form#upload").submit(function(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var formData = new FormData($(this)[0]);
$.ajax({
url : '/uploadController/upload',
type: 'POST',
data: formData,
async: false,
beforeSend: beforeSendHandler,
success: function (data) {
var msg=data.msg;
var obj=data.obj;
if(data.success == true)
{
$('#successmsg').html(msg);
$('.alert-success').show();
$('.alert-danger').hide();
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
}else {
$('#errmsg').html(msg);
$('.alert-danger').show();
$('.alert-success').hide();
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
POST url 400(Bad Request)
Here console showing in error $.ajax({ line on my js file.
But it working on some systems, i don't what is the problem.
Anyone has some ideas?? Thanks a lot.
Since you are using jQuery, you can get serialized you form with this line:
var formData = $(this).serialize()
Use this formData in the ajax and it should work (assuming the relative URL to post is correct)

Abort ajax file uploading

I need to implement AJAX file uploading interruption by click on cancel button.
Here's code which I'm trying to use:
var reqx=null;
function ajax_upload(){
reqx = $.ajax({
type: 'post',
url: "/file.php",
data: new FormData( $('#file')[0] ),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("success");
},
error: function (data) {
console.log("error");
}
})
}
$('input[type=file]').change(function () {
ajax_upload();
});
$('#cancel').click(function(){
if (reqx != null){
reqx.abort();
reqx = null;
}
});
Clicking on Cancel button causes an error:
Uncaught TypeError: reqx.abort is not a function
Need help to find out mistake in my code. Thanks.
IIRC your looking for resolve(). http://api.jquery.com/deferred.resolve/ It causes the deferred to immediately complete and process any done logic.

ajax form submit redirect like a not ajax form

I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});

jQuery does not work in IE11, but works in Chrome

I have problem with jQuery. When I upload image in Chrome it performs the AJAX successfully and I am able to update the page with the response data. But in IE 11 and Firefox it does not. The code:
$(".newfoto").on('submit', (function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
e.preventDefault();
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#mailresult").html(data);
setTimeout(function() {
$("#mailresult").empty();
}, 2000);
var imgTag = '<img src="image.php?imgid=' + escape($('.myphoto').attr('id')) + '" />';
$('.myphoto').html(imgTag);
},
error: function() {}
});
}));
The correct way to prevent the form from submitting and reloading the page is to use a return false; at the end of the submit function. This will also replace e.preventDefault(); in your code.
Also, FormData is not supported on all browsers. See https://stackoverflow.com/a/2320097/584192. You may need to detect and workaround this.
$(".newfoto").on('submit', function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: (typeof FormData === 'function') ? new FormData(this) : $(this).serialize(),
contentType: false,
cache: false,
processData: false,
success: function(data) {
// success
},
error: function(jqXHR, status, error) {
console.log(error);
}
});
return false;
});

Categories