How to set selected value in edit mode - Select2 with AJAX Remote Data - ajax

Please wait, I know you will say that this is a possible Duplicate. The answer is Yes.
Here's the link
But none of the answers works for me.
On my blade I put the value in a hidden input field.
<input type="hidden" value="{{ $recipe->cuisine_type_id }}" id="selectedCuisineTypeId">
I have the same scenarios. Here's my JS;
var selectedCuisineTypeId = $("#selectedCuisineTypeId").val();
$('#cuisine_type_id').val(selectedCuisineTypeId).trigger('change');
$( "#cuisine_type_id" ).select2({
ajax: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
placeholder: "Select Cuisine",
url: "{{ route('ajax-cuisine-search') }}",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
Why it is not working for me? What did I miss?

I have solved my issue above. Here's what I did.
Make a hidden field of the ID you want to get selected and set a variable for it.
<input type="hidden" value="{{ $recipe->cuisine_type_id }}" id="selectedCuisineTypeId">
Create a new route to fetch the selected value and trigger Select2.
Route
Route::get('recipe/cuisine/{id}', [SearchController::class, 'getSelectedCuisine'])->name('getSelectedCuisine');
Controller
*selectCuisineSearch class to load the list of Cuisines.
getSelectedCuisine class to fetch the selected Cuisine in Edit Mode
public function selectCuisineSearch(Request $request)
{
$search = $request->search;
if ($search == '') {
$cuisines = Cuisine::orderby('name', 'asc')->select('id', 'name')->get();
} else {
$cuisines = Cuisine::orderby('name', 'asc')->select('id', 'name')->where('name', 'like', '%' . $search . '%')->limit(5)->get();
}
$response = array();
foreach ($cuisines as $cuisine) {
$response[] = array(
"id" => $cuisine->id,
"text" => $cuisine->name
);
}
return response()->json($response);
}
public function getSelectedCuisine(Request $request)
{
$cuisineId = $request->id;
$cuisines = Cuisine::where('id', $cuisineId)->first();
$response = array(
"id" => $cuisines->id,
"name" => $cuisines->name
);
return response()->json($response);
}
On my Edit Blade
$(document).ready(function(){
$( "#cuisine_type_id" ).select2({
ajax: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
placeholder: "Select Cuisine",
url: "{{ route('ajax-cuisine-search') }}",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
search: params.term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
var selectedCuisineTypeId = $("#selectedCuisineTypeId").val();
var cuisineSetSelected = $('#cuisine_type_id');
$.ajax({
type: 'GET',
url: '{{ route('getSelectedCuisine')/' + selectedCuisineTypeId
}).then(function (response) {
var option = new Option(response.name, response.id, true, true);
cuisineSetSelected.append(option).trigger('change');
cuisineSetSelected.trigger({
type: 'select2:select',
params: {
results: response
}
});
});
});
This solution might be long. You are free to suggest making this shorter. I am happy to learn more. Cheers!

Related

how to create relational select option ajax in laravel 8

I try to create a relational select option in laravel 8 using ajax but didn't work I get this error in the console: 405 Method Not Allowed
POST http://127.0.0.1:8000/decomptes/%7B%7B%20route(%20'getOperationsChantier'%20)%20%7D%7D 405 (Method Not Allowed)
the route
Route::post('/getOperationsChantier', [DecompteController::class, 'getOperationsChantier'])->name('getOperationsChantier');
the jquery code
$(document).ready(function(){
// When an option is changed, search the above for matching choices
$('#chantiers').change(function(){
$("#mySelect option").remove();
// $("#city option").remove();
var id = $(this).val();
$.ajax({
url : "{{ route( 'getOperationsChantier' ) }}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
type: 'post',
dataType: 'json',
success: function( result )
{
$.each( result, function(k, v) {
$('#mySelect').append($('<option>', {value:k, text:v}));
});
},
error: function()
{
//handle errors
alert('error...');
}
});
}).change();
});
the function in the controller :
function getOperationsChantier( Request $request )
{
$this->validate( $request, [ 'id' => 'required|exists:chantiers,id' ] );
$chantierOperations = ChantierOperation::where('chantier_id', $request->get('id') )->get();
$output = [];
foreach( $chantierOperations as $chantierOperation )
{
$output[$chantierOperation->id] = $chantierOperation->operation_id;
}
return $output;
}
can someone help me this is the first time when I use ajax

Ajax update field database field in laravel blade template

I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);

How to parse an object passed by an AJAX?

I made an Ajax POST request into my Laravel function however i am facing this result:
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style')
This happens when i die and dump my data so as to see what i get from ajax request. I have this jquery method:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#save-person').on('click', function() {
let first_name = $('#first_name').val();
let middle_name = $('#middle_name').val();
let third_name = $('#third_name').val();
let family_name = $('#family_name').val();
$.ajax({
url: urlReq+"/api/employee/customize",
type: "POST",
data: {
first_name: first_name,
middle_name: middle_name,
third_name: third_name,
family_name: family_name,
},
cache: false,
success: function(dataResult){
console.log(dataResult);
let data = dataResult;
if(data.statusCode==200){
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
});
and on my php method i have this:
public function customize_store(Request $request){
//dd($request->first_name);
$input = $request->all();
dd($input);
return response()->json(['Person'=>$input]);
}
which result to <script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx =... but my input are also present there that looks like this:
#<span class=sf-dump-protected title="Protected property">parameters</span>: <span class=sf-dump-note>array:15</span> [<samp>
"<span class=sf-dump-key>first_name</span>" => "<span class=sf-dump-str title="7 characters">Michael</span>"
"<span class=sf-dump-key>middle_name</span>" => "<span class=sf-dump-str title="6 characters">Sangga</span>"
"<span class=sf-dump-key>third_name</span>" => <span class=sf-dump-const>null</span>
"<span class=sf-dump-key>family_name</span>" => "<span class=sf-dump-str title="7 characters">Smith</span>"
How would i extract those data so that i can persist it on my database?
Try this code.. check the URL, Routes on which you are sending your
data..
public function addPersonData(Request $request){
$save_person = new Person(); // Initialize your model here..
$save_person->first_name = $request->get('first_name');
$save_person->middle_name = $request->get('middle_name');
$save_person->third_name = $request->get('third_name');
$save_person->family_name = $request->get('family_name');
$save_person->save();
return 'ok';
}
I think I got it. First add a name to your route (see here) and the ajax part in your jQuery (assuming you use a form to submit the user data):
in your Route.php add:
Route::post('api/employee/customize', 'PersonController#customize_store')->name('api.employee.customize');
Your jQuery ajax request:
$('#save-person').submit(function(e) {
e.preventDefault();
let first_name = $('#first_name').val();
let middle_name = $('#middle_name').val();
let third_name = $('#third_name').val();
let family_name = $('#family_name').val();
$.ajax({
url: "{{ route('api.employee.customize') }}",
type: "POST",
data: { first_name, middle_name, third_name, family_name },
cache: false,
success: function(data){
console.log(data);
if(data.status === 'success'){
$("#success").show();
$('#success').html('Data added successfully !');
//the person's details are in data.person.first_name etc
//you already knew that, but added is the new data.person.id you may use
}
else {
alert("Error occured !");
}
}
});
});
and your controller, assuming the model linked to this data is Person:
public function customize_store(Request $request){
$person = new Person($request->all());
if ($person->save()) {
return response()->json(['status' => 'success', 'person'=>$person]);
}
return response()->json(['status' => 'fail']);
}

codeigniter form validation with anchor tag click

I want to validate some form fields without submitting the form.
Here is my code if someone can help.
View:
<form>
<input type="text" name="first_name" placeholder="First Name..." class="textfield">
<a href="javascript:void();" onClick="validateName();">
</form>
Script:
function validateName(){
var first_name = $('.textfield').val();
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: first_name,
dataType:"json",
success: function(response){
var obj = eval(response);
if(obj.error==0){
console.log('Success');
}
else{
console.log('Failed');
}
}
});
}
Controller:
public function contAjax(){
// loading form validation library //
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'required');
if($this->form_validation->run()== TRUE){
echo json_encode(array('error' => 0));
}
else{
echo json_encode(array('error' => 1));
}
}
It always returns error=1 and form validation is not working...
This is untested code... but should work ( he said with a grin )
function validateName() {
var first_name = $('.textfield').val();
console.log('first_name is ' + first_name); // Check it's getting this far
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: {first_name: first_name},
dataType: "json",
success: function (response) {
if (response.error == 0) {
console.log('Success');
}
else {
console.log('Failed');
}
}
});
}
So with the addition of the console.log you can easily inspect your value...
I am not a big fan of using capitals in urls ( only works on windows and can lead to tears on a linux / apache server ) so best to use lowercase.
Just to add some more debug to this the simplish way you could inspect what the server side sees you posting...
This is just a way to check your posted values ( using something like firebug or similar is far better...)
function contAjax() {
// loading form validation library //
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'required');
$first_name = $this->input->post('first_name');
if ($this->form_validation->run() == TRUE) {
echo json_encode(array('error' => 0, 'first_name' => $first_name));
} else {
echo json_encode(array('error' => 1, 'first_name' => $first_name));
}
}
And your JS would become...
function validateName() {
var first_name = $('.textfield').val();
console.log('first_name is ' + first_name); // Check it's getting this far
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: {first_name: first_name},
dataType: "json",
success: function (response) {
if (response.error == 0) {
console.log('Success - First Name = ' + response.first_name);
}
else {
console.log('Failed - First Name = ' + response.first_name);
}
}
});
}
The trick is to know how to "see" what is happening which makes debugging these kinds of things of lot easier...
Hope that helps. Again this code is untested but shows the principal...

Delete a row from the database via ajax

I have this javascript function to delete the row but the function is not working
$(document).ready(function()
{
$('table#example td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "supprimerkpi",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
// sets specified color for every odd row
$('table#example tr:odd').css('background',' #FFFFFF');
}
});
}
});
and in my page html:
<a href="#" class="delete" style="color:#FF0000;">
in my controller
$repository = $this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi'); $id=$this->getRequest()->query->get('id');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneBy(array('id' => $id));
$em->remove($uti);
$em->flush();
You are sending the "id" via POST method. So, you need to change:
$id=$this->getRequest()->query->get('id');
into:
$id=$this->getRequest()->request->get('id');
Also, you could change:
$uti=$repository->findOneBy(array('id' => $id));
into:
$uti=$repository->find($id);
.. as find() searches entity using the primary key...
On a side note, what is "supprimerkpi"? That can't be a valid destination URL, right? :)
In your routing.yml
delete_data:
path: /delete
defaults: { _controller: AcmeDemoBundle:Default:delete}
in your ajax call url parameter change that according to this
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "{{ path('delete_data') }}",
data: {id :id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
// sets specified color for every odd row
$('table#example tr:odd').css('background',' #FFFFFF');
}
});
in your AcmeDemoBundle/Controller/DeafultControlller.php
public function deleteAction(Request $request)
{
$id = $request->get('id');
$repository =
$this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneById($id);
$em->remove($uti);
$em->flush();
}

Resources