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)
Related
My web-application can only work with .xlsx-files. I created a function in my controller, which converts a .xls-file into an .xlsx-file. The conversion works totally fine. So whenever I try to open a .xls-file, I send it via Ajax request.
After that, I want to respond with the converted .xlsx-file, but it never arrives at the client.
Since the conversion works fine, i simplified the code, to just pass a simple .xlsx file, which didn't work aswell.
JavaScript:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
formData = new FormData();
formData.append("xlsfile", files[0]);
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: formData,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
Controller:
public IActionResult ConvertToXlsx(IFormFile xlsfile) {
//For simplification without conversion
//var xlsconverter = new XLSConverter();
//FileStreamResult response = xlsconverter.XLSConvert(xlsfile);
var path = $"wwwroot/temp/";
var filepath = Path.Combine(path, "test.xlsx");
MemoryStream x = new MemoryStream();
using(FileStream fs = System.IO.File.OpenRead(filepath)) {
fs.CopyTo(x);
}
return File(x, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
In the browser-network tab I get Status: net::ERR_CONNECTION_RESET
Am I missing a setting somewhere, which causes I simply can't respond with files?
If you want to pass file to action,try to use the following code:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: files[0],
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
And if you want to return file with content type,you can try to use:
public IActionResult ConvertToXlsx(IFormFile xlsfile)
{
return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
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?
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>');
}
}
});
});
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");
}
}
});
});
On submit button click,
I am passing a variable to sendmail.php.It's showing that contactname is undefined in php.
why is it happening ?
Here is my Code :
var name = document.getElementById('stream_cotactname').value;
alert(name);
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : "cotactname="+name+"file=" + formdata,
dataType: "jsonp",
contentType: false,
processData:false,
jsonp: "jsoncallback",
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
My Php File:
<?php
$name =$_POST['cotactname'];die("A".$name);
?>
ALL gone well,Thanks.
Now let my introduce my exact code:
<script type="text/javascript">
var formdata = false;
(function () {
var input = document.getElementById("uploaded_file");
formdata = false;
formdata = new FormData();
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}, false);
}());
</script>
HOw can I get the form data information in php (like we do as $_FILES)
If you are not using cross domain call then you can call ajax like this:
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : {cotactname:name},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
try to change your data sending for more https://api.jquery.com/jQuery.ajax/
data : {cotactname:name},
also try to check console for any error is post ok on that file or try with correct path of file
You are sending a string from ajax and getting value of variable.
Try this:
CHANGE
data : "cotactname="+name,
TO
data: {"cotactname" : name},