Laravel 8 Dynamic Dependent Input - ajax

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212

i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);

Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

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

two select dynamics vue laravel

I want to load 2 select with vue, I have country, city state, but I don't want to call the js from resources / app.js since I don't need it in all the pages only in a particular sight. I am new to vue. when I load it from resources / app.js if it works but only for status but not for city and in the other pages it throws me an error since it cannot find the object.
I don't want to call him here
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
//require('./estado');
//require('./ciudad');
so how do i make the call and where do i put the js files
file get state resources/js/estado.js
const app = new Vue({
el: '#app',
data: {
selected_pais: '',
selected_estado: '',
selected_ciudad: '',
estados: [],
ciudades: [],
},
mounted(){
document.getElementById('estado').disabled = true;
this.selected_pais = document.getElementById('pais').getAttribute('data-old');
if(this.selected_pais !='')
{
this.loadEstados();
}
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
document.getElementById('ciudad').disabled = true;
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
if(this.selected_estado !='')
{
this.cargarCiudades();
}
this.selected_ciudad = document.getElementById('ciudad').getAttribute('data-old');
},
methods: {
loadEstados() {
this.selected_estado ='';
document.getElementById('estado').disabled =true;
if (this.selected_pais !="") {
axios.get(`http://127.0.0.1:80/estados/pais`, {params: {pais_id: this.selected_pais} }).then((response) => {
this.estados = response.data;
document.getElementById('estado').disabled =false;
});
}
},
cargarCiudades() {
this.selected_ciudad ='';
document.getElementById('ciudad').disabled =true;
if (this.selected_estado !="") {
axios.get(`http://127.0.0.1:80/ciudades/estado`, {params: {estado_id: this.selected_estado} }).then((response) => {
this.ciudades = response.data;
document.getElementById('ciudad').disabled =false;
});
}
},
}
});
file get city resources/js/ciudades.js
const app = new Vue({
el: '#app',
data: {
selected_estado: '',
selected_ciudad: '',
ciudades: [],
},
mounted(){
document.getElementById('ciudad').disabled = true;
this.selected_estado = document.getElementById('estado').getAttribute('data-old');
if(this.selected_estado !='')
{
this.cargarCiudades();
}
this.selected_ciudad2 = document.getElementById('ciudad').getAttribute('data-old');
},
method: {
cargarCiudades() {
this.selected_ciudad2 ='';
document.getElementById('ciudad').disabled =true;
if (this.selected_estado !="") {
axios.get(`http://127.0.0.1:80/ciudades/estado`, {params: {estado_id: this.selected_estado} }).then((response) => {
this.ciudades = response.data;
document.getElementById('ciudad').disabled =false;
});
}
}
}
});
files view
#extends('layouts.app')
#section('content')
#inject('paises','App\Services\Paises')
<div class="container">
<div class="row">
<div class="col-md-8">
#if ($errors->any())
<div class="alert alert-danger">
<h4>Por Favor corriga los siguientes errores </h4>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/usuarios" method="POST">
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Nombre</label>
<input type="text" class="form-control" name="nombre" id="inputEmail4" placeholder="Nombre" value="{{old('nombre')}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Email</label>
<input type="text" class="form-control" name="email" id="inputPassword4" placeholder="Email" value="{{old('email')}}">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Direccion</label>
<input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St" name="direccion" value="{{old('direccion')}}">
</div>
<div class="form-row">
<div class="form-group col-md-4" id="div_pais">
<label for="inputCity">Pais</label>
<select v-model="selected_pais" id="pais" data-old="{{old('cbo_pais')}}"
v-on:change="loadEstados()" name="cbo_pais" class="form-control">
#foreach ($paises->get() as $index => $pais)
<option value="{{$index}}" >{{$pais}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Estado</label>
<select v-model="selected_estado" id="estado" data-old="{{old('cbo_estado')}}"
v-on:change="cargarCiudades()" name="cbo_estado" class="form-control" >
<option value="">Selecione un Estado</option>
<option v-for="(estado, index) in estados" v-bind:value="index">#{{estado}}</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState">Ciudad</label>
<select v-model="selected_ciudad" id="ciudad" data-old="{{old('cbo_ciudad')}}"
name="cbo_ciudad" class="form-control" >
<option value="">Selecione un Ciudad</option>
<option v-for="(ciudad, index) in ciudades" v-bind:value="index">#{{ciudad}}</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputZip">Zip</label>
<input type="text" class="form-control" id="inputZip" name="zip">
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Registrar</button>
<button type="reset" class="btn btn-danger">Cancelar</button>
</form>
</div>
</div>
</div>
#endsection
#section('scripts')
#endsection
how do I call the files in the view?

Cannot save value using ajax in laravel

I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());

Laravel Vue.js API: axios' PUT method doesn't send any data to controller

I'm trying to update some data in Model using API in Laravel and Vue.js
but I can't do this because axios doesn't send any data to server, I'm checking the data right before sending and they exist (I use FormData.append to add all fields)
I check data before sending using the code:
for(var pair of formData.entries()) {
console.log(pair[0]+ ': '+ pair[1]);
}
and I get this result:
You can check the appropriate code:
[function for updating]
updateStartup() {
let formData = new FormData();
formData.append('startup_logo', this.update_startup.startup_logo);
formData.append('country_id', this.update_startup.country_id);
formData.append('category_id', this.update_startup.category_id);
formData.append('startup_name', this.update_startup.startup_name);
formData.append('startup_url', this.update_startup.startup_url);
formData.append('startup_bg_color', this.update_startup.startup_bg_color);
formData.append('startup_description', this.update_startup.startup_description);
formData.append('startup_public', this.update_startup.startup_public);
axios.put('/api/startup/' + this.update_startup.id, formData, { headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
}
[controller method where I should receive data]:
public function update(Request $request, $id) {
return $request; // just for checking if I get data
...
}
[HTML with vue.js where I use object which I send in updateStartup function]:
<!-- Modal edit -->
<div class="modal fade editStartUp" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<img src="/admin/images/modal-cross.png" alt="Close">
</button>
</div>
<div class="modal-body">
<form method="POST" enctype="multipart/form-data" #submit.prevent="updateStartup">
<h4 class="sel-c-t">Select category</h4>
<div class="submit-fields-wr">
<select name="category" v-model="update_startup.category_id" class="selectpicker select-small" data-live-search="true" #change="updateCategoryDetails()">
<option v-for="category in categories" :value="category.id" :selected="category.id == update_startup.category_id ? 'selected' : ''" >{{ category.name }}</option>
</select>
<select v-if="update_startup.is_admin" name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
</div>
<div class="submit-fields-wr">
<input type="text" placeholder="Startup name" v-model="update_startup.startup_name">
<input type="url" v-model="update_startup.startup_url" placeholder="URL">
</div>
<textarea v-model="update_startup.startup_description" name="startup_description" placeholder="Describe your startup in a sentence.">
</textarea>
<div v-if="!update_startup.is_admin">
<h4 class="sel-c-t bold">Contact details:</h4>
<div class="submit-fields-wr">
<select name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
<input type="text" placeholder="Your Name" v-model="update_startup.contact_name">
</div>
<div class="submit-fields-wr">
<input type="text" v-model="update_startup.contact_phone" placeholder="Your phone number">
<input type="email" v-model="update_startup.contact_email" placeholder="Your email address">
</div>
</div>
<p class="upl-txt">Company’s logo.<span>(upload as a png file, less than 3mb)</span></p>
<div class="file-upload">
<div class="logo-preview-wr">
<div class="img-logo-preview">
<img :src="update_startup.startup_logo" alt="logo preview" id="img_preview">
</div>
</div>
<label for="upload" class="file-upload_label">Browse</label>
<input id="upload" #change="onFileUpdated" class="file-upload_input" type="file" name="file-upload">
</div>
<div class="preview-divider"></div>
<h4 class="sel-c-t bold">Preview:</h4>
<div class="preview-wrapper-row">
<a href="#" class="start-up-wr">
<div class="start-up-part-1 edit">
<div class="flag-cat-wr">
<div class="flag-wr">
<img :src="update_startup.country_flag" :alt="update_startup.country_name">
</div>
<div class="category-wr">
{{ update_startup.category_name }}
</div>
</div>
<img :src="update_startup.startup_logo" :alt="update_startup.startup_name" class="start-up-logo">
</div>
<div class="start-up-part-2">
<h4 class="startup-name">{{ update_startup.startup_name }}</h4>
<p class="startup-description">
{{ update_startup.startup_description }}
</p>
</div>
</a>
<div class="color-picker-btns-wr">
<div>
<input type="text" class="color_picker" v-model="update_startup.startup_bg_color">
<button class="colo_picker_btn">Background Color</button>
</div>
<div class="modal-bottom-btns">
<div class="btn-deactivate-active">
<button type="submit" class="btn-deactivate" #click="deactivateExistingStartup()">Deactivate</button>
<button type="submit" class="btn-activate" #click="activateExistingStartup()">Activate</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modal edit -->
[Additional info - also when I open modal(where I have form for updating) I change form data accordingly to startup id]:
showUpdateStartup(startup) {
setTimeout(() => {
$('.selectpicker').selectpicker('refresh');
}, 50);
this.update_startup.id = startup.id;
this.update_startup.category_id = startup.category.id;
this.update_startup.category_name = startup.category.name;
this.update_startup.startup_name = startup.name;
this.update_startup.startup_description = startup.description;
this.update_startup.startup_url = startup.url;
this.update_startup.startup_logo = startup.logo;
this.update_startup.startup_bg_color = startup.startup_bg_color;
this.update_startup.contact_id = startup.contact.id;
this.update_startup.contact_name = startup.contact.name;
this.update_startup.contact_phone = startup.contact.phone;
this.update_startup.contact_email = startup.contact.email;
this.update_startup.country_id = startup.contact.country.id;
this.update_startup.country_flag = startup.contact.country.flag;
this.update_startup.country_name = startup.contact.country.name;
this.update_startup.is_admin = startup.contact.is_admin;
this.update_startup.startup_public = startup.public;
},
Let me know if you have any additional questions
Thank you guys a lot for any help and ideas!
Try using formData.append('_method', 'PATCH') with axios.post method.
Return the input data instead of the Request object from your controller:
return $request->input();

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

Resources