Delete a row from the database via ajax - 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();
}

Related

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

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!

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']);
}

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

Resources