I'm struggling with formData in Ajax calls. I read everything I could with the same information, tried get the form with this, getElementById and nothing works (even tried several solutions from SO).
I have a form with id add-lang-form:
<form class="js-validation-addlang" method="post" enctype="multipart/form-data" id="add-lang-form" name="add-lang-form">
<div class="form-group row">
<label class="col-6 col-form-label">Language Name</label>
<label class="col-6 col-form-label">Language Code</label>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="lang_name" name="lang_name">
<span class="input-group-addon"><i class="fa fa-file"></i></span>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="lang_code" name="lang_code">
<span class="input-group-addon"><img src="/assets/img/flags/def.png" id="flag-icon"/></i></span>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-12" for="lang_tags">Language Tags</label>
<div class="col-lg-12">
<div class="input-group">
<input type="text" class="form-control" id="lang_tags" name="lang_tags">
<span class="input-group-addon"><i class="fa fa-list"></i></span>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-12">Image</label>
<div class="col-md-12">
<input type="file" id="lang_img" name="lang_img" class="dropify" />
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<button type="submit" class="btn btn-alt-primary pull-right">Submit</button>
</div>
</div>
</form>
And I have a function that is called after form validation with submitHandler:
function AddLang(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var form = document.getElementById('add-lang-form');
var formData = new FormData(form);
$.ajax({
url: 'PHP_FILE',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: {
dados: formdata,
caller: 'addlang',
},
type: 'POST',
beforeSend: function() {
$("#login_btn").html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$("#login_btn").attr("disabled", true);
},
success: function(output) {
if (output == "OK") {
alert("OK");
} else {
alert(output);
}
}
});
};
I tried creating the formData directly, everything and nothing works.
The $_POST['dados'] is not set. Any clue of whats going on?
you can't use a FormData object as the value of a parameter, it has to be the entire data: value. If you want to add additional parameters, use FormData.append().
function AddLang(e) {
//var data = $("#add-lang-form").serialize();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var form = document.getElementById('add-lang-form');
var formData = new FormData(form);
formData.append('caller', 'addlang');
$.ajax({
url: 'PHP_FILE',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: formData,
type: 'POST',
beforeSend: function() {
$("#login_btn").html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$("#login_btn").attr("disabled", true);
},
success: function(output) {
if (output == "OK") {
alert("OK");
} else {
alert(output);
}
}
});
};
Related
I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
my html code is :
I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
<ul name="ali" id="singleFieldTags" class="tagit ui-widget ui-widget-content ui-corner-all">
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">reza</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">ali</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-new">
<input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off">
</li>
</ul>
<form id="form" method="post" action="/save_new" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="choose-file" class="custom-file-upload" id="choose-file-label">
Click Here to upload image
</label>
<br/>
<br/>
<label >no image selected !</label>
<input name="uploadDocument" type="file" id="choose-file"
accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
</div>
<div class="form-group">
<label for="title">Description</label>
<textarea name="meta_description" class="form-control"></textarea>
</div>
<div class="form-group">
<label >keywords</label>
<input name="tags" id="mySingleField" value="reza,ali" type="hidden" disabled="true">
<ul name="ali" id="singleFieldTags"></ul>
</div>
<button type="submit" onclick="myF()" class="btn btn-success pull-left"> save</button>
</form>
in my javascript
<Script type="text/javascript">
function myF() {
var data2 = [];
var inputs = $(".tagit-choice");
for (var i = 0; i < inputs.length; i++) {
data2[i] = $(inputs[i]).text();
}
$.ajax({
url:'/save_new',
type: 'POST',
dataType:'json',
// data: JSON.stringify(data2),
data: JSON.stringify(data2),
contentType: 'application/json; charset=utf-8',
success: function( data ){
console.log('ok');
console.log(data);
},
error: function (xhr, b, c) {
console.log('error');
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
}
when i send data from ajax i have error in console
error reza:263:37
xhr=[object Object] b=error c=
but in Request JSON
i see
0 "reza×"
1 "ali×"
Please help me Thanks
my controller is :
public function save_new(Request $request){
// dd($request->all());
dd($request->getContent());
}
my route is :
Route::POST('/save_new','Backend\AdminPostController#save_new')->name('save_new');
edit:
my problem is solved thans you all
var fd = new FormData();
var file = $("#form input[name=uploadDocument]")[0].files;
fd.append('file', file[0]);
fd.append('title', $("#form input[name=title]").val());
fd.append('description', $("#form textarea[name=meta_description]").val());
fd.append('tags', JSON.stringify(data2));
$.ajax({
type: 'post',
url: '/ok2',
contentType: false,
processData: false,
data: fd,
success: function(response) {
},
error: function (response) {},
});
I'm not sure about your work but this is one of the basic method to send data via jquery make sure to put ajaxSetup in document.ready function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#form').on('submit',function(){
$.ajax({
type:'post',
url:$("#form").attr('action'),
data:$("#form").serializeArray(),
success:function(data){
//response
console.log(data);
}
});
});
//Here is my multipart/form-data form
<form id="addNewRoomForm" enctype="multipart/form-data">
<div class="form-group">
<label for="room_title">Room Title</label>
<input type="text" class="form-control" id="room_title" name="room_title" placeholder="Enter Room Title">
</div>
<div class="form-group">
<label for="room_category">Room Category</label>
<select class="form-control" id="room_category" name="room_category">
<option value=""></option>
<option value="1">Standard Room</option>
<option value="2">Family Room</option>
</select>
</div>
<div class="form-group">
<label for="room-images">Room Images</label>
<div class="input-images"></div><!--Here im using image-uploader.js Plugin By Christian Bayer-->
</div>
<div class="form-group">
<label for="room_description">Room Description</label>
<textarea class="form-control" id="room_description" name="room_description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success btn-icon-split" id="addRoomBtn">
<span class="icon text-white-50">
<i class="fas fa-arrow-right"></i>
</span>
<span class="text">Add Room</span>
</button>
</form>
//Here is my ajax form submission for the above form which is working fin
$("#addNewRoomForm").on('submit', function(e){
var process_url = "<?php echo base_url();?>";
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: process_url + 'admin/rooms/process_add_room',
data: formData,
// dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
alert("sending...");
},
success: function(msg){
alert(msg)
}
});
});
// but when I using the same code inside the jquery-validation.js submitHandler function, it is showing the "message : Undefined_index: room_title" in alert function. below are the codes showing error:
$('#addNewRoomForm').validate({ // initialize the plugin
rules: {
room_title: {
required: true,
},
room_category: {
required: true,
}
},
messages: {
room_title: {
required: "Please Enter Room Title",
},
room_category: {
required: "Select Room Category",
}
},
highlight: function (input) {
console.log(input);
$(input).addClass('is-invalid');
},
unhighlight: function (input) {
$(input).removeClass('is-invalid');
},
errorPlacement: function (error, element) {
// $(element).parents('.input-group').append(error);
$(element).parents('.form-group').append(error);
},
submitHandler: function (form) {
var process_url = "<?php echo base_url();?>";
// e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: process_url + 'admin/rooms/process_add_room',
data: formData,
// dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
alert("sending...");
},
success: function(msg){
alert(msg)
}
});
return false;
}
});
I want to submit the multipart/form-data with jquery-validation. I've tried all the ways now want your help.
I'm trying to save a data using ajax
this is my global function for api's, I'm using this global function even in show of data to table.
ajax = (action, data, method, callback) => {
return $.ajax({
type: method,
// url: `https://dev2.bliimo.net/${action}`,
url: `http://localhost:8080/${action}`,
contentType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", `Bearer ${gon.global.currentUser.access_token}`);
},
data: { data: data },
async: !1,
cache: false,
error: e => {
console.log(e.responseText);
console.log("Error occured");
}
});
};
when i click the "add new catalog" button, the modal appears,
inside the modal there is a form
Now, this is the form:
<form id="add-new-catalog-form" class="uk-form-stacked" method="post">
<div class="uk-grid uk-margin-remove uk-padding-remove uk-width-1-1">
<div class="uk-width-1-3 uk-padding-remove">
<div>
<div class="uk-margin">
<label class="uk-form-label uk-text-bold" for="add-catalog-name">Catalog Name</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-medium category-input" id="add-catalog-name" type="text" autocapitalize="words" placeholder="Catalog Name" />
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label uk-text-bold" for="iconimg-output">Icon Image</label>
<%= image_tag('', id: 'iconimg-output')%>
<div class="js-upload" uk-form-custom>
<button class="uk-button uk-button-default upload-cloudinary-icon" type="button" tabindex="-1">UPLOAD</button>
</div>
</div>
</div>
</div>
<div class="uk-width-2-3 uk-margin-remove uk-padding-remove">
<div class="uk-grid uk-width-1-1 uk-margin-remove uk-padding-remove">
<div class="uk-width-1-2 uk-margin-remove uk-padding-remove">
<label class="uk-form-label uk-text-bold" for="landingpageimg-output">Landing Page Image</label>
<%= image_tag('', id: 'landingpageimg-output')%>
<div class="js-upload" uk-form-custom>
<button class="uk-button uk-button-default upload-cloudinary-landing" type="button" tabindex="-1">UPLOAD</button>
</div>
</div>
<div class="uk-width-1-2 uk-margin-remove uk-padding-remove">
<label class="uk-form-label uk-text-bold" for="categorypageimg-output">Catalog Cover Image</label>
<%= image_tag('', id: 'categorypageimg-output')%>
<div class="js-upload" uk-form-custom>
<button class="uk-button uk-button-default upload-cloudinary-category" type="button" tabindex="-1">UPLOAD</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="uk-modal-footer uk-text-right">
<button class="uk-button uk-button-default uk-modal-close" type="button">Cancel</button>
<button class="uk-button uk-button-primary" type='submit'>Save</button>
</div>
</form>
when I click the save button in the modal, it will run this function
This is my submit function:
$('#add-new-catalog-form').on('submit', e => {
let catalog_name = $('#add-catalog-name').val();
let catalog_icon = $("#iconimg-output").attr('src');
let catalog_landing_image = $('#landingpageimg-output').attr('src');
let catalog_cover_image = $('#categorypageimg-output').attr('src');
let data = `name=${catalog_name}&thumbnail=${catalog_icon}&landingPageImage=${catalog_landing_image}&coverImage=${catalog_cover_image}`;
ajax("api/catalogs", `${data}`, "POST");
});
it says "Invalid mime type \"json\": does not contain '/'","code":500"
how to solve this?
dataType and contentType are not the same:
dataType: "json",
contentType: "application/json; charset=utf-8",
...
Done!
$('#add-new-catalog-form').on('submit', e => {
e.preventDefault();
let catalog_name = $('#add-catalog-name').val();
let catalog_icon = $("#iconimg-output").attr('src');
let catalog_landing_image = $('#landingpageimg-output').attr('src');
let catalog_cover_image = $('#categorypageimg-output').attr('src');
let data = { "name": catalog_name, "thumbnail": catalog_icon, "landingPageImage": catalog_landing_image, "coverImage": catalog_cover_image };
ajax("api/catalogs", JSON.stringify(data), "POST");
window.location.replace("/catalog");
});
I'm facing error on Upload xml and upload csv am a rookie so please can you provide me a elaborate answer
I've tried debugging the code on clicking upload button till upload function is working fine on jumping to uploadxml() function the data is not sent.
My HTML code
<div class="file-upload">
<form id="file-upload-form">
<div class="upload">
<div class="col-lg-6">
<div class="input-group" id="one">
<input type="text" class="form-control" id="t1" placeholder="Select an xml file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="xmlbtn">Browse</button>
</span>
</div>
<input type="file" accept=".xml" class="hidden" id="xmlPicker" name="xmlFile"/>
</div>
<div class="col-lg-6">
<div class="input-group" id="two">
<input type="text" class="form-control" id="t2" placeholder="Select an csv file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="csvbtn">Browse</button>
</span>
</div>
<input type="file" class="hidden" accept=".csv" id="csvPicker" name="csvFile"/>
</div>
</div>
<div class="uploadfooter">
<button class="btn btn-default center" type="button" id="upload">Upload</button>
</div>
</form>
</div>
My Js
$(document).ready(function () {
$(".ts-sidebar-menu li a").each(function () {
if ($(this).next().length > 0) {
$(this).addClass("parent");
};
})
var menux = $('.ts-sidebar-menu li a.parent');
$('<div class="more"><i class="fa fa-angle-down"></i></div>').insertBefore(menux);
$('.more').click(function () {
$(this).parent('li').toggleClass('open');
});
$('.parent').click(function (e) {
e.preventDefault();
$(this).parent('li').toggleClass('open');
});
$('.menu-btn').click(function () {
$('nav.ts-sidebar').toggleClass('menu-open');
});
$('#zctb').DataTable();
$("#input-43").fileinput({
showPreview: false,
allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
elErrorContainer: "#errorBlock43"
// you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
$("#xmlbtn").bind("click", function(){
$("#xmlPicker").trigger("click");
});
$("#xmlPicker").bind("change", function(e){
$("#t1").val($("#xmlPicker")[0].files[0].name);
})
$("#csvbtn").bind("click", function () {
$("#csvPicker").trigger("click");
});
$("#csvPicker").bind("change", function (e) {
$("#t2").val($("#csvPicker")[0].files[0].name)
})
$("#upload").on("click",function () {
var firstfile = $("#t1").val();
var secondfile = $("#t2").val();
if(!firstfile || firstfile != null){
updateXml();
}
if(!secondfile || secondfile != null){
updatecsv();
}
})
function updateXml(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
function updatecsv(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
});
This line here:
var form = $("#file-upload-form").val()
A form does not have a value, its inputs have one. FormData expects a form, so you need to give it a reference to it.
var form = $("#file-upload-form");
var data = new FormData(form[0]); //expects a DOM form
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i'm new in asp MVC so I will try to make a login form with ajax so i write jsonresult to check the username and password in the controller and i call it in ajax but it's not working and i don't know why so that's my controller code
public ActionResult login()
{
return View();
}
[HttpPost]
public JsonResult ValidateUser(string username,string password)
{
using(var contxt=new EnglisCenterEntities())
{
var data = from a in contxt.Employee
where a.Username == username && a.Passwords == password
select a;
if(data.Count()>0)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
}
and this is my view and ajax code
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 alert alert-warning">
<h2 class="text-center">Login</h2>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<button class="btn btn-warning form-control" type="submit" id="savedata"><i class="glyphicon glyphicon-log-in"></i> Login</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#savedata').click(function () {
var data = {
"username": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/ValidateUser",
type: "Post",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Index", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Login", "Account")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
</script>
Why it's not working ? any help please
There is no need of JSON.stringify, modify your ajax call data as shown :-
$.ajax({
url: "/Account/ValidateUser",
type: "Post",
data: data,
dataType: "json",
.....
});