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'],
]);
}
Related
I've been studying and trying ajax for a couple of days. This code is totally working when page is reloading, However, my target is when I submit the form, it will not reload.
I've been trying it for couple days and it's really not working. It is submitting and reloading instead of not reloading.
I have provided my code below:
Views:
<form method="post" action="" onsubmit="return post();" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputEmail1"></label>
<input type="number" class="form-control" name="fightIDa" id="fightID" aria-describedby="emailHelp" placeholder="FIGHT NUMBER" hidden />
</div>
<input type="text" id="arenaID" name="arenaID" hidden />
<div class="form-group">
<label for="exampleInputEmail1"><i class="fas fa-user mr-2"></i>Handler Name</label>
<input type="text" class="form-control" name="handlerName" id="handlerName" aria-describedby="emailHelp" placeholder="Enter Handler Name" required />
</div>
<!-- <div class="form-group"> -->
<!-- <label for="exampleInputEmail1"><i class="fas fa-clipboard mr-2"></i>Position</label> -->
<!-- <input type="text" class="form-control" name="position" value="MERON" id="meron1" aria-describedby="emailHelp" placeholder="Enter Rooster Description" required> -->
<!-- </div> -->
<label for="exampleInputEmail1"><i class="fas fa-clipboard mr-2"></i>Rooster Specifications</label>
<div class="row">
<div class="form-group col-3">
<input type="text" class="form-control" name="bodyColor" id="bodyColor" aria-describedby="emailHelp" placeholder="Body Color" required />
</div>
<div class="form-group col-3">
<input type="text" class="form-control" name="legColor" id="legColor" aria-describedby="emailHelp" placeholder="Leg Color" required />
</div>
<div class="form-group col-2">
<input type="text" class="form-control" name="wingSpan" id="wingSpan" aria-describedby="emailHelp" placeholder="Wing Span" required />
</div>
<div class="form-group col-2">
<input type="text" class="form-control" name="weight" id="weight" aria-describedby="emailHelp" placeholder="Weight" required />
</div>
<div class="form-group col-2">
<input type="text" class="form-control" name="tailColor" id="tailColor" aria-describedby="emailHelp" placeholder="tailColor" required />
</div>
<div class="form-group col-2">
<input type="text" class="form-control" name="breed" id="breed" aria-describedby="emailHelp" placeholder="Breed" required />
</div>
</div>
<!-- <div class="form-group"> -->
<!-- <label for="exampleInputEmail1">Rooster Photo</label> -->
<!-- <input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter Date Added" required> -->
<!-- </div> -->
<div class="form-group">
<label for="pic_file"><i class="fas fa-images mr-2"></i>Rooster Image</label>
<input type="file" name="roosterPhoto" class="form-control btn-sm" id="roosterPhoto" />
</div>
<!-- <div class="form-group"> -->
<!-- <label for="exampleInputEmail1">Date Added</label> -->
<!-- <input type="date" class="form-control" name="date" value="" id="addedBy" aria-describedby="emailHelp" placeholder="Enter Date Added" required> -->
<!-- </div> -->
<!-- <div class="form-group"> -->
<!-- <label for="exampleInputEmail1"><i class="fas fa-at mr-2"></i>Added By</label> -->
<!-- <input type="text" class="form-control" name="addedBy" aria-describedby="emailHelp" placeholder="USERNAME" disabled> -->
<!-- </div> -->
<!-- select -->
<button type="submit" class="btn btn-success btn-danger text-bold float-right" id="meron" value="save">Submit</button>
</form>
<p id="status"></p>
<!-- end form -->
Controller:
public function creates(){
$id = $this->input->post('arenaID');
$data = array (
'fightID' => '0',
'handlerName' => $this->input->post('handlerName'),
'position' => 'meron',
'bodyColor' => $this->input->post('bodyColor'),
'legColor' => $this->input->post('legColor'),
'wingSpan' => $this->input->post('wingSpan'),
'weight' => $this->input->post('weight'),
'breed' => $this->input->post('breed'),
'tailColor' => $this->input->post('tailColor'),
'addedBy' => $this->session->userdata('uid'),
'fightStatus' => 'on-queue',
'arenaID' =>$id,
'roosterPhoto' => $this->upload(),
);
$this->db->insert('fight_entries', $data);
echo 'Added successfully.';
}
Script & Ajax:
function post() {
var fightID = document.getElementById("fightID").value;
var arena = document.getElementById("arenaID").value;
var handlername = document.getElementById("handlerName").value;
var bodycolor = document.getElementById("bodyColor").value;
var legcolor = document.getElementById("legColor").value;
var wing = document.getElementById("wingSpan").value;
var weight = document.getElementById("weight").value;
var tail = document.getElementById("tailColor").value;
var breed = document.getElementById("breed").value;
var photo = document.getElementById("roosterPhoto").value;
if (fightID && arenaID && handlerName && bodyColor && legColor && wingSpan && weight && tailColor && breed && roosterPhoto)
$.ajax({
type: "POST",
url: "<?=site_url('arena/creates')?>",
data: {
fightID: fightID,
arenaid: arenaID,
handler_Name: handlerName,
body_Color: bodyColor,
leg_Color: legColor,
wing_Span: wingSpan,
weight: weight,
tail_Color: tailColor,
breed: breed,
rooster_Photo: roosterPhoto
},
success: function(response) {
document.getElementById("status").innerHTML = "Form Submitted Successfully";
}
});
return false;
}
You need to return false bottom of the submit function
like this
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
var handlerName = $("input[name='handlerName']").val();
var bodyColor = $("input[name='bodyColor']").val();
var legColor = $("input[name='legColor']").val();
var wingSpan = $("input[name='wingSpan']").val();
var weight = $("input[name='weight']").val();
var breed = $("input[name='breed']").val();
var tailColor = $("input[name='tailColor']").val();
var roosterPhoto = $("input[name='roosterPhoto']").val();
$.ajax({
type: "POST",
url: "<?= site_url('arena/creates')?>",
data: {
handlerName: handlerName,
bodyColor: bodyColor
legColor: legColor,
wingSpan: wingSpan,
weight: weight,
breed: breed,
tailColor: tailColor
roosterPhoto: roosterPhoto
},
dataType: "json",
error: function () {
alert('Something is wrong');
},
success: function (data) {
alert('form was submitted');
}
});
return false;
}
</script>
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));
}
});
});
});
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();
CODEIGNITER METHOD
public function agregar_post(){
$nombre = $this->post('nombre');
$mail = $this->post('mail');
$telefono = $this->post('telefono');
$password = $this->post('password');
$nivel_listado = $this->post('nivel_listado');
// Store he whole data into $data
$data = array(
'id' => '',
'nombre' => $nombre,
'mail' => $mail,
'telefono' => $telefono,
'password' => $password,
'api_key' => '',
'nivel_listados' => $nivel_listado
);
$query = $this->db->insert('cliente',$data);
// Check if insert is succes
if ($query)
{
$this->output->set_header("Access-Control-Allow-Origin: http://www.verdulero.com", false); // header allow
$this->response($query,201);
}else
{
$this->response(null,404);
}
}
//JQUERY AJAX
$("#frmAddClient").submit(function (event){
event.preventDefault();
var dataForm = $(this).serialize();
// ajax to insert a new product
$.ajax({
type: $(this).attr('method'), // METHOD FROM FORM
url: $(this).attr('action'), // URL FROM FORM
crossDomain: true,
data: dataForm,
success: function(){
alert();
}
});
// CLEAN THE FORM AFTER INSERT
$("#frmAddClient")[0].reset();
});
// HTML
<form name="frmAddClient" id="frmAddClient" method="post" action="<?= $addClient ?>" class="form-horizontal">
<div class="form-group">
<label for="Email" class="col-sm-4 control-label">Correo electronico:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="text" class="form-control" id="Email" name="mail" placeholder="Verdulero#example.com" value="" autofocus required>
</div>
</div>
</div>
<div class="form-group">
<label for="Nombre" class="col-sm-4 control-label">Nombre:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="Nombre" name="nombre" placeholder="Juan Verdura" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="Telefono" class="col-sm-4 control-label">Telefono:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-phone-alt"></span></span>
<input type="text" class="form-control" id="Telefono" name="telefono" placeholder=" 555 555 555" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="Password" class="col-sm-4 control-label">Password:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" id="Password" name="password" placeholder="Password" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="nivel_listado" class="col-sm-4 control-label">Nivel Listado:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<select class="form-control" name='nivel_listado' id='nivel_listado'>
<option value=''>Elija</option>
<option value='1'>Usuario nivel 1</option>
<option value='2'>Usuario nivel 2</option>
<option value='3'>Usuario nivel 3</option>
<option value='4'>Nivel administrador</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<input type="submit" class="btn btn-success" name="submit" id="Submit_User" value="Insertar nuevo usuario"/>
</div>
</div>
</form>
Use $this->input->post() instead of $this->post()
$nombre = $this->input->post('nombre');
$mail = $this->input->post('mail');
$telefono = $this->input->post('telefono');
$password = $this->input->post('password');
$nivel_listado = $this->input->post('nivel_listado');
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