ajax upload multipart form data as json object - javascript

Here there are form data with image. I need to send whole image data through json object. Below I have mentioned the code. under the below method I could get whole data except logo. I need to send whole data at once
<form class="form-horizontal" id="companyData">
<fieldset>
<legend>Add Company</legend>
<div class="control-group">
<label class="control-label" for="code">Code</label>
<div class="controls">
<input id="code" name="code" type="text" placeholder="code" class="input-large">
</div>
</div>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input id="name" name="name" type="text" placeholder="Name" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label" for="logo">Logo</label>
<div class="controls">
<input id="logo" name="logo" class="input-file" type="file">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Admin Username</label>
<div class="controls">
<input id="username" name="username" type="text" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label" for="AdminPassword">Admin Password</label>
<div class="controls">
<input id="AdminPassword" name="AdminPassword" type="text" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label" for="submit"></label>
<div class="controls">
<button id="submit" name="submit" class="btn btn-primary">Save</button>
</div>
</div>
</fieldset>
</form>
here is my script
<script type="text/javascript">
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var formData = JSON.parse(JSON.stringify(jQuery('#companyData').serializeArray()));
$.ajax({
type: "POST",
url: "",
data: formData,
cache: false,
success: function (data) {
}
});
});
});
</script>

image is a problem while using json.stringify.Send the formdata object and append all the items into it. Try this
var imgFile = document.getElementById('logo');
var imgfileList = imgFile.files;
var formdata = new FormData();
if (imgfileList && imgfileList != null && imgfileList.length > 0) {
formdata.append(imgfileList[0].name, imgfileList[0]); or add the name
formdata.append('logofilename', imgfileList[0]);
}
var other_data = $('#companyData :input').serializeArray();
$.each(other_data, function (key, input) {
formdata.append(input.name, input.value);
});
$.ajax({
url: UrlRoot.SaveTeamInfo,
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function () {
}
});
Please remeber to add process data and content type to false as specified in the ajax call above.
try this is formdata is undefined'
if(typeof FormData == "undefined"){
var data = [];
data.push(imgfileList[0].name, imgfileList[0]);
}
else{
var data = new FormData();
data.append('data', JSON.stringify(inputData));
}
Use .push instead of .append for array

Related

I couldn't pass an img using ajax?

I'm trying to include a logo when adding a new airline, but I don't know how can I pass input with file type to the controller with ajax. I tried to use FormData(). I did not get any error, but the file was not passed to the controller I have looked at some questions similar to my problem, but I can't find a solution.
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Airline Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">country</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="country" name="country" placeholder="Enter Airline country" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Logo</label>
<div class="col-sm-12">
<input type="file" class="form-control" id="logo" name="logo" placeholder="Enter Airline Code" value="" required="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save" value="addNewBook">Save changes
</button>
</div>
</form>
ajax:
$('body').on('click', '#btn-save', function (event) {
event.preventDefault()
var id = $("#id").val();
var name = $("#name").val();
var country = $("#country").val();
let logo = new FormData(document.getElementById("addEditBookForm"));
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('admin/add-update-Airlines') }}",
data: {
id:id,
name:name,
country:country,
logo:logo,
},
contentType: false,
processData:false,
cache: false,
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
Swal.fire(
'Good job!',
'You clicked the button!',
'success'
)
}
});
});
Controller:
public function store(Request $request)
{
$newImgName = time() . '-' . $request->name . '.' .$request->logo->extension();
$request->logo->move(public_path('img'),$newImgName);
$Airline = Airline::updateOrCreate(
[
'id' => $request->id
],
$request->validate([
'name' => ['required', 'string', 'max:255'],
'country' => ['required', 'string', 'max:255'],
'logo' => ['required|mimes:ipg,png,jpeg|max:5048'],
]),
[
'name' => $request->name,
'country' => $request->country,
'logo' => $newImgName,
]);
return response()->json(['success' => true]);
}
First thing is csrf token not passing to ajax so change form as below.Also updated
<form action="{{ url('admin/add-update-Airlines') }}" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Airline Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">country</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="country" name="country" placeholder="Enter Airline country" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Logo</label>
<div class="col-sm-12">
<input type="file" class="form-control" id="logo" name="logo" placeholder="Enter Airline Code" value="" required="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save" value="addNewBook">Save changes
</button>
</div>
</form>
Then in ajax I have simplified for testing so you can modify according to your need
$(document).on('click', '#btn-save', function(e) {
e.preventDefault()
var url = $("#applicationForm").attr('action');
let myForm = document.getElementById('addEditBookForm');
let formData = new FormData(myForm);
$.ajax({
type:"POST",
url:url,
data: formData,
contentType: false,
processData:false,
cache: false,
dataType: 'json',
success: function(res){
}
});
});
Validation
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'country' => ['required', 'string', 'max:255'],
'logo' => ['required','mimes:ipg,png,jpeg','max:5048'],
]);
}

Ajax form with post method

The AJAX form does not want to work, it throws an error. I need it to work when a button is clicked and all data is refreshed.
<form name="form" id="form" class="form">
<div class="field">
<label for="input-kitId" class="label is-size-7 has-text-weight-light has-text-left">Order ID</label>
<div class="field">
<div class="control is-expanded">
<input type="text" id="input-kitId" class="home-form__input input is-danger" name="number" value="" placeholder="Order ID"/>
</div>
</div>
</div>
<div class="field">
<label for="input-firstName" class="label is-size-7 has-text-weight-light has-text-left">Email</label>
<div class="field"><div class="control is-expanded">
<input type="text" id="input-firstName" class="home-form__input input" name="email" value="" placeholder="Email"/>
</div>
</div>
</div>
<button type="submit" class="button is-midnightBlue">Generate Booking Reference</button>
</form>
<script type="text/javascript">
$("#form").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
crossDomain: true,
type: "POST",
url: 'https://www.harleymedic.co.uk/qrcodes/form.php',
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
});
</script>
Try to add a form method. Get or Post method
Ex: form method="post"

Formdata not getting populated

I currently have a webpage hitting a webservice to send multipart/form-data but somehow the fields are not getting appended into the formdata object. Could someone help me out ?
index.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Sample upload</title>
<script type="text/javascript" src="webjars/jquery/3.2.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
/>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#dataform')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/save",
data: data,
//http://api.jquery.com/jQuery.ajax/
//https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
</script>
</head>
<body>
<h1>SampleCardSubmit</h1>
<form id="dataform" method="POST" enctype="multipart/form-data">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Section I:To be filled by Partner</h4>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-sm-5 control-label">Partner Name:</label>
<div class="col-sm-5">
<input id="name" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Photograph of
applicant:</label>
<div class="col-sm-5">
<input id="photo" type="file" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner OLM ID:</label>
<div class="col-sm-5">
<input id="olmid" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner Mobile
Number:</label>
<div class="col-sm-5">
<input id="mobile" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner Email:</label>
<div class="col-sm-5">
<input id="email" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Disability:</label>
<div class="col-sm-5">
<select id="disabibilty" class="form-control">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Partner Company Name:</label>
<div class="col-sm-5">
<input id="company" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Name of Partner on
Company ID:</label>
<div class="col-sm-5">
<input id="nameoncard" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-sm-5">
<input id="btnSubmit" type="submit" class="btn btn-primary"/>
</div>
</div>
</div>
</div>
</form>
<h1>Ajax Post Result</h1>
<span id="result"></span>
</body>
</html>
Controller
#RestController
public class CardController {
#Autowired
private CardService cardService;
#RequestMapping(value="/save", method = RequestMethod.POST)
public ResponseEntity<?> multiUploadFileModel(#ModelAttribute Card card) {
cardService.saveCard(card);
return new ResponseEntity("Successfully uploaded!", HttpStatus.OK);
}
}
Model
#Entity
public class Card {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private Blob photo;
#Column(unique=true)
private String olmId;
private String mobileNumber;
private String email;
private String disability;
private String partnerCompany;
private String nameOnCompanyCard;
Request Payload on clicking the submit button is this:
------WebKitFormBoundary1NqBHFrbwUgHBc7g
Content-Disposition: form-data; name="CustomField"
This is some extra data, testing
------WebKitFormBoundary1NqBHFrbwUgHBc7g--
Comments regarding handling on the backend are also appreciated.
Help please!!
As provided in my comment, you had forgotten the "name" parameter in your <input>, <select>, etc.
This causes the fields and their data not to be added to the resulting POST (since the browser doesn't know what to do with it).
You can try this below logic by adding x-www-form-urlencoded in the header and adding your data as shown below. Let me know if it works out for you.
$.ajax({
type: "POST",
url: "/save",
headers: {
'Content-Type': 'appliation/x-www-form-urlencoded',
'Authorization': 'Basic VGV.... Uy' // Add authorization if required
},
data: {
"CustomField", "This is some extra data, testing",
..... // More attributes if any
},
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});

How I can send data from html Form, to a nodejs Server using Javascript only

this is my form in form.html,I have to do an ajax call type post
<div class= "container " >
<div class="form-group ">
<label for="id">Id</label>
<input type="text" class="form-control" id="id" >
</div>
<div class="form-group">
<label for="name">Nome</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="pwd">Prezzo</label>
<input type="text" class="form-control" id="prezzo">
</div>
<input type="submit" value="invia dati" class="btn btn-primary" id="button" />
</div>
I solved it in this way
var $id = $('#id');
var $name = $('#name');
var $prezzo = $('#prezzo');
$(function(){
$('#button').click(function(e){
e.preventDefault();
console.log('select_link clicked');
var object = {
id:$id.val(),
name:$name.val(),
prezzo: $prezzo.val()
};
$.ajax({
type: 'POST',
data: JSON.stringify(object),
contentType: 'application/json',
url: 'http://localhost:3000/router/newProducts',
success: function(data) {
console.log('success');
console.log(JSON.stringify(object));
}
});
});
});

Prevent page from refreshing after an ajax call

I have a bootstrap form the info from which I am saving to a json file using an ajax call.
My problem is that when I press the Submit button the page seems to refresh after the call(executed after the submit button is clicked), which is something i'd definitely like to avoid.
I tried to investigate the problem, but my knowledge is insufficient for that as I don't have an indepth understanding of any of these concepts.
Here is my BS form :
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Full Name:</label>
<div class="col-sm-2">
<input type="name" class="form-control" id="nameFull">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="phone">Phone:</label>
<div class="col-sm-2">
<input type="phone" class="form-control" id="phoneApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-2">
<input type="email" class="form-control" id="emailApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-2">
<input type="date" class="form-control" id="date">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Hour:</label>
<div class="col-sm-2">
<select class="form-control" id="time">
<option value="Time" class="">Time</option>
<option value="10am" class="">10:00-10:30</option>
<option value="1030am" class="">10:30-11:00</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="reason">Reason:</label>
<div class="col-lg-3">
<textarea class="form-control" id="reason" name="comments" placeholder="Describe the reason to make an appointment here. Please, include symptoms and any historical data that may help us determine your case." rows="5"></textarea><br>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="saveAppt" class="btn btn-default">Submit</button>
</div>
</div>
</form>
And here is the ajax call :
$(document).ready(function() {
$("#saveAppt").click(function(){
var fullName = $("#nameFull").val();
var userName = $("#cpr").val();
var phone = $("#phoneApp").val();
var email = $("#emailApp").val();
var date = $("#date").val();
var time = $("#time").val();
var reason = $("#reason").val();
console.log(time);
console.log(date);
console.log(reason);
var jAppointment= {};
jAppointment.fullName = fullName;
jAppointment.userName = userName;
jAppointment.phone = phone;
jAppointment.email = email;
jAppointment.date = date;
jAppointment.time = time;
jAppointment.reason = reason;
console.log(JSON.stringify(jAppointment));
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'save-appointments.php',
data: { data: JSON.stringify(jAppointment) },
success: function () {console.log("Thanks!"); },
failure: function() {console.log("Error!");}
});
});
});
Now what the submit action refresh your page the click event will never be raised since the <button> tag has type='submit' by defaul just add type='button' type to avoid submit/refresh :
<button type="button" id="saveAppt" class="btn btn-default">Submit</button>
Hope this helps.
$(document).ready(function() {
$("#saveAppt").click(function(){
var fullName = $("#nameFull").val();
var userName = $("#cpr").val();
var phone = $("#phoneApp").val();
var email = $("#emailApp").val();
var date = $("#date").val();
var time = $("#time").val();
var reason = $("#reason").val();
console.log(time);
console.log(date);
console.log(reason);
var jAppointment= {};
jAppointment.fullName = fullName;
jAppointment.userName = userName;
jAppointment.phone = phone;
jAppointment.email = email;
jAppointment.date = date;
jAppointment.time = time;
jAppointment.reason = reason;
console.log(JSON.stringify(jAppointment));
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'save-appointments.php',
data: { data: JSON.stringify(jAppointment) },
success: function () {console.log("Thanks!"); },
failure: function() {console.log("Error!");}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Full Name:</label>
<div class="col-sm-2">
<input type="name" class="form-control" id="nameFull">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="phone">Phone:</label>
<div class="col-sm-2">
<input type="phone" class="form-control" id="phoneApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-2">
<input type="email" class="form-control" id="emailApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-2">
<input type="date" class="form-control" id="date">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Hour:</label>
<div class="col-sm-2">
<select class="form-control" id="time">
<option value="Time" class="">Time</option>
<option value="10am" class="">10:00-10:30</option>
<option value="1030am" class="">10:30-11:00</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="reason">Reason:</label>
<div class="col-lg-3">
<textarea class="form-control" id="reason" name="comments" placeholder="Describe the reason to make an appointment here. Please, include symptoms and any historical data that may help us determine your case." rows="5"></textarea><br>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type='button' id="saveAppt" class="btn btn-default">Submit</button>
</div>
</div>
</form>
<br><br><br><br><br><br>
Crate a reference to your event in your click handler.
$("#saveAppt").click(function(e){
then call the preventDefault function on that event after your AJAX call.
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'save-appointments.php',
data: { data: JSON.stringify(jAppointment) },
success: function () {console.log("Thanks!"); },
failure: function() {console.log("Error!");}
});
e.preventDefault();

Categories

Resources