I need to send my Front-end data to my server. To do that I create code something like this. But I can't find out send my data to the server using ajax (multipart/form-data)
My HTML Part -
<form id="frmCustomer">
<div>
<label class="form-label" for="customerID">Customer ID</label>
<input class="form-control" id="customerID" name="id" type="text">
</div>
<div>
<label class="form-label" for="customerName">Customer Name</label>
<input class="form-control" id="customerName" name="name" type="text">
</div>
<div>
<label class="form-label" for="customerAddress">Customer Address</label>
<input class="form-control" id="customerAddress" name="address" type="text">
</div>
<div>
<label class="form-label" for="customerSalary">Customer Salary</label>
<input class="form-control" id="customerSalary" name="salary" type="text">
</div>
<div class="form-group">
<label for="inputNICImageCreateAccount"> <i class="tags icon"></i> Image Of Your NIC</label>
<input class="form-control-file" id="inputNICImageCreateAccount" type="file" name="file">
</div>
<div class="btn-group mt-3">
<button class="btn btn-primary" id="btnSave" type="button">Register Customer</button>
<button class="btn btn-info" id="btnSearch" type="button">Search</button>
<button class="btn btn-danger" id="btnRemove" type="button">Remove</button>
<button class="btn btn-warning" id="btnGetAll" type="button">Get All</button>
</div>
</form>
My Ajax Part -
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'multipart/form-data',
async: true,
data:,
success: function (data) {
console.log(data)
}
})
})
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
var data = new FormData();
data.append('customerID',customerID);
data.append('customerName',customerName);
data.append('customerAddress',customerAddress);
data.append('customerSalary',customerSalary);
data.append('NICImage',NICImage);
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'multipart/form-data',
async: true,
data:data,
processData: false,
success: function (data) {
console.log(data)
}
});
});
keys setting with FormData should match with your API endPoint parameter names.
to pass data in JSON format rather the Formdata,
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
var formData = {
customerID : customerID,
customerName : customerName,
customerAddress : customerAddress,
customerSalary : customerSalary
};
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'application/json',
async: true,
data : JSON.stringify(formData),
processData: false,
success: function (data) {
console.log(data)
}
});
});
type:'post',
url:url,
dataType:'json',
data:new FormData($('#frmCustomer')[0]),
processData: false,
contentType: false,
cache:false,
async:false,
Related
I am learning laravel, when I want to update an object and I use ajax to send data to update action with put method (routing also to set) but my update action side is not receiving it request that ajax send like so
! Code
<form id="formEdit" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="card-body">
<div class="form-group">
<label for="name">Name</label>
<input value="{{$role->name ?? ''}}" type="text" class="form-control" id="name" name="name" placeholder="Enter name">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="float-right btn btn-primary">Lưu lại</button>
</div>
</form>
```
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function sendAjax(url, formData, type, method = 'post'){
var result = $.ajax({
url: url,
method: method,
typeData: 'json',
data: formData,
processData: false,
contentType: false,
async: false
});
return resultAjax(result, type);
}```
```
<script>
$('#formEdit').submit(function(event){
event.preventDefault();
var eleValidate = ['name'];
var data = new FormData($('#formEdit')[0]);
var url = "{{route('role.update', $role->id)}}";
var result = sendAjax(url, data, 'edit', 'put');
if(result){
renderError(result, eleValidate);
}else{
removeError(eleValidate, 'formEdit');
}
});
</script>
```
Route::put('/role/update/{id}', 'update')->name('role.update');
public function update(Request $request, $id)
{
if($request->ajax()){
$role = RoleModel::find($id);
dd($request);
}
}
Payload
dd($request)
//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 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);
}
}
});
};
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