How to get input text value from AJAX to symfony controller - ajax

I have a problem to get my input text value in my controller.
This is my AJAX script:
$(document).ready(function() {
$('#valider').click(function () {
var searchText = $('#searchText').val();
$.ajax({
type: "POST",
url: "/firstproject/web/app_dev.php/parc/searchmodel/"+searchText,
data:{'type':searchText},
success: function (response) {
console.log(response);
},
error: function (response,xhr,status) {
alert("erroe"+status);
}
});
});
});
This is my view.twig where I have a text input:
{% block javascripts %}
<script src="{{ asset('bundles/js/jquery.min.js') }}"></script>
<script src="{{ asset('bundles/js/script.js') }}"></script>
{% endblock %}
<input type="text" id="searchText" name="searchText" value=" "placeholder="search by libel">
<input id="valider" type="submit" value="valider">
<h1>La liste des modeles</h1>
<table border="1">
<tr>
<th>Id</th>
<th>Libelle</th>
<th>pays</th>
<th>modifier</th>
<th>supprimer</th>
</tr>
{% for m in mod %}
<tr>
<td>{{ m.id }}</td>
<td>{{ m.libelle}}</td>
<td>{{ m.pays }}</td>
<td>
modifier
</td>
<td>supprimer</td>
</tr>
{% endfor %}
</table>
This is my controller action:
public function searchAction(Request $request){
$request->request->get('type');
dump($request);
$em = $this->getDoctrine()->getManager();
$modele = $em->getRepository("EspritParcBundle:Modele")
->searchbyLib($request);
return $this->render("EspritParcBundle:Modele:searchmodel.html.twig",array('mod'=>$modele));
}
This is my custom function searchbylib:
class ModeleRepository extends EntityRepository
{
public function searchbyLib($libele)
{
$em = $this->getEntityManager()
->createQuery('SELECT m FROM EspritParcBundle:Modele m
WHERE m.libelle LIKE :libele')
->setParameter('libele',$libele);
dump($em->getResult());
return $em->getResult();
}
}
And finally, my routing file:
searchmodel:
path: /searchmodel/{type}
defaults: { _controller: EspritParcBundle:Modele:search}
This is my output:
When entering "BMW" in the text field then click on the validation button, I would like it to show me only BMW models and the url to be redirected.

view.html.twig
{% block javascripts %}
<script src="{{ asset('bundles/js/jquery.min.js') }}"></script>
<script src="{{ asset('bundles/js/script.js') }}"></script>
{% endblock %}
<form action="{{ path('searchmodel') }}" method="POST">
<input type="text" id="searchText" name="searchText" value=" "placeholder="search by libel">
<input id="valider" type="submit" value="valider">
</form>
<h1>La liste des modeles</h1>
<table border="1">
<tr>
<th>Id</th>
<th>Libelle</th>
<th>pays</th>
<th>modifier</th>
<th>supprimer</th>
</tr>
{% for m in mod %}
<tr>
<td>{{ m.id }}</td>
<td>{{ m.libelle}}</td>
<td>{{ m.pays }}</td>
<td>
modifier
</td>
<td>supprimer</td>
</tr>
{% endfor %}
</table>
routing file:
searchmodel:
path: /searchmodel
defaults: { _controller: EspritParcBundle:Modele:search}
controller :
public function searchAction(Request $request){
$request = $request->get('type');
$em = $this->getDoctrine()->getManager();
$modele = $em->getRepository("EspritParcBundle:Modele")
->searchbyLib($request);
return $this->render("path:to:view.html.twig",array('mod'=>$modele));
}

The $type parameter is passed through the query string
searchmodel:
path: /searchmodel/{type}
defaults: { _controller: EspritParcBundle:Modele:search}
So you can directly add it to the parameter of the method like this :
public function searchAction(Request $request, $type)
{
$em = $this->getDoctrine()->getManager();
$modele = $em->getRepository("EspritParcBundle:Modele")
->searchbyLib($request);
return $this->render("path:to:view.html.twig",array('mod'=>$modele));
}
Is that help you?

I found out that in my controller $request = $request->get('type'); always return null, so I've tried with $lib = $request->getContent(); and then I did dump($lib); to display what it contains and here is the output:
So after that, I used substr function to extract only the text value and delete the rest and everything is working well.

Related

How can I insert array using ajax laravel?

Help please ,I recover my data in frontend use jquery and I can display in console, now I want to insert these data in the database we are using ajax and laravel, here is my table.
Hi,help please ,I recover my data in frontend use jquery :
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td class="mat">{{ $salarie->matricule }}</td>
<td class="name">{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td class="salaireValue">{{ $salarie->salairenet }}</td>
<td ><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
This is my code jquery which allows to recover my data
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.add-all').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var currentHtml = $(allChecked[i]).parent().siblings('.salaireValue')[0];
var currentHtml1 = $(allChecked[i]).parent().siblings('.name')[0];
var currentHtml2 = $(allChecked[i]).parent().siblings('.mat')[0];
var currentHtml3 = $(allChecked[i]).parent().siblings('.datea')[0];
var result = parseInt($(currentHtml)[0].innerText);
var result1 = $(currentHtml1)[0].innerText;
var result2 = parseInt($(currentHtml2)[0].innerText);
console.log(result);
console.log(result1);
console.log(result2);
}
});
});
</script>
This my controller I do not know how to write the function.
public function addMultiple(Request $request){
dd(request());
}
route
Route::post('mensuel', ['as'=>'salarie.multiple-add','uses'=>'SalarieController#addMultiple']);

How to showing data on table with datatables 'yajra'

I following this tutorial : How to route in Laravel DataTables
its so simple , but i cant do it . after i set my controller and my route and view , its not showing data and and table. in the table i have a button like'action' how i can take this comand to this button ?
can you check my faulth query
Route::get('user/show1', 'userController#show')->name('usershow1');
Route::get('user/show1-dt', 'userController#indexDataTables')->name('usershow1dt');
controller
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTables()
{
$pemeliharaan = Pemeliharaan::query();
// return DataTables::eloquent($pemeliharaan)->toJson();
return Datatables::of($pemeliharaan)->make(true);
}
and i have a view like this . the page number,search and pagination is showing at view ,but this data not showing. can you correctted this view ?
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>status</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
{{-- #php ---> before i suing datatables my view like that
$no=0;
#endphp
#foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> Lihat Data</span> </td>
<td>{{ $i->created_at}}</td>
</tr>
#endforeach --}}
</tbody></table>
</div>
.
.
#endsection
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('usershow1dt') !!}',
columns: [
{ data: 'nama_alat', name: 'nama_alat'},
{ data: 'status', name: 'status'},
{ data: 'User Input', name: 'nama'},
{ data: 'Action', name: 'name'},//here my button
{ data: 'Tanggal', name: 'created_at'},
],
});
})
</script>
#endpush
Try This:
public function show() {
$pemeliharaan = Pemeliharaan::where('user','alat')->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}

Ajax and Django

I have a jquery ajax code that looks like below,Its working on a delete button and a checkbox.
$(".delete-row").click(function(){
$("table
tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
var value = $('chk').val();
$(this).parents("tr").remove();
$.ajax({
url: "/delete/",
// type: "post", // or "get"
data: value
});
});
});
});
This jquery call should delete the checked row in a table and the added ajax call will call a django view.
My doubt is I am passing the checkbox value to django view in the above AJAX call. In this case how do django view come to know what table row to delete based on the checkbox value?
below is how my table is getting created in a for loop
{% for x in dirs %}
<tr id='this_row' style="text-align: center;">
<td>
<input type="checkbox" id="chk" value="this_row" name="record"></td>
<td>
{{ x.name }}
</td>
<td>
{{ x.created_date }}
</td>
<td>
{{ x.description }}
</td>
</tr>
{% endfor %}
below is the delete button
<button type="submit" name="erase" class="delete-row">Delete Row</button>
Just add the id of the row as value attribute to the checkbox, so your ajax will send a list of ID. Instead of this_row, add {{x.id}} the instance id
{% for x in dirs %}
<tr id='tr-{{x.id}}' style="text-align: center;">
<td><input type="checkbox" id="chk-{{x.id}}" value="{{x.id}}" name="record"></td>
<td>
{{ x.name }}</td>
<td>{{ x.created_date }}</td>
<td>{{ x.description }}</td>
</tr>
{% endfor %}
And in your ajax, you have access to it with
// send this array via ajax
$(".delete-row").click(function(){
var id_list = new Array();
$("input[name=record]:checked").each(function(){
id_lists.push($(this).val());
$(this).parent("tr").remove(); // Remove the row,
// the correct is parent() without 's', not parents()
});
// with type:'post', don't forget the csrf_token
$.ajax({
url: "/delete/",
type: "post",
data: {
id_list:id_list,
csrfmiddlewaretoken:"{{ csrf_token }}"
},
});
});
And in your view, you can retrieve the id_list containing all the selected rows with reqest.POST.getlist('id_list[]'). In case it was a GET request reqest.GET.getlist('id_list[]')

Cannot access id being passed in vue.js and laravel

I am having hard time inserting the values which is the id that is being passed from the form into the controller of my enrollment system. To achieve this I make use of vue.js and vue-resource library. In my all.js file I am gettting the correct id value when I console.log the id being passed. However, when passing it to the route address of my application I am getting 500 error. Also, upon debugging I' m getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'section_subject_id' cannot be null (SQL: insert into reservations. How can I solve this?
ReservationController.php
class ReservationController extends Controller
{
public function create($id)
{
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects'));
}
public function store(Request $request)
{
$subject = new Reservation();
$subject->section_subject_id = $request->input('id');
$subject->student_id = 1;
$subject->save();
}
}
all.js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#app-layout',
data: {
subject: {
id : ''
},
subjects: []
},
ready: function(){
},
methods:{
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', id, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}
}
});
form.blade.php
<body>
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id }} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
Try formatting the data being sent like this: {id: this.id}
So your Vue addSubject Method looks like this:
addSubject: function(id){
this.subject = id;
this.$http({url: 'http://localhost:8000/reservation', {id: this.id}, method: 'POST'}).then(function(response){
}, function (response){
console.log('error');
});
}

laravel delete is not working

I am wondering how to put a csrf token in a form so that delete will work?
Here is my code:
Route:
Route::delete('category_delete/{id}',['as'=>'category_delete','uses'=>'CategoryController#destroy']);
index.blade.php
#section('adminContent')
{!! Form::token() !!}
<div class="table-responsive art-content">
<table class="table table-hover table-striped">
<thead>
<th> NAME</th>
<th> ACTIONS</th>
</thead>
<tbody>
#foreach($categoriesView as $category)
<tr>
<td>{!! $category->name!!}</td>
<td>{!! link_to_route('categories.edit', '', array($category->id),array('class' => 'fa fa-pencil fa-fw')) !!}</td>
<td><button type="button" id="delete-button" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="pagination"> {!! $categoriesView->render() !!}</div>
</div>
#stop
CategoryController:
public function destroy($id,Category $category)
{
$category = $category->find ( $id );
$category->delete ();
Session::flash ( 'message', 'The category was successfully deleted!.' );
Session::flash ( 'flash_type', 'alert-success' );
}
If I used ajax, javascript or jquery, how should the code be?
Using jquery I would do something like the following.
Add the line below in the header of your home view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Now in your javascript
function deleteMe(button)
{
// You might want to put the ajaxSetup function where it will always load globally.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if(confirm("Are you sure?"))
{
$.get(
'category_delete/'+button.id,
function( response )
{
// callback is called when the delete is done.
console.log('message = '+ response.message);
}
)
}
}
In index.blade.php, make your id more specific.
...
<td><button type="button" id=".$category->id" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o" onlick="deleteMe(this);></i></button>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return response()->json(
'message' => 'Deleted',
)
}
Note: No need to add
Form::token in your view
Hope this helps.....
Updated...........
If you were to do it using laravel only, I will suggest you use a link rather than the button you are using.
In index.blade.php, make your id more specific.
...
<td><a href="category_delete/".$category->id class="delete-button" data-url = "{!! url('category_delete')!!}"><i class="fa fa-trash-o"></i></td>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return view('index');//important.
}
If you want your link to look like a button, use css or a css framework like bootstrap
That should be it. hope this helps again.

Resources