Bootbox.js Confirm choice before submitting form - php

Hello I have decided to use Bootbox.js as a simple way to incorporate a bootstrap modal so that I can make the user confirm their choice before the form is posted and the changes are made.
I am using Laravel, jQuery, Bootstrap and Bootbox.js in my default layout file:
Layout.blade.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"></script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script src="js/vendor/bootstrap.js"></script>
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<script src="js/vendor/bootbox.js"></script>
User Page:
{{Form::open('choice')}}
#foreach($items as $item)
<tr>
<td>{{ HTML::image($item->image, '', array('class' => 'img img-rounded', 'width' => '100px', 'height' => '100px')) }}</td>
<td>{{$item->name}}</td>
<td>{{ $item->desc }}</td>
<td>{{ Form::radio('item', $item->item_id)}}</tr>
#endforeach
</tbody>
</table>
{{ Form::submit('Confirm Choice', array('class' => 'btn btn-success btn-block')) }}
<script>
$(document).ready(function() {
$(document).on("click", ".alert", function(e) {
bootbox.confirm("Are you happy with the decision you have made?", "I have changed my mind", "I am happy with my choice", function(result) {
if (result) {
console.log("user confirmed");
} else {
console.log("user declined");
}
});
});
});
</script>
{{Form::close()}}
I do not know how to make the modal appear before and prevent submission. But only post if the user has confirmed their choice?

Adding e.preventDefault() in the onClick handler will prevent the form submission.
<script>
$(document).ready(function() {
$(document).on("click", ".alert", function(e) {
e.preventDefault();
bootbox.confirm("Are you happy with the decision you have made?", "I have changed my mind", "I am happy with my choice", function(result) {
if (result) {
console.log("user confirmed");
} else {
console.log("user declined");
}
});
});
});
</script>

Related

Am not able to insert data into database using ajax laravel

I am trying to take amount from the html tags and store the amount into database but the about here
ajax code is not working and data is not stored in the database. And how to know if ajax code is redirected it's control to the laravel controller
#include('layouts.students.header')
<meta name="csrf-token" content="{{csrf_token()}}">
<body>
<div class="col">
<p class="text-right" style="font-size: 18px;">
<i class="fa fa-rupee"></i><strong
class="amount">299</strong>
</p>
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-block btn-lg
buy_now">Proceed</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('button').click(function(event){
e.preventDefault();
var amount = $('.amount').html();
$.ajax({
url : '{{route('razorpay')}}',
method : 'POST',
dataType : 'jason',
data : {amount :amount * 100},
success : function (Response) {
console.log(Response);
}
});
});
});
</script>
</body>
</html>
controller :
public function dopayment(Request $request)
{
$data = $request->all();
$result = Payment::insert($data);
echo "inserted";
}
In ajax method can you use dataType : 'json', instead of jason

Laravel pagination without refreshing page

I found this Ajax for pagination without refreshing the page.
Pagination works, but page is refreshing every time, it's annoying because table is on bottom of the page.
Can you check, maybe I made some mistake. Or give me some ideas to fix this.
Controller:
public function index(Request $request)
{
$satwork = DB::table('companies')
->leftJoin('devices', 'companies.id', '=', 'devices.companyId')
->leftJoin('vehicles', 'devices.id', '=', 'vehicles.deviceId')
->leftJoin('drivers', 'vehicles.id', '=', 'drivers.vehicleId')
->select('companies.company_name', 'devices.device_type', 'vehicles.license_plate', 'drivers.driver_name')
->paginate(5);
return view('/welcome', compact('satwork'));
}
public function fetch_data(Request $request)
{
if ($request->ajax())
{
$satwork = DB::table('companies')
->leftJoin('devices', 'companies.id', '=', 'devices.companyId')
->leftJoin('vehicles', 'devices.id', '=', 'vehicles.deviceId')
->leftJoin('drivers', 'vehicles.id', '=', 'drivers.vehicleId')
->select('companies.company_name', 'devices.device_type', 'vehicles.license_plate', 'drivers.driver_name')
->paginate(5);
return view('pagination', compact('satwork'))->render();
}
}
welcome.blade
<div class="container">
<div id="table_data">
#include('pagination')
</div>
</div>
</div>
<!-- pagination -->
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
fetch_data(page);
});
function fetch_data(page) {
$.ajax({
url: "//pagination?page=" + page,
success: function(satwork) {
$('#table_data').html(satwork);
}
});
}
});
}
</script>
pagination blade
<tbody>
#foreach ($satwork as $row)
<tr>
<td>{{ $row -> company_name}}</td>
<td>{{ $row -> device_type}}</td>
<td>{{ $row -> license_plate}}</td>
<td>{{ $row -> driver_name}}</td>
</tr>
#endforeach
</tbody>
{!! $satwork->links() !!}
routes
Route::get('/', 'WelcomeController#index');
Route::get('/welcome/pagination', 'WelcomeController#fetch_data');
Your ajax request URL to fetch the pagination is not correct.
url: "//pagination?page=" + page
That should be url: "/welcome/pagination?page=" + page
function fetch_data(page) {
var l = window.location;
// the request path should be
// domain.com/welcome/pagination
$.ajax({
url: l.origin + l.pathname + "?page=" + page,
success: function(satwork) {
$('#table_data').html(satwork);
}
});
}
It can be done with dataTables
Script:
<script>
$(document).ready(function() {
$('#companies').DataTable({
"lengthMenu": [[2, 3, 5, 10, 20, -1], [2, 3, 5, 10, 20, "All"]]
});
});
</script>
Style:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
And it's working.

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

JQueryUI dialog not working in my laravel application

In My view file I am importing my necessary libraries as following
{{ Html::script(asset('js/jquery-1.11.0.min.js')) }}
{{ Html::script(asset('js/jquery-ui.min.js')) }}
{{ Html::style(asset('css/jquery-ui.css')) }}
Then I have the following in my view to create dialog:
<button id="hello">Click Me</button>
<div id="dialog1" style="display:none">
<div>
Hello World
</div>
</div>
And just at the bottom I have the following Script:
$(document).ready(function () {
$("#dialog1").dialog({
autoOpen: false,
modal: true
});
});
$("#hello").click(function() {
$("#dialog1").dialog('open');
});
The same thing is working in jsfiddle but not in my laravel. Do i need to do anything? I am getting the the following error in the console:
Uncaught TypeError: $(...).dialog is not a function
Here is how my files are loaded
#extends('layouts.headerfooter')
#section('content')
{{ Html::style(asset('css/home.css')) }}
{{ Html::script(asset('js/home.js')) }}
<script src="https://code.jquery.com/jquery-1.12.1.js" integrity="sha256-VuhDpmsr9xiKwvTIHfYWCIQ84US9WqZsLfR4P7qF6O8=" crossorigin="anonymous"></script>
{{Html::script('https://code.jquery.com/jquery-1.12.1.js')}}
{{ Html::script('js/jquery-ui.min.js') }}
{{ Html::style('css/jquery-ui.css') }}
<script>
$(document).ready(function () {
$("#dialog1").dialog({
autoOpen: false,
modal: true
});
});
$("#hello").click(function() {
$("#dialog1").dialog('open');
});
</script>
<div>
</div>
#endsection
it might be that your jquery-ui is customize and doesnt include dialog widget, try also putting your
$("#hello").click(function() {
$("#dialog1").dialog('open');
});
inside the $(document).ready(...)

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).

Categories