I cannot save the form data using Laravel 9 and Ajax. The city_name, longitude, and latitude come from the JSON file, so when I choose a city, its longitude and latitude get dynamically filled up. I manually enter the address and save the form, but an error pops up. From the controllers, when I used the function dd($workplaces), nothing happened, and from the JavaScript, the console.log(data) gives an empty data[] like below:
Look here form data =
FormData(6) {
_token → "SnoXgjegU7tuk3HdoWUoj88egv2evUyLDZnGroC5",
city_name → "Bafoussam",
address → "<p>qwerty</p>",
latitude → "5.4667",
longitude → "10.4167",
workplaces_id → ""
}
workplace:800:17
Server response:
Object {
draw: 0,
recordsTotal: 0,
recordsFiltered: 0,
data: []
}
workplace:809:25
That tells me an error isn't listed in the log file or the browser console. I would appreciate any help in solving the issue. My initial code is below.
Controllers
public function store(Request $request)
{
$workplaces_id = $request->workplaces_id;
// dd($workplaces_id);
if ($request->ajax()) {
if ($workplaces_id != '') {
# update case
return $this->update($request, $workplaces_id);
} else {
# insert case
$validator = $request->validated();
// dd($validator);
try {
DB::beginTransaction();
$workplaces = Workplace::create(
[
'city_name' => $validator['city_name'],
'address' => $validator['address'],
'longitude' => $validator['longitude'],
'latitude' => $validator['latitude'],
'created_by' => \Auth::user()->id
]
);
DB::commit();
dd($workplaces);
return Response()->json(
[
'success' => true,
'data' => $workplaces,
'message' => trans('hrprofile::Workplace.job_pos_create')
]
);
} catch (\Exception $e) {
DB::rollback();
Log::error($e->getMessage());
return response()->json(['success' => false, 'message' => $e->getMessage()]);
}
}
}
}
JavaScript
// STORING DATA FORM INTO THE DATABASE
$('#WorkplaceForm').submit(function(e) {
e.preventDefault();
var addresses = tinyMCE.activeEditor.getContent();
$('#address').val(addresses);
var formData = new FormData(this);
console.log('Look here form data =', formData);
$.ajax({
type: 'POST',
url: "{{ route('workplace.store') }}",
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
console.log('Server response:', data);
if (data.success) {
$("#workplace-modal").modal('hide');
toastr.success(data.message);
var oTable = $('#workplace-datatable').dataTable();
oTable.fnDraw(false);
$("#btn-save").html("{{ __('formular.save') }}");
$("#btn-save").attr("disabled", false)
} else {
toastr.error(data.message);
}
},
error: function(data) {
toastr.error(data.message);
}
});
});
// DROPDOWN FOR ALL CITIES DYNAMICALLY POPULATE LATITUDE & LONGITUDE
$(document).ready(function() {
$.getJSON('/assets/json/cm.json', function(data) {
// console.log('Data here = ', data);
$.each(data, function(key, value) {
// Improved option creation
$('#city_name').append($('<option>').text(value.city).val(value.city));
});
$('#city_name').change(function() {
var selectedCityId = $(this).val();
var cityData = null;
$.each(data, function(key, value) {
if (value.city == selectedCityId) { // Use strict comparison (===)
cityData = value;
return false; // Exit the loop after finding the match
}
});
if (cityData) {
$('#latitude').val(cityData.lat);
$('#longitude').val(cityData.lng);
} else {
$('#latitude').val('');
$('#longitude').val('');
}
});
});
});
Form view
<form method="post" action="javascript:void(0)" id="WorkplaceForm" enctype="multipart/form-data">
@csrf
<div class="modal-body">
{{-- WORPLACE NAME --}}
<div class="row">
<div id="additional_department input hidden"></div>
<div class="col-md-4">
<label for="city_name" class="control-label LBL">
<span class="text-danger">*</span>{{ __('hrprofile::workplace.wp_name') }}
</label>
<select name="city_name" class="form-select selectpicker" id="city_name" data-width="100%" data-live-search="true" required="">
<option value=""></option>
</select>
</div>
</div>
{{-- ADDRESS --}}
<div class="row mt-3">
<div class="col-md-12">
<label for="address" class="control-label">
<span class="text-danger"></span>{{ __('hrprofile::workplace.wp_address') }}
</label>
<textarea id="address" rows="5" name="address" class="tinymce" required=""></textarea>
</div>
</div>
{{-- LONGITUDE | LATITUDE --}}
<div class="row mt-3">
<div class="col-md-6 col-sm-12">
<label for="latitude" class="control-label LBL">
<span class="text-danger"></span>
{{ __('hrprofile::workplace.wp_latitude') }} °
</label>
<input type="text" id="latitude" name="latitude" class="form-control " value="" required="" readonly>
</div>
<div class="col-md-6 col-sm-12">
<label for="longitude" class="control-label LBL">
<span class="text-danger"</span>
{{ __('hrprofile::workplace.wp_longitude') }} °
</label>
<input type="text" id="longitude" name="longitude" class="form-control " value="" required="" readonly>
</div>
</div>
</div>
<br>
<div class="modal-footer">
{!! Form::hidden('workplaces_id', '', ['id' => 'workplaces_id']) !!}
<button type="submit" class="btn btn-info" id="btn-save">{{ __('hrprofile::workplace.btn_save') }}</button>
<button type="button" class="btn btn-danger waves-effect" data-bs-dismiss="modal">{{ __('hrprofile::workplace.btn_close') }}</button>
</div>
</form>
I tried to change the controllers like the one below but I am still facing the same issue.
public function store(Request $request)
{
$validator = $request->validate([
'city_name' => 'required',
'address' => 'nullable', // Update based on your requirement
'latitude' => 'required',
'longitude' => 'required',
]);
try {
DB::beginTransaction();
$workplaces = Workplace::create([
'city_name' => $validator['city_name'],
'address' => $validator['address'],
'longitude' => $validator['longitude'],
'latitude' => $validator['latitude'],
'created_by' => Auth::id(),
]);
DB::commit();
return response()->json([
'success' => true,
'data' => $workplaces,
'message' => trans('hrprofile::Workplace.job_pos_create'),
]);
} catch (\Exception $e) {
DB::rollback();
Log::error($e->getMessage());
return response()->json([
'success' => false,
'message' => 'An error occurred while saving data.',
]);
}
}
Response()->json(...)should beresponse()->json(...).DB::rollback()should beDB::rollBack(). You might encounter problems later on if you don't correct those.