Laravel 9 upload image with ajax validation jQuery error - javascript

Whats wrong with my code? i use laravel 9, ajax, jQuery validation, and everytime i click submit, always show error like the one below appears
This display error:
{message: "validation.required (and 2 more errors)",…}
errors: {first_name: ["validation.required"], last_name: ["validation.required"],…}
message: "validation.required (and 2 more errors)"
My Controller:
public function store(Request $request)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'image' => 'required|mimes:jpg,jpeg,png|max:1024',
]);
$file = Request()->file('image');
$file_name = Str::random(20) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images'), $file_name);
$form_data = [
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'image' => $file_name
];
AjaxCrud::create($form_data);
return response()->json(['success' => 'Data added successfully.']);
}
My Route:
Route::get('/', [AjaxCrudController::class, 'index']);
Route::resource('ajax-crud', AjaxCrudController::class);
My Form:
<div class="modal fade" id="addmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Form</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="javascript:void(0)" name="addmodal" id="addform" class="form-horizontal"
enctype="multipart/form-data">
#csrf
<div class="mb-3">
<label for="first_name" class="form-label">First Name</label>
<input type="text" class="form-control" name="first_name" id="first_name" required>
</div>
<div class="mb-3">
<label for="last_name" class="form-label">Last Name</label>
<input type="text" class="form-control" name="last_name" id="last_name" required>
</div>
<div class="mb-3">
<label for="image" class="form-label">Select Profile Image</label>
<input type="file" class="form-control" name="image" id="image" required>
</div>
<div class="modal-footer">
<input type="submit" name="addbutton" id="addbutton" class="btn btn-primary" value="Add" />
<button type="button" class="btn btn-warning" data-bs-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
My Script:
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Add modal
$('#create_record').click(function(){
$('#addmodal').modal('show');
$('.modal-title').text('Add New Record');
$('#addbutton').val('Add');
$('#addaction').val('Add');
});
// Save Data
if ($('#addform').length > 0) {
$('#addform').validate({
rules: {
first_name: 'required',
last_name: 'required',
image: 'required',
},
messages: {
first_name: 'First name required!',
last_name: 'Last name required!',
image: 'Image required!',
},
submitHandler: function (form) {
event.preventDefault();
$.ajax({
data: $('#addform').serialize(),
url:'{{ route('ajax-crud.store') }}',
method:'POST',
contentType: false,
cache:false,
processData: false,
dataType:'json',
success:function(data)
{
$('#addform')[0].reset();
$('#addmodal').modal('hide');
$('#user_table').DataTable().ajax.reload();
iziToast.success({
title: 'Data added successfully.',
message: '{{ Session('success')}}',
position: 'topCenter'
});
}
})
}
});
}
});
</script>
......................................................................................................

Related

HTML required attribute not working with AJAX submission

HTML required attribute not working with AJAX submission
I have created a model Form and set its input field to require attribute but its not working with ajax
<div class="modal fade hide" id="ajax-book-model" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ajaxBookModel">Add New Machine</h5>
<!-- <button type="reset" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" onClick="window.location.reload();">
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST">
<input type="hidden" name="id" id="id">
<input type="hidden" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Name</label>
<input type="text" id="machine_name" name="machine_name" class="form-control form-control-sm" placeholder="Enter Machine Name" required>
<span class="text-danger">{{ $errors->first('machine_name') }}</span>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>IOT Device ID</label>
<input type="text" id="iot_device_id" name="iot_device_id" class="form-control form-control-sm" placeholder="Enter IOT Device ID" required>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Local device ID</label>
<input type="text" id="local_device_id" name="local_device_id" class="form-control form-control-sm" placeholder="Enter Local Device ID" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-gradient-danger mb-2" data-dismiss="modal" onClick="window.location.reload();">Close</button>
<button type="submit" id="btn-save" value="addNewBook" class="btn btn-sm btn-gradient-danger mb-2">Save</button>
</div>
</form>
</div>
</div>
</div>
and this is ajax code
i just want to run simpal html required field validation with ajax
$('body').on('click','#btn-save', function (event){
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id:id,
user_id:user_id,
machine_name:machine_name,
iot_device_id:iot_device_id,
local_device_id:local_device_id,
},
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
}
});
});
i just want to run required field validation with ajax i could not find any solution .
Try changing your btn click event to form submit event.
$('body').on('submit', '#addEditBookForm', function (event) {
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type: "POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id: id,
user_id: user_id,
machine_name: machine_name,
iot_device_id: iot_device_id,
local_device_id: local_device_id,
},
dataType: 'json',
success: function (res) {
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
}
});
});
The following should help: change to a form confirmation event instead of a Click button event. And do not forget to write this code so that the page does not reload:
event.preventDefault();

Submit AJAX request with textfields values and image using Laravel

Currently I have working save data using ajax and laravel. But when I tried to add image field on saving it doesn't work properly now.
First I can pass variables with values using ajax to my controller.
these are my variables name, type, select_file, steps, step_no
If I didn't fill up one of those fields it will prompt an error message.
I can get the file name of the select_file field and validate it on my controller.
How ever when I'm trying save and all fields are filled up this gives me an error like this
The select_file must be an image
Error prompts even though it has an image png file.
Here's my HTML
<div class="modal fade" id="modalRecipes" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<!--Header-->
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Recipes</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--Body-->
<div class="modal-body">
<div class="container">
<form>
{{ csrf_field() }}
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">Name</label>
<div class="col-md-6">
<input type="text" class="form-control name" name="name" id="name">
</div>
</div>
<div class="form-group row">
<label for="type" class="col-md-4 col-form-label text-md-right">Type</label>
<div class="col-md-6">
<select class="form-control type" name="type" id="type">
</select>
</div>
</div>
<div class="form-group row">
<label for="select_file" class="col-md-4 col-form-label text-md-right">Select Image</label>
<div class="col-md-6">
<input type="file" name="select_file" id="select_file" />
</div>
</div>
<div class="optionBox">
<div class="block step">
<div class="form-group">
<label for="step1">Step 1</label>
<textarea name="steps" data-steps="1" class="form-control rounded-0 steps" id="step1" rows="10"></textarea>
</div>
</div>
</div>
<div class="">
<span class="add">Add Option</span>
</div>
</form>
</div>
</div>
<!--Footer-->
<div class="modal-footer">
<button type="button" class="btn btn-outline-success" data-dismiss="modal">Close</button>
<button type="button" name="submit" class="btn btn-success waves-effect" id="btnSubmit">Submit</button>
</form>
</div>
</div>
and here's my AJAX
$(document).ready(function () {
$("#btnSubmit").click(function () {
var name = $("#name").val();
var type = $("#type").val();
var select_file = $("#select_file").val();
var steps = [],
step_no = [];
$('textarea[name="steps"]').each(function() {
steps.push($(this).val());
step_no.push($(this).attr('data-steps'));
});
var x = document.getElementById("btnSubmit");
x.innerHTML = "Loading...";
document.getElementById("btnSubmit").disabled = true;
$.ajax({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('insert') }}",
method: "POST",
data:{
name:name,
type:type,
steps:steps,
step_no:step_no,
select_file:select_file
},
dataType: "json",
success:function(data)
{
if (data.success.length > 0) {
location.reload();
} else {
toastr.error(data.error[0]);
var x = document.getElementById("btnSubmit");
x.innerHTML = "Submit";
document.getElementById("btnSubmit").disabled = false;
}
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
});
And here's my Controller
public function insert(Request $request)
{
$message = "";
$output = array();
$error = array();
$success = array();
$validator = Validator::make($request->all(), [
'select_file'=>'image',
'name' => 'required',
'type' => 'required',
'steps' => 'required',
'step_no' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors()->all();
$error[] = $messages;
} else {
$dateTime = date('Ymd_His');
$image = $request->select_file;
$new_name = $dateTime . '.' . $image->getClientOriginalExtension();
$image->move(public_path('img'), $new_name);
// Code for saving data.....
$messages = "Successfully Saved!";
$success[] = $messages;
}
$output = array(
'error'=>$error,
'success'=>$success
);
echo json_encode($output);
}

TypeError: 'append' called on an object that does not implement interface FormData

$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method:"POST",
data:postData,
contentType:false,
proccessData:false,
success: function(data)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
this is my JS
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title text-xs-center">Tambah Biaya Pembayaran</h3>
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="reset" class="btn btn-grey" value="Bersihkan">
<input type="submit" class="btn btn-warning" name="action" id="action" value="Tambah">
</div>
</div>
</form>
</div>
</div>
and this is the view.
But i got an error like
TypeError: 'append' called on an object that does not implement interface FormData.
Did i forget something to add? What should i do? thankyou for your help
Need a correction for typo :)
proccessData:false
should be
processData: false
To avoid FormData errors make sure that the ajax options must be like
$.ajax({
url : "url",
type: "POST",
data : postData,
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR){
//
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});

Sending HTML input value to JavaScript

I don't know what's wrong with my code, it didn't work.
My controller :
public function add_user_driver()
{
if(!$this->user_permission->check_permission())return;
$plate_number = $this->input->post('plate_number');
$location_id = $this->input->post('location_id');
$data_user = array(
'plate_number' => $plate_number,
'location_id' => $location_id,
);
$this->db->insert('user_driver', $data_user);
echo json_encode(array("plate_number" => $plate_number, "location_id" => $location_id));
}
The view :
<div class="modal fade" id="usermodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">USER_DRIVER</h4>
</div>
<div class="modal-body" id='add'>
<div class="row" id="form_pesan">
<input type="hidden" name="id" id="id" />
<div class="col-sm-6">
<input type="text" class="form-control input-lg" id="plate_number" name="plate_number" placeholder="Plate Number" required>
</div>
<div class="col-sm-6">
<input type="text" class="form-control input-lg" id="location_id" name="location_id" placeholder="Location Id" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add" type="button" class="btn btn-primary btn-md" onclick=add()>Add</button>
</div>
</div>
<div id="form_submit_result"></div>
</div>
</div>
JavaScript :
$(document).ready(function(){
matchFormFields = "#form_pesan input[required]";
matchFormSubmitResult = "#form_submit_result";
errorColor = 'red';
});
function add(){
var formIsValid = true;
$(matchFormFields).each(function() {
$(this).css('border-color', '');
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
if (formIsValid) {
plate_number = $("#plate_number").val();
location_id = $("#location_id").val();
$.ajax
({
url : "<?php echo site_url('admin/add_user_driver')?>/",
type: "POST",
dataType: "text",
data:{plate_number: plate_number, location_id: location_id},
success: function(data)
{
$("#usermodal").modal("hide");
$("#alert").show();
//location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
notify('Error data');
}
});
};
}
I want to submit value from input text to JavaScript add function, but somehow, the .val() doesn't return the actual value. What did I do wrong?
please try this
datatype: "json"
or
datatype: "text"
JSON.stringify({plate_number: plate_number, location_id: location_id})
var abc = $("#plate_number").val();
alert(abc);
return false;
You can use the variable abc in javascript.

Krajee Bootstrap File Input unresponsive

I'm trying to use this plugin and I'm not getting anything back when I click submit on the form.
This is the form that is inside a modal. I'm using bootstrap.
<form id="myForm" action="#" method="post" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="closeModalTimes">
×
</button>
<h4 class="modal-title">Upload New Document</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Name *</label>
<input class="form-control" type="text" id="name" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject *</label>
<textarea name="subject" id="subject" class="form-control" required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="inputFile">Document File *</label>
<input type="file" name="inputFile" id="inputFile" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn" id="closeModalButton">
Close
</button>
<button type='button' id="submitFile" class='btn'>
Send
</button>
</div>
</div><!-- /.modal-content -->
<input name="myId" type="hidden" id="myId" value="393839334034933">
<input name="user" type="hidden" id="user" value="339">
<input name="page" type="hidden" id="page" value="test">
</form>
This is the jquery on the bottom of the page
$("#inputFile").fileinput({
overwriteInitial: false,
maxFileSize: 4000,
showPreview: false,
showUpload: false,
uploadAsync: true,
allowedFileExtensions: ["jpg", "jpeg", "gif", "png"],
browseClass: "btn btn-info",
elErrorContainer: "#documentErrorBlock",
msgSizeTooLarge: "File exceeds size",
msgInvalidFileExtension: "Invalid extension",
uploadURL: "upload.php",
uploadExtraData: function() {
return {
id: $("#myId").val(),
userId: $("#user").val(),
page: $("#page").val(),
name: $("#name").val(),
subject: $("#subject").val()
};
}
});
$('#inputFile').on('filebatchuploadsuccess', function(event, data, previewId, index) {
alert('success: '+data.response);
});
$('#inputFile').on('filebatchuploaderror', function(event, data, previewId, index) {
alert('error: '+data.response);
});
$("#submitFile").click(function(e) {
$('#inputFile').fileinput('upload');
});
And this is the PHP file:
$output = array();
$output['message'] = 'Reached PHP';
$output['success'] = true;
echo json_encode($output);
When I click nothing happens at all... not an error message or anything...
Thanks for your help!
The reason for not submitting came from your "uploadURL" which is spelt wrongly according to the documentation.
Change this
uploadURL: "upload.php",
to
uploadUrl: "upload.php",
that solves your problem.
http://plugins.krajee.com/file-input#option-uploadurl

Categories