how to show laravel blade code in ajax - php

in my index.balde.php
{{ Form::open(['url'=>'/crm/promotion/multi_destroy', 'method'=>'POST', 'id'=>'form_delete_all','class'=>'form-horizontal']) }}
#foreach ($promotions as $promotion)
<tr class="odd gradeX data-table-item">
<td><input type="checkbox" class="multidel" name="multidel_{{$promotion->id}}"></td>
<td>{{$promotion->name}}</td>
<td>{{$promotion->i_name}}</td>
<td>{{ substr($promotion->descr, 0, 100)}}...</td>
<td>{{$promotion->start}}</td>
<td>{{$promotion->end}}</td>
<td>
#if(isset(Session::get('permissions')[$module]))
{{ Render::tableButtons(Session::get('permissions')[$module], $actions['table'] ,array("[ID]" => $promotion->id), array() ) }}
#endif
</td>
</tr>
#endforeach
{{Form::close()}}
when one action change i will show by
if($('#ed').val()!="" && $('#sd').val()=="")
{
$.ajax({
type: "GET",
dataType: "json",
url: '/crm/promotion/promotion_search_end',
data:'end='+$('#ed').val(),
beforeSend: function(){
},
success: function (data)
{
//$('.data-table-item').html('');
$('.data-table-item').empty();
console.log(data);
$.each(data, function(index, item_data)
{
//console.log(item_data.id);
$('#data-table').footable();
$('#data-table').append('<tr class="odd gradeX data-table-item"><td><input type="checkbox" class="multidel" name="multidel_'+item_data.id+'"></td><td>'+item_data.name+'</td><td>'+item_data.i_name+'</td><td>'+item_data.descr+'</td><td>'+item_data.start+'</td><td>'+item_data.end+'</td><td></td></tr>');
});
},
complete: function(){
// do the following after success is done.
},
error: function(){
// do the following if there is error.
}
});
}
I want to use in ajax. How can i use?
#if(isset(Session::get('permissions')[$module]))
{{ Render::tableButtons(Session::get('permissions')[$module], $actions['table'] ,array("[ID]" => $promotion->id), array() ) }}
#endif

You can use laravel blade code in javascript. In your case, you can use like the following
<script>
#if(isset(Session::get('permissions')[$module]))
var value = {{ Render::tableButtons(Session::get('permissions')[$module], $actions['table'] ,array("[ID]" => $promotion->id), array() ) }}
alert(value);
#endif
</script>

Related

PHP Laravel : Delete Data using Ajax

I want to delete some data from database using ajax.. I've done the following steps to run..But while I was trying to delete it's shows following Error:
Failed to load resource: the server responded with a status of 404
(Not Found)
Here is my route:
Route::post('/delete/{id}',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
Here is the controller:
public function delete($id)
{
Item::find($id)->delete();
return Redirect::back();
}
And here is my view page:
<html>
<head>
<title> Item List</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3> List Of Courses </h3></br>
<table class="table table-striped table-bordered dataTable" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Title</td>
<td>Description</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($items as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->title }}</td>
<td>{{$row->description}}</td>
<td>
<button type="button" onclick="deleteItem({{ $row->id }})" id="Reco" class="btn btn-danger">Delete</button>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
<script>
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/delete/'+id,
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
If anyone find the error I've done, hope you'll help me to find it out.
Generally passing parameter while deleting is not a good idea. since we can delete the data through url e.g /delete/4 while you may want to delete only after clicking the delete button.
$.ajax({
type: "POST",
url: "{{url('/delete)}}",
data:{id:id}
success: function(result) {
console.log(result);
}
});
route:
Route::post('/delete',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
and, the controller
public function delete(Request $request)
{
$id=$request->id;
Item::where(['id'=>$id])->delete();
return Redirect::back();
}
Try this code:
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url:"{{url('delete')}}",
data:{id:id},
success: function(result) {
location.reload();
}
});
}
try this code
function deleteItem(id) {
var _token = $("input[name='_token']").val();
$.ajax({
type: "POST",
url: '/task/'+id,
data: '_method=DELETE&_token=' + _token,
success: function (result) {
console.log(result);
}
});
}
Try this:
$.ajax({
type: "POST",
url: url('/delete'), // The correct way to call ajax function in laravel
data:{
id: id
},
success: function(result) {
console.log(result);
}
});
You can set a method destroy in your controller which laravel automatically uses for deleting. It accepts id.
public function destroy($id){
Item::find($id)->delete();
echo 'Deleted Successfully.';
}
for ajax just send a method delete with your token.
jQuery.ajax({
url:'your-controller-route/id',
type: 'post',
data: {_method: 'delete', _token :token},
success:function(msg){
// do stuff
}
});

Symfony: pass parameter to Ajax url

I am trying to figure out how to enable/disable user with checkbox without page reload.
index.html.twig
<table>
<thead>
<tr>
<th>UserName</th>
<th>Enabled</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<td><a href="{{ path('user_show', {'id': user.id}) }}">
{{ user.username }}</a>
</td>
<td><input id="user_enable_{{ user.id }}" onclick="enabledChange({{ user.id }})"
type="checkbox" {% if user.enabled %}checked{% endif %}/>
</td>
{% endfor %}
</tbody>
</table>
<script>
var changePath = {{ path('user_enable_change', {'id': user.id}) }};
function enabledChange(id)
{
var value = $(this).val();
console.log('value: ' + value);
$.ajax({
type: "POST",
url: changePath,
async: true,
data: { },
success: function () {
console.log('success');
}
});
}
</script>
UserController
/**
* #Route("/enable/{id}", name="user_enable_change")
*/
public function userDisableAction(User $user) {
if($user->isEnabled()){
$user->setEnabled(false);
}else {
$user->setEnabled(true);
}
try {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
catch(\Exception $e) {
return new JsonResponse('error');
}
return new JsonResponse('success');
}
Question
How can I set corresponding user id to enabledChange function and change checked state depending on user state?
You need to add quotes to your variables, and pass changePath as an argument:
onclick="enabledChange('{{ user.id }}', '{{ path('user_enable_change', {'id': user.id}) }}')"
then:
function enabledChange(id, changePath) {
var value = $(this).val();
console.log('value: ' + value);
$.ajax({
type: "POST",
url: changePath,
async: true,
data: { },
success: function () {
console.log('success');
}
});
}
I hope this will help.
Another clean way of doing this is by passing parameters and routes via data attributes and accessing the button by class. In my example I had to increase product quantity without refreshing:
<button class="btn btn-sm btn-info increase"
data-id="{{ p.id }}"
data-url="{{ path('cart_add', {'pid': p.id}) }}">
Increase qty
</button>
$(document).ready(function() {
$(".increase").click(function (e) {
var value = $(this).data('id');
console.log('value: ' + value);
$.ajax({
type: "POST",
url: $(this).data('url'),
async: true,
data: {},
success: function () {
console.log('success increment');
}
});
});
});

getting method not allowed exception when send ajax with post method

i develop web application with laravel 5.2 , i try to send an array with ajax to my controller , the request sent but after that i saw the error :405 method not allowed , i searched many times but this problem didn't solve :
my ajax code is :
// send array of stream checkbox to controller
$('#json-btn').click(function () {
var input = $("form input:checkbox");
var stream = [];
$.each($(input), function(){
stream.push($(this).val());
});
var jstream = JSON.stringify(stream);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '/ajaxGet/',
type: 'POST',
data: {_token: CSRF_TOKEN , jstream:jstream},
dataType: 'JSON',
success: function (data) {
alert(data);
}
});
});
my route is :
Route::post('ajaxGet', 'ajaxController#getRequest');
my controller is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class ajaxController extends Controller
{
public function getRequest(Request $request)
{
echo $request['jstream'];
}
}
and finally this is my form :
{!! Form::open(array('id' => 'trailer-form')) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<table dir="rtl">
<thead>
<tr>
<th>quality</th>
<th>link</th>
<th>steram</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{!! Form::select('quality[]', array('noQuality'=>'select...','64p'=>'64p','144p'=>'144p','240p'=>'240p','360p'=>'360p','480p'=>'480p','720p'=>'720p', '1080p'=>'1080p'), null , ['class'=> 'form-control lns' , 'id' => 'quality-input']) !!}
</td>
<td>
{!! Form::text('downLoadLink[]',null,['class' => 'form-control ln' , 'id' => 'down-input']) !!}
</td>
<td>
{!! Form::checkbox('stream[]','false',null,['class' => 'form-control' , 'id' => 'streamCheck' , 'onchange' => 'createAlerts(this)']) !!}
</td>
<td>
<button class="btn btn-success btn-add" type="button">
<i class="glyphicon glyphicon-plus gs"></i>
</button>
</td>
</tr>
</tbody>
</table>
{!! Form::submit('json create',['class' => 'btn btn-success' , 'id' => 'json-btn']) !!}
{!! Form::close() !!}
please help me to solve this problem thank you so very much :)

Symfony delete ajax

I have a problem when I want delete a register with Ajax and Symfony, in template Twig.
<tbody>
{% for entity in entities %}
<tr>
<td>
<a class="delete btn btn-danger btn-xs glyphicon glyphicon-trash" data-playgroup-id="{{ entity.id }}" ></a>
</td>
</tr>
{% endfor %}
</tbody>
Ajax:
$(document).ready(function() {
$(".delete").click(function(){
var pid = $(this).attr("data-playgroup-id");
bootbox.confirm("Are you sure?", function(result) {
if(result){
$.ajax({
url: '{{path('playergroup_delete', { 'id': pid}) }}',
type: 'delete',
success: function(result) {
console.log('Delete');
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
});
I receive the next error:
Variable "pid" does not exists.
Thanks!
As MouradK say you ar passing a variable in a twig function (server side) and you are getting this variable using javascript (client side).
to solve this do something like this :
$(document).ready(function() {
$(".delete").click(function(){
var pid = $(this).attr("data-playgroup-id");
bootbox.confirm("Are you sure?", function(result) {
url = '{{path('playergroup_delete', { 'id': 0}) }}';
url = $url.replace("0",pid);
if(result){
$.ajax({
url: url,
type: 'delete',
success: function(result) {
console.log('Delete');
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
});
It means that you did not pass the pid variable to your Twig template.
Pass it trough the controller and you'll be fine
The error is :
You are trying to set a variable comming from the client (javascript) in your twig template (which is a server side).

Symfony2: The CSRF token is invalid. Please try to resubmit the form

I have a form wher I have to fill in some information in a field.
Even if I put something inside, I am getting the error:
The CSRF token is invalid. Please try to resubmit the form
Related to this question: symfony2 CSRF invalid I am using correctly the $form->bindRequest()
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
if ($form->isValid())
{
...
}
Here is my template (twig) code:
<div class="item item-last">
<h1>Create Affiliation</h1>
{% if valid == false %}
<div class="error">
{{ form_errors(form) }}
{{ form_errors(form.affiliation) }}
{{ error }}
</div>
{% endif %}
{% if app.session.flash('user-notice') != '' %}
<div class="flash-notice">
{% autoescape false %}
{{ app.session.flash('user-notice') }}
{% endautoescape %}
</div>
{% endif %}
</div>
<div class="item item-last">
<form action="{{ path('SciForumVersion2Bundle_user_submission_affiliation_create', {'hash_key' : submission.hashkey, 'author_id' : author.id }) }}?ajax=no" method="POST" class="authorForm" {{ form_enctype(form) }}>
<div style="float:left;">
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td>
{{ form_label(form.affiliation) }}
</td>
<td>
{{ form_widget(form.affiliation, { 'attr': {'size': 40} }) }}
</td>
</tr>
<tr>
<td>
</td>
<td>
<div class="button button-left button-cancel">
<img src="{{ asset('bundles/sciforumversion2/images/design/new/button-red.png') }}"/>
cancel
</div>
<div style="float: left;"> </div>
<div class="button button-left button-cancel">
<img src="{{ asset('bundles/sciforumversion2/images/design/new/button.png') }}"/>
<input type="submit" name="login" value="submit" />
</div>
<div style="clear: both;"></div>
</td>
</tr>
</table>
</div>
{{ form_rest(form) }}
</form>
</div>
And here is the js code:
function init_submission_functions()
{
init_fck();
$(".submission_link").unbind("click").bind("click", function() {
var href = $(this).attr("href");
if( href == null || href == '' ) return false;
$.ajax({
type: "POST",
async: true,
url: href,
cache: false,
dataType: "json",
success: function(data) {
$("#content .contentwrap .itemwrap").html( data.content );
init_submission_functions();
}
});
return false;
});
$(".authorForm").unbind("submit").bind("submit", function() {
var href = $(this).attr("action");
if( href == null || href == '' ) return false;
var affiliation = "blabla";
$.ajax({
type: "POST",
async: true,
url: href,
affiliation: affiliation,
cache: false,
dataType: "json",
success: function(data) {
$("#content .contentwrap .itemwrap").html( data.content );
init_submission_functions();
}
});
return false;
});
}
But I am still getting the same error.
Send a serialized form using the serialize jQuery method:
$form.submit(function (e) {
e.preventDefault();
$this = $(this);
$.post($this.attr('action'), $this.serialize(), function (response) {
// handle the response here
});
});
This way Symfony will handle the submit request as a normal request — you don't have to do anything special to handle an Ajax form submission. All you'll need to do is to return a JsonResponse — if you need it, of course.
Here is an example of handling the form — adapt it to your needs:
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid()) {
// do something here — like persisting or updating an entity
return new JsonResponse([
'success' => true,
]);
}
return new JsonResponse([
'success' => false,
'form' => $this->render($pathToTheTemplateHere, [
'form' => $form,
],
]);
}
The other way would be to use different templates: form.json.twig and form.html.twig — read the docs for details.

Categories