how to make ajax call inside a edit form view in laravel - ajax

i have created a form for editing the record from db there is different time slots and i want to make delete function for them so i made a ajax call but am confused in URL www.hostname.com/dental/public/admin/manageschedule/1/api/ajax 404 (Not Found)
how to call ajax inside a laravel edit form
here is what i have done:
#extends('admin.layouts.app_inner')
#section('htmlheader_title')
Home
#endsection
#section('content')
#if (count($errors))
#foreach($errors->all() as $error)
<div class="alert alert-danger"><i class="fa fa-fw fa-close"></i> {{ $error }}</div>
#endforeach
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>Success</h4>
{{ $message }}
</div>
#endif
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title text-green"><b>Add Schedule</b></h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
{!! Form::model($doctors, ['method' => 'PATCH','route' => ['manageschedule.update', $doctors->doctor_id],'class' => 'form-horizontal','files'=>true]) !!}
<div class="form-group">
<label class="col-md-3 control-label"> Select Doctor :</label>
<div class="col-md-5">
<select class="form-control" required name="doctor_name">
<?php $results = DB::select(DB::raw("SELECT day FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' Order BY id DESC ")); ?>
<option value="{{$doctors->doctor_name}}" SELECTED="YES">{{$doctors->doctor_name}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" required> Day :</label>
<div class="col-md-5">
<div class="md-checkbox-inline">
<?php $day = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); ?>
#foreach($day as $days)
<input name="day[]" value="<?php echo $days; ?>" type="checkbox" class="md-checkbox" <?php
foreach ($results as $row) {
if ($row->day == $days) {
echo 'checked="checked"';
} else {
}
}
?> >
<label for="checkbox7"> <?php echo $days; ?> </label>
#endforeach
</div>
</div>
</div>
<?php foreach ($results as $row) { $d=$row->day;}
$result= DB::select(DB::raw("SELECT * FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' And day='".$d."' "));
?>
<div class="form-group">
<label class="col-md-3 control-label" required>Time slots</label>
<div class="col-md-6">
<table class="table table-bordered" id="employee_table" width="50%" >
<th>Start Time</th>
<th>End Time</th>
<th>Manage</th>
<?php foreach ($result as $key=>$vari) {
$id = $vari->id;
?>
<tr id="row1">
<td><div class="input-group ">
<input type="text" class="form-control" id="time" placeholder="Start Time" name="s_time[]" value="<?php echo $vari->start_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<td><div class="input-group ">
<input type="text" class="form-control" id="time1" placeholder="Start Time" name="e_time[]" value="<?php echo $vari->end_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<?php if ($key == 0) { ?>
<td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' disabled></td>
<?php } else { ?>
<td><span class='delete' id='del_<?php echo $id; ?>'><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' id='del_<?php echo $id; ?>' ></td>
</tr>
<?php }
}
?>
</table>
<a type="button" onclick="add_rows();" class="fa fa-plus-circle btn btn-primary"> Add More Time Slots</a>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"> Per Patient Time :</label>
<div class="col-md-5">
<div class=" input-daterange">
<input type="text" name="p_time" class="form-control" placeholder="Set per patient time" id="time1" value="<?php
echo $result[0]->p_time; ?>">
<span class="help-block"> You can set only minute </span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Visibility :</label>
<div class="col-md-5">
<input type="radio" id="checkbox2_5" value="Yes" name="visible" class="md-radiobtn" <?php
foreach($result as $check)
{
if($check->visibility=='Yes'){ echo 'checked="checked"';}else{}
} ?> >
<label for="checkbox2_5"> Yes </label>
<input type="radio" id="checkbox2_10" value="No" name="visible" class="md-radiobtn" <?php foreach($result as $check)
{
if($check->visibility=='No'){ echo 'checked="checked"';}else{}
} ?>>
<label for="checkbox2_10"> No </label>
</div>
</div>
<br><br>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right"id="submit">Update Schedule </button>
</div>
{!! Form::close() !!}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time').timepicker();
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time1').timepicker();
})
});
</script>
<script type="text/javascript">
function add_rows()
{
$rowno = $("#employee_table tr").length;
$rowno = $rowno + 1;
$("#employee_table tr:last").after("<tr id='row" + $rowno + "'><td><div class='input-group '><input type='text' class='form-control' placeholder='Start Time' name='s_time[]' onclick=showtime('row" + $rowno + "')><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><div class='input-group '><input type='text' class='form-control' id='time1' placeholder='End Time' name='e_time[]'><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' onclick=delete_row('row" + $rowno + "')></td></tr>");
}
function delete_row(rowno)
{
$('#' + rowno).remove();
}
</script>
<script type="text/javascript">
//Variant Deleting script///
$(document).ready(function () {
// Delete
$('.delete').click(function () {
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
alert('Are you sure you want to delete?');
$.ajax({
url: 'api/ajax',
type: 'delete',
data: {id: deleteid},
success: function (response) {
// Removing row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
}
});
});
});
</script>
<meta name="_token" content="{!! csrf_token() !!}" />
#endsection
here is my controller of api
Route::post('ajax','Controller#ajax')->name('ajax');
here is my web route:
Route::get('/', function () {
return view('auth.login');
});
Route::post('/', function () {
return view('auth.login')->with('successMsg','Please Select A role .');
});
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.home');
Route::resource('managedoctor', 'AddDocController');
Route::resource('managefront', 'AddFrontController');
Route::resource('managepatient', 'AddPatientController');
Route::resource('manageschedule', 'AddScheduleController');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
Route::prefix('doctor')->group(function() {
Route::get('/login', 'Auth\DoctorLoginController#showLoginForm')->name('doctor.login');
Route::post('/login', 'Auth\DoctorLoginController#login')->name('doctor.login.submit');
Route::get('/', 'DoctorController#index')->name('doctor.home');
Route::get('/logout', 'Auth\DoctorLoginController#logout')->name('doctor.logout');
});
Route::prefix('frontdesk')->group(function() {
Route::get('/login', 'Auth\FrontdeskLoginController#showLoginForm')->name('frontdesk.login');
Route::post('/login', 'Auth\FrontdeskLoginController#login')->name('frontdesk.login.submit');
Route::get('/', 'FrontdeskController#index')->name('frontdesk.home');
Route::get('/logout', 'Auth\FrontdeskLoginController#logout')->name('frontdesk.logout');
});

my issue is resolved now the mistake i have done is i was not using the same route group in which am calling the controller with AUTH method

Related

Laravel Ajax Add To Cart Not working 500 internal error

I have code I am working on. I will list the page, the route, and the controller code. When I inspect and click on the add to cart button I get 500 internal server error and I cannot figure out what I did. It should be giving a message checking to see if the item is already in the cart and if not send a message saying item is in the cart but I can't get past the 500 internal server error.
Page
#extends('layouts.frontend.frontend')
#section('title')
Distinctly Mine - {{$products->name}}
#endsection
#section('content')
<div class="py-3 mb-4 shadow-sm babyblue border-top">
<div class="container">
<h6 class="mb-0">Collections / {{$products->category->name}} / {{$products->name}}</h6>
</div>
</div>
<div class="container">
<div class="card-shadow shadow-sm product_data">
<div class="card-body">
<div class="row">
<div class="col-md-4 border-right">
<div class="img-hover-zoom img-hover-zoom--xyz card-img-top">
<img src="{{ asset('backend/uploads/products/'.$products->image) }}" class="w-100 h-100" alt="{{$products->name}}">
</div>
</div>
<div class="col-md-8">
<h2 class="mb-0">{{ $products->name}}</h2>
<hr>
<label for="" class="me-3">Price: ${{$products->original_price}}</label>
<p class="mt-3">{!! $products->small_description !!}</p>
<hr>
#if($products->qty > 0)
<label for="" class="badge bg-success text-dark fw-bold">In Stock</label>
#else
<label for="" class="badge bg-danger text dark fw-bold">Out of Stock</label>
#endif
<div class="row mt-2">
<div class="col-md-2">
<input type="hidden" value="{{$products->id}}" class="prod_id">
<label for="Quantity">Quantity</label>
<div class="input-group text-center mb-3" style="width:130px">
<button type="button" class="input-group-text decrement-btn">-</button>
<input type="text" name="quantity" value="1" class="form-control qty-input" />
<button type="button" class="input-group-text increment-btn">+</button>
</div>
</div>
<div class="col-md-10">
<br />
<button type="button" class="btn btn-warning text-dark fw-bold ms-3 float-start"><i class=" me-1 fa fa-heart text-danger me-1"></i>Add To Wishlist</button>
<button type="button" class="btn btn-success ms-3 float-start text-dark fw-bold addToCartBtn"><i class="me-1 fa fa-shopping-cart text-dark me-1"></i>Add to Cart</button>
</div>
<hr>
<h2>Description</h2>
{{$products->description}}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function (){
$('.addToCartBtn').click(function (e){
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
dataType: "dataType",
success: function (response){
alert(response.status);
}
});
});
$('.increment-btn').click(function (e){
e.preventDefault();
var inc_value = $('.qty-input').val();
var value = parseInt(inc_value,10);
value = isNaN(value) ? 0 :value;
if(value < 10)
{
value++;
$('.qty-input').val(value);
}
});
$('.decrement-btn').click(function (e){
e.preventDefault();
var dec_value = $('.qty-input').val();
var value = parseInt(dec_value,10);
value = isNaN(value) ? 0 :value;
if(value > 1)
{
value--;
$('.qty-input').val(value);
}
});
});
</script>
#endsection
Route
Route::middleware(['auth'])->group(function (){
Route::post('/add-to-cart',[CartController::class,'addProduct']);
});
Controller
<?php
namespace App\Http\Controllers\Frontend;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class CartController extends Controller
{
public function addProduct(Request $request)
{
$product_id = $request->input('product_id');
$product_qty = $request->input('product_qty');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->name." Already Added to cart"]);
}else{
$cartItem = new Cart();
$cartItem->prod_id = $product_id;
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status'=>$prod_check->name." Added to cart"]);
}
}
}
else{
return response()->json(['status'=> "Login To Continue"]);
}
}
}

Banner Images not being reinserted correct to database

When I update my banner_image it should delete the ones from the database Then re insert the ones that are set.
Currently what it does is deletes the banner image but then re inserts blank banner_image
But should remove that enitre row.
Question How to make sure when I update it that will remove the images rows that are no longer selected and not re insert them
public function update($bid = NULL, $data = array()) {
$banner_update = array('banner_title' => $data['banner_title'], 'banner_status' => $data['banner_status']);
$this->db->where('bid', $bid);
$this->db->update('banner', $banner_update);
$this->db->where('bid', $bid)->delete('banner_image');
if (isset($data['banner_image'])) {
$banner_images = array();
$i = 0;
foreach ($data['banner_image'] as $image) {
$banner_images[$i] = array(
'bid' => $bid,
'banner_image' => $image['image'],
);
$i++;
}
$this->db->insert_batch('banner_image', $banner_images);
}
}
View
<?php echo form_open($action);?>
<div class="container">
<div class="card mt-3">
<div class="card-body">
<?php if (validation_errors()) {?>
<?php unset($_POST);?>
<div class="bg-error-warning">
<ul>
<?php echo validation_errors('<li>', '</li>');?>
</ul>
</div>
<?php }?>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<p>Banner Title</p>
<div class="form-group">
<input type="text" name="banner_title" value="<?php echo $banner_title;?>" placeholder="Enter Banner Title" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<table id="images" class="table table-striped table-bordered">
<tbody>
<tr>
<td>
<button type="button" onclick="addImage();" data-toggle="tooltip" title="Add Banner!" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
</td>
</tr>
<?php $image_row = 0; ?>
<?php foreach ($banner_images as $banner_image) { ?>
<tr id="image-row<?php echo $image_row; ?>">
<td>
<a href="" id="thumb-image<?php echo $image_row; ?>" data-toggle="image">
<img src="<?php echo $banner_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" class="img-thumbnail"/></a>
<input type="hidden" name="banner_image[<?php echo $image_row; ?>][image]" value="<?php echo $banner_image['image']; ?>" id="input-image<?php echo $image_row; ?>" />
</td>
</tr>
<?php $image_row++; ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<p>Banner Status</p>
<div class="form-group">
<?php $options = array('0' => 'Disabled', '1' => 'Enabled'); echo form_dropdown('banner_status', $options, $banner_status, array('class' => 'form-control'));?>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<button type="submit" class="btn btn-block btn-dark">Create Banner</button>
</div>
</div>
</div>
</div>
</div>
</div>
<?php echo form_close();?>
<script type="text/javascript">
var image_row = <?php echo $image_row; ?>;
function addImage() {
html = '<tr id="image-row' + image_row + '">';
html += '<td class="text-left">';
html += '<a href="" id="thumb-image' + image_row + '" data-toggle="image" >';
html += '<img src="<?php echo $placeholder; ?>" width="100" height="100" class="img-thumbnail" data-placeholder="<?php echo $placeholder; ?>"/>';
html += '<input type="hidden" name="banner_image[' + image_row + '][image]" value="" id="input-image' + image_row + '" />'
html += '</a>';
html += '</td>';
html += '<td class="text-left">';
html += '<button type="button" onclick="$(\'#image-row' + image_row + '\').remove();" data-toggle="tooltip" title="Remove Banner!" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button>'
html += '</td>';
html += '<script>';
html += '$(document).ready(function(){';
html += '$(\'[data-toggle="tooltip"]\').tooltip();';
html += '});';
html += '<\/script>';
$('#images tbody').append(html);
image_row++;
}
</script>
Have got it working just had to put empty in the foreach loop
public function update($bid = NULL, $data = array()) {
$banner_update = array('banner_title' => $data['banner_title'], 'banner_status' => $data['banner_status']);
// Updates the main banner table
$this->db->where('bid', $bid);
$this->db->update('banner', $banner_update);
// Removes banners so can have clean insert of new banners selected
$this->db->where('bid', $bid);
$this->db->delete('banner_image');
// Inserts new banner images & saved ones.
if ($this->input->post('banner_image')) {
foreach ($this->input->post('banner_image') as $image) {
if (!empty($image['image'])) {
$this->db->insert('banner_image', array('bid' => $bid, 'banner_image' => $image['image']));
}
}
}
}

Validating forms on laravel

Hi i getting this error When I try to validate a form, with this
$this->validate($request, [
'documento' => 'required|unique:cliente|max:55',
]);
htmlentities() expects parameter 1 to be string, array given (View: C:\sisVentas\resources\views\ventas\cliente\create.blade.php)
this is my view please help.
#extends ('layouts.admin')
#section ('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Nuevo Cliente</h3>
#if (count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</div>
{!!Form::open(array('url'=>'ventas/cliente','method'=>'POST','autocomplete'=>'off', 'files'=>'true'))!!}
{{Form::token()}}
<div class="row">
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="empresa">Empresa</label>
<input type="text" name="empresa" value="{{old('empresa')}}" class="form-control"
placeholder="Empresa...">
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="contacto">Direccion</label>
<input type="text" name="direccion" value="{{old('direccion')}}" class="form-control"
placeholder="Direccion...">
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label>Tipo Documento</label>
<select name="tipo_documento" class="form-control">
<option value="J">J</option>
<option value="G">G</option>
<option value="V">V</option>
<option value="E">E</option>
</select>
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="Numero de documento">Numero de Documento</label>
<input type="text" name="documento" id="documento" required value="{{old('documento')}}"
onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="form-control"
placeholder="Numero de Documento...">
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="razon_social">Razon Social</label>
<input type="text" name="razon_social" value="{{old('razon_social')}}" class="form-control"
placeholder="Razon social...">
</div>
</div>
</div>
<div class="row">
<div class="panel panel-primary">
<div class="panel-body">
<div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" name="pnombre" id="pnombre" class="form-control" placeholder="Nombre...">
</div>
</div>
<div class="col-lg-5 col-sm-5 col-md-5 col-xs-12">
<div class="form-group">
<label for="telefonos">Telefonos</label>
<input type="text" name="ptelefono" id="ptelefono" class="form-control"
value="{{old('precio')}}" placeholder="Telefonos...">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="correo">Correo</label>
<input type="text" name="pcorreo" id="pcorreo" class="form-control"
value="{{old('correo')}}" placeholder="correo...">
</div>
</div>
<div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
<div class="form-group">
<button type="button" id="bt_add" class="btn btn-primary">Agregar</button>
</div>
</div>
<div class="col-lg-8 col-sm-8 col-md-8 col-xs-12">
<table id="detalles" class="table table-striped table-bordered table-condensed">
<thead style="background-color: #ccc">
<th>Opciones</th>
<th>Nombre</th>
<th>Contacto</th>
<th>Correo</th>
</thead>
<tfoot>
<th></th>
<th></th>
<th></th>
<th></th>
</tfoot>
<tbody>
</tbody>
</table>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" id="guardar" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
</div>
{!!Form::close() !!}
#push ('scripts') <!-- Trabajar con el script definido en el layout-->
<script>
//////////
$('#guardar').hide();
$(document).ready(function () {
$('#bt_add').click(function () {
agregar();
});
});
var cont = 0;
var total = 0;
subtotal = [];
function agregar() {
nombre = $('#pnombre').val();
telefono = $('#ptelefono').val();
correo = $('#pcorreo').val();
if (nombre != "" && telefono != "") {
total = total + subtotal[cont];
var fila = '<tr class="selected" id="fila' + cont + '"><td><button type="button" class="btn btn-warning" onclick="eliminar(' + cont + ')" >X</button></td><td><input type="text" name="nombre[]" value="' + nombre + '"</td><td><input type="text" name="telefono[]" value="' + telefono + '"</td><td><input type="text" name="correo[]" value="' + correo + '"</td></tr>';
cont++;
limpiar();
$('#detalles').append(fila);
$('#guardar').show();
} else {
alert("Error al ingresar los detalles del contacto, revise los datos del contacto ");
}
}
function limpiar() {
$('#pnombre').val("");
$('#ptelefono').val("");
$('#pcorreo').val("");
}
function eliminar(index) {
$("#fila" + index).remove();
evaluar();
}
</script>
#endpush
#endsection
and this is my controller
<?php
namespace sisVentas\Http\Controllers;
use Illuminate\Http\Request;
use sisVentas\Http\Requests;
use sisVentas\Persona;
use sisVentas\Contacto;
use Response;
use sisVentas\Evento;
use Carbon\Carbon;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use sisVentas\Http\Requests\PersonaFormRequest;
use DB;
class ClienteController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
if ($request)
{
$query=trim($request->get('searchText'));
$clientes=DB::table('cliente')
->where ('empresa','LIKE','%'.$query.'%')
->orwhere ('tipo_documento','LIKE','%'.$query.'%')
->orwhere ('documento','LIKE','%'.$query.'%')
->orwhere ('direccion','LIKE','%'.$query.'%')
->orwhere ('razon_social','LIKE','%'.$query.'%')
->orderBy('codigo_cliente','desc')
->paginate(7);
return view('ventas.cliente.index',["clientes"=>$clientes,"searchText"=>$query]);
}
}
public function create()
{
return view("ventas.cliente.create");
}
public function store (Request $request)
{
$this->validate($request, [
'documento' => 'required|unique:cliente|max:55',
]);
try {
DB::beginTransaction();
$persona=new Persona;
$persona->tipo_documento=$request->get('tipo_documento');
$persona->documento=$request->get('documento');
$persona->empresa=$request->get('empresa');
$persona->direccion=$request->get('direccion');
$persona->razon_social=$request->get('razon_social');
$persona->save();
$id = $persona->codigo_cliente;
$evento=new Evento;
$user = Auth::id();
$evento->cod_usuario=$user;
$evento->tabla='Cliente';
$evento->accion='Nuevo Ingreso';
$evento->codigo_referencia=$id;
$mytime = Carbon::now(' America/Caracas');
$evento->fecha =$mytime->toDateTimeString();
$evento->save();
$nombre=$request->get('nombre');
$telefono = $request->get('telefono');
$correo = $request->get('correo');
$cont = 0;
while ($cont < count($nombre)) {
# code...
$detalle = new Contacto();
$detalle->idempresa=$id;
$detalle->nombre=$nombre[$cont];
$detalle->telefono=$telefono[$cont];
$detalle->correo=$correo[$cont];
$detalle->save();
$cont=$cont+1;
}
DB::commit();
} catch (\Exception $e) {
DB::rollback();
}
return Redirect::to('ventas/cliente/create');
}
public function show($id)
{
return view("ventas.cliente.show",["persona"=>Persona::findOrFail($id)]);
}
public function edit($id)
{
return view("ventas.cliente.edit",["persona"=>Persona::findOrFail($id)]);
}
public function update(PersonaFormRequest $request,$id)
{
$persona=Persona::findOrFail($id);
$persona->tipo_documento=$request->get('tipo_documento');
$persona->documento=$request->get('documento');
$persona->empresa=$request->get('empresa');
$persona->direccion=$request->get('direccion');
$persona->razon_social=$request->get('razon_social');
$persona->update();
$evento=new Evento;
$user = Auth::id();
$evento->cod_usuario=$user;
$evento->tabla='Cliente';
$evento->accion='Modificacion';
$evento->codigo_referencia=$id;
$mytime = Carbon::now(' America/Caracas');
$evento->fecha =$mytime->toDateTimeString();
$evento->save();
return Redirect::to('ventas/cliente');
}
public function destroy($id)
{
$persona=Persona::findOrFail($id);
$clientes = DB::table('cliente')->where('codigo_cliente', '=', $id)->delete();
$persona->update();
$evento=new Evento;
$user = Auth::id();
$evento->cod_usuario=$user;
$evento->tabla='Cliente';
$evento->accion='Eliminar';
$evento->codigo_referencia=$id;
$mytime = Carbon::now(' America/Caracas');
$evento->fecha =$mytime->toDateTimeString();
$evento->save();
return Redirect::to('ventas/cliente');
}
}
this issue appear because one of the value that is between the {{}} returning an array instead of string.
and i think it is in the following code
<input type="text" name="pcorreo" id="pcorreo" class="form-control" value="{{old('correo')}}" placeholder="correo...">
and as I saw in your view code you have an input with name correo[] that is an array, and after the validation failure the controller redirect to the form view, the old('correo') function return an array instead of string

Error 500 in Laravel ajax

I got this error which I tried to fix with no success
in console
xhr.send( options.hasContent && options.data || null );//error
js
var data_id;
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$(".edit_cost").click(function() {
data_id = $(this).closest('div.portlet').attr('data-id');
});
$(".submit_cost").on('click',function(e) {
e.preventDefault();
var type = $(".cost_form").find('input[name="type"]').val();
var cost = $(".cost_form").find('input[name="cost"]').val();
var revenue = $(".cost_form").find('input[name="revenue"]').val();
var profit = $(".cost_form").find('input[name="profit"]').val();
var data = $("form.cost_form").serialize();
alert(data);
$.ajax({
url: "/partA-edit-cost",
type: "POST",
data: {
// 'types': type,
//'cost': cost,
// 'revenue': revenue,
// 'profit': profit,
// 'data_id': data_id
// 'data' : data
},
error: function(data) {
console.log(data);
},
success: function(log) {
console.log(log);
}
})
});
});
Routes
Route::post('/partA-edit-cost', 'CostController#editCost');
html
#foreach($costs as $widget)
<li data-row="1" data-col="1" data-sizex="3" data-sizey="3">
<div class="portlet portlet-sortable light bordered ui-widget-content ui-resizable" data-id="{{$widget->id }}" data-find="{{$widget->id.$widget->name }}" data-name="{{ $widget->name }}">
<div class="portlet-title ui-sortable-handle">
<div class="caption font-green-sharp">
<i class="fa fa-money"></i>
<span class="caption-subject bold uppercase">{{ $widget->name }}</span>
</div>
<div class="actions">
<a href="javascript:;" class="btn btn-circle btn-default btn-sm remove">
<i class="fa fa-trash-o"></i> Remove </a>
<div class="btn-group">
<button type="button" class="btn btn-primary edit_cost" data-toggle="modal" data-target="#cost"><i class="fa fa-edit" data-button ="{{$widget->id}}"></i>Edit</button>
</div>
<a class="btn btn-circle btn-icon-only btn-default fullscreen" href="javascript:;"></a>
</div>
</div>
<div class="portlet-body">
<div>{!! html_entity_decode($widget->api) !!}</div>
</div>
</div>
</li>
#endforeach
<div class="modal fade bs-example-modal-sm cost" id="cost" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" id="cost">
<div class="modal-content">
<div class="col-md-12" style="width:500px;">
<div class="portlet box white">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Edit Cost
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="/partA-edit-cost" class="cost_form" method="POST">
<div class="form-actions top">
<button type="submit" class="btn green submit_cost">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
<div class="form-body">
<div class="form-group">
<label class="control-label">Type</label>
<input type="text" name="type" class="form-control type" placeholder="Enter Cost type">
</div>
<div class="form-group">
<label class="control-label">Cost</label>
<input type="text" name ="cost" class="form-control" placeholder="Enter Cost">
</div>
<div class="form-group">
<label class="control-label">Revenue</label>
<input type="text" name="revenue" class="form-control" placeholder="Enter Revenue">
</div>
<div class="form-group">
<label class="control-label">Profit</label>
<input type="text" name="profit" class="form-control" placeholder="Enter Profit">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Cost;
class CostController extends Controller
{
public function editCost(Request $request)
{
$type = $request->get('type');
//$id = $request->get('id');
$cost = COST::where('id', 3);
$cost->type = "type";
$cost->save();
return \Response::json(['id' => $id,'type' => $type],200);
}
}
Disable temporarily stuff inside the editCost method will remove the error
public function editCost(Request $request) {
echo "ok";
}//returns on "ok " to the console;
I think there is any error at $cost = COST::where('id', 3);, try changing it to
$cost = Cost::where('id', 3)->first();
$cost = COST::where('id', 3); results query scope not the Model, therefore you should add first() method, if no result matches your condition it will return null which can also result in the internal error issue since, you are calling $cost->type on the next line.
I hope this helps.
In your code the variable $id is not defined in your return statement ( you have commented it out )
return \Response::json(['id' => $id,'type' => $type],200);
I think the code should look like:
$type = $request->get('type');
//$id = $request->get('id');
$cost = Cost::where('id', 3)->first();
$cost->type = "type";
$cost->save();
return \Response::json(['id' => 3,'type' => $type],200);
If that works you can use the dynamic $id and $type variables

how to validate a field in tab?

I need that the customer field is required, if it is empty when pressing the continue button, this not must allow continue to next step and it then should appear a message indicating that the field is empty and need be completed.
Please, i need a help or advice about how to could make the validation.
Using boostrap.
<ul class="nav nav-pills nav-justified" id="NotTab">
<li class="active disabledTab">1. <?php echo $tab_customer; ?></li>
<li class="disabled disabledTab">2. <?php echo $tab_payment; ?></li>
</ul>
<div id="tab-customer" class="tab-pane active">
<div class="control-group">
<label class="control-label" style="color: #F00;"><b><?php echo $entry_customer; ?></b></label>
<div class="controls">
<input type="text" name="customer" value="<?php echo $customer; ?>" class="span3" onclick="this.select();">
<input type="hidden" name="customer_id" value="<?php echo $customer_id; ?>">
<input type="hidden" name="customer_group_id" value="<?php echo $customer_group_id; ?>">
</div></div>
<div class="form-actions">
<button class="btn btn-primary prevtab" type="button" onclick="return showNext()"><span class="glyphicon glyphicon-arrow-right"></span> Next </button></div>
</div>
<script>
var $tabs = $('#NotTab li');
function showPrev() {
$tabs.filter('.active').prev('li').removeClass("disabled");
$tabs.filter('.active').prev('li').find('a[data-toggle]').each(function () {
$(this).attr("data-toggle", "tab");
});
$tabs.filter('.active').prev('li').find('a[data-toggle="tab"]').tab('show');
$tabs.filter('.active').next('li').find('a[data-toggle="tab"]').each(function () {
$(this).attr("data-toggle", "").parent('li').addClass("disabled");
})
}
function showNext() {
$tabs.filter('.active').next('li').removeClass("disabled");
$tabs.filter('.active').next('li').find('a[data-toggle]').each(function () {
$(this).attr("data-toggle", "tab");
});
$tabs.filter('.active').next('li').find('a[data-toggle="tab"]').tab('show');
$tabs.filter('.active').prev('li').find('a[data-toggle="tab"]').each(function () {
$(this).attr("data-toggle", "").parent('li').addClass("disabled");;
})
}
</script>
Thanks.
You can use a simple check, to check if the input is empty.
if( !$('[name=customer]').val() ) {
alert('Input is empty');
return;
}

Resources