Laravel Ajax Add To Cart Not working 500 internal error - ajax

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

Related

How to fetch next record from DB when a user submits Answer or Time is finished in laravel 8?

Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Events extends Model
{
use HasFactory;
use SoftDeletes;
public function EventQues()
{
return $this->hasMany(Questions::class, 'event_id')->limit(1);
}
}
Controller
public function ActiveEvent()
{
$display = Events::where('status', 1)->with('EventQues')->first();
// $next = Questions::where('id', '>',$request->id)->where('is_deleted',0)->first('id');
return view('frontend.index', compact('display'));
}
// function for front send answer value to DB
public function getData(Request $request)
{
$value = $request->all();
return response()->json($value, 200);
}
view
#extends('frontend.master')
#section('title', 'Home')
#section('content')
{{-- top menu Start --}}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand text-uppercase font-weight-bold" href="#">Logo</a>
<div class="col-2">
<h5 class=" dropdown-toggle text-light" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">{{ Auth::user()->name }}</h5>
<div class="dropdown-menu mt-1" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="{{ route('twitch.logout') }}">Log Out</a>
</div>
</div>
</div>
</nav> {{-- top menu end --}}
<div class="container-fluid">
<div class="row">
<div class="card shadow col-lg-8 col-md-8 col-sm-12 m-4">
<div class="card-body ">
<div id="twitch-embed"></div>
</div>
</div>
<div class="card shadow col-lg-3 col-md-3 col-sm-12 m-4">
<div class="card-body">
<div id="list-example" class="list-group mt-2">
#if (!$display)
<h2 class="font-weight-bold mt-5" id="Nothing">Currently No Event Is Active</h2>
#else
<h3 class="font-weight-bold p-2 text-light text-center bg-primary">{{ $display->title }}</h3>
<p class="text-justify">{{ $display->description }}</p>
{{-- Displaying questions of Active event from database --}}
<h4 class="text-center p-2">Time :<span id="timer"> </span></h4>
#foreach ($display->EventQues as $data)
<div id="quesDiv"></div>
<div id="quesDiv1">
<h5 id="question">{{ $data->question }}</h5>
<form >
#csrf
<div class="btn btn-group-toggle d-flex flex-column" id="radioDiv"
data-toggle="buttons">
<label class="btn btn-secondary mb-2">
<input type="radio" name="options" id="option_a1" class="answer-check-box"
autocomplete="off" data-value="1"> Yes
</label>
<label class="btn btn-secondary">
<input type="radio" name="options" id="option_a2" class="answer-check-box"
autocomplete="off" data-value="2"> NO
</label>
</div>
</form>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
#include('frontend.script')
#endsection
Script.js
$('#option_a1,#option_a2').click(function() {
if (options = $("input[type='radio']:checked")) {
val = options.attr('data-value');
} else if (options = $("input:checkbox:not(:checked)")) {
val = "";
}
});
let interval = setInterval(req, 1000);
function req() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if (val || timeleft < '0') {
$.ajax({
type: "post",
url: "{{ route('ajax') }}",
data: {
'id': '{{ $data->id }}',
'value': val
},
success: function(data) {
$('#quesDiv1').hide();
$('#quesDiv').html('Next Question');
},
error: function(data) {
console.log('error!!')
}
});
var timeOut = setTimeout(interval, 1000);
}
// clearInterval(interval);
}
I am making an app where I have made one to many relation between events and questions. When an event is active questions related to this event are displayed one at a time and when a user submits an answer then fetch the next question from Database. And I was using Ajax call for this.

How to make a select field (year list) unique per ID or number and remove the selected year from the dropdown list?

I'm new to laravel, I'm trying to achieve a functionality when selecting a year for a specific ID or number that year will be removed from the dropdown list or it will not be listed.
Below I added screenshots and my code so far. I'm actually struggling to figure this out. :(
Please let me know if you need to check my controller.php and others.
Here's my code:
JS:
$(document).ready(function () {
// input fields
$("#tax-dec-form").on('submit', function (e) {
e.preventDefault()
$('#tax-dec-form').find('span.error').remove() //resets error messages
let _url = null;
let data = $('#tax-dec-form').serialize();
if ($('#tax-dec-form').hasClass('new')) {
_url = 'add-tax-info'
data = $('#tax-dec-form').serialize() + "&pin_id=" + pin_id
} else {
_url = 'update-tax-info'
}
$.ajax({
url: _url,
type: "POST",
data: data,
success: function (response) {
if (response.code == 200) {
//console.log(response)
$('#tax-dec-form').removeClass('new');
swal({ title: "Success!", text: response.message, type: "success", buttonsStyling: false, confirmButtonClass: "btn btn-success" })
}
},
error: function (response) {
console.warn(response.responseJSON.errors)
$.each(response.responseJSON.errors, function (field_name, error) {
if ($(document).find('#tax-dec-form [name=' + field_name + ']').next().is('span')) {
$(document).find('#tax-dec-form [name=' + field_name + ']').next('span').remove()
}
$(document).find('#tax-dec-form [name=' + field_name + ']').after('<span class="error text-danger">' + error + '</span>')
})
}
})
})
$('[data-toggle="tooltip"]').tooltip()
})
//for dynamic year list
$(document).ready(function () {
var d = new Date();
for (var i = 0; i <= 40; i++) {
var option = "<option value=" + parseInt(d.getFullYear() + i) + ">" + parseInt(d.getFullYear() + i) + "</option>"
$('[id*=DropDownList1]').append(option);
}
});
Blade.php:
<div class="content menu-css">
<div class="container-fluid">
{{-- upper form here --}}
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header card-header-primary">
<h4 class="card-title">Tax Information</h4>
<p class="card-category">Please complete all fields</p>
</div>
<div class="form-group">&nbsp</div>
<div class="card-body">
#if (session('status'))
<div class="row">
<div class="col-sm-12">
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="material-icons">close</i>
</button>
<span>{{ session('status') }}</span>
</div>
</div>
</div>
#endif
<div class="form_container">
<form action="/action_page.php" id="tax-dec-form" {{$taxesInfo !== null ? '' : 'class=new'}}>
#csrf
<div class="form-group">
<label for="taxdeclarationnumber">Tax Declaration No:</label>
<input value="{{ $taxesInfo->tax_declaration_number ?? ''}}" type="text" class="form-control" name="tax_declaration_number" placeholder="Input Tax Declaration No..">
</div>
<div class="form-group">&nbsp</div>
<div class="form-group">
<label for="current">Current RPT: </label>
<input type="text" value="{{ $taxesInfo->current_rpt ?? ''}}" class="form-control" name="current_rpt" placeholder="Input Current RPT..">
</div>
<div class="form-group">
<label for="years" class="bmd-label-static">Select Tax Declaration Year</label>
<select id="DropDownList1" class="custom-select mr-sm-2" data-style="btn btn-secondary" name="year">
</select>
</div>
</form>
</div>
<div class="clearfix"> </div>
<div id="form-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="btn-save1">Save</button>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>

Ajax call route laravel not found

i want to make delete confirmation laravel with Modal,
i call route laravel in ajax, but why the route is not found .
this is my route in laravel
Route::delete('delete-product/{productId}', 'StoreController#hapus')->name('product.delete');
this is my ajax delete..
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
$('.modal-footer').on('click', '.hapus', function() {
$.ajax({
type: 'DELETE',
url: 'delete-product/' + productId,
data: {
'_token': $('input[name=_token]').val(),
},
when i click icon trash,, modal is show, but in modal when i click delete button then inspect element in browser my route is not found
this is inspect element
Request URL: http://localhost:8000/delete-product/
Request Method: DELETE
Status Code: 404 Not Found
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
why the URL just delete/product .... not include ID ,,
even though my url in ajax called like this
......
url: 'delete-product/' + productId,
.....
this is my blade code
#if(sizeof($resp->content) > 0)
<ul class="the-product">
#foreach($resp->content as $item)
<li>
#if(isset($store) && $store->storeId == $item->store->storeId)
<i class="icofont-ui-love"></i>
#else
<a class="btn btn-danger delete-modal"><i class="fa fa-trash" data-id="{{$item->productId}}"></i></a>
<a class="btn btn-danger" onclick="return myFunction();" href="{{url('edit.product', $item->productId)}}"><i class="icofont-ui-edit"></i></a>
{{-- <i class="icofont-ui-edit"></i> --}}
{{-- <i class="icofont-ui-delete"></i> --}}
#endif
{{-- onclick="ajaxContent(event, this);" --}}
<a href="productDetail/{{ $item->productId }}" class="the-item #if($item->discount > 0)on-promo #endif">
#if($item->discount > 0)
<div class="prod-rib">{{ $item->discount }}% Off</div>
#endif
<img data-src="#if($item->imageId != null){{ config('constant.showImage').$item->imageId }}#else{{ asset('images/no-image-available.png') }}#endif"
src="#if($item->imageId != null){{ config('constant.showImage').$item->imageId }}#else{{ asset('images/no-image-available.png') }}#endif"
alt="{{ $item->productNm }}">
<div class="prod-name">{{ $item->productNm }}</div>
<div class="prod-rev">
#for($i=0; $i<5;$i++)
#if($i<$item->reviewRate)
<img src="{{asset('img/kopi-on.svg')}}" />
#else
<img src="{{asset('img/kopi.svg')}}" />
#endif
#endfor
<span>{{ $item->reviewCount }} ulasan</span>
</div>
<div class="prod-price">
#if($item->discount > 0)
<span>Rp. {{ number_format($item->price,0,',','.') }}</span> Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
#else
Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
#endif
</div>
</a>
Add to cart <i class="icofont-cart"></i>
{{-- //onclick="ajaxContent(event, this);" --}}
<a href="{{url('/store-detail/'.$item->store->storeId)}}" class="the-store">
<img src="#if($item->store->storePic != null){{ config('constant.showImage').$item->store->storePic }}#else{{ asset('images/no-image-available.png') }}#endif" />
{{ $item->store->storeNm }}
<span>{{ $item->store->percentFeedback }}% ({{ $item->store->totalFeedback }}
feedback)</span>
</a>
</li>
#endforeach
</ul>
<ul class="pagination">
<li class="disabled">
<span><i class="icofont-rounded-double-left"></i></span>
</li><li class="disabled">
<span><i class="icofont-rounded-left"></i></span>
</li>
{{-- active --}}
#for ($i = 0; $i < $resp->totalPages && $i < 5; $i++)
<li class="" onclick="ajaxContent(event, this,null,{'key':'page','value':{{$i+1}} })">
<span>{{$i + 1}}</span>
</li>
#endfor
<li>
<i class="icofont-rounded-right"></i>
</li>
<li>
<i class="icofont-rounded-double-right"></i>
</li>
</ul>
#else
<div class="container clearfix">
<div class="style-msg errormsg mt-5">
<div class="sb-msg"><i class="icon-remove"></i><strong>Maaf</strong>, pencarian anda tidak cocok dengan
produk apapun. Silahkan coba lagi
</div>
</div>
</div>
#endif
<!-- Modal form to delete a form -->
<div id="deleteModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<h3 class="text-center">Are you sure you want to delete the following post?</h3>
<br />
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2" for="id">ID:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="id_delete" disabled>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-10">
<input type="name" class="form-control" id="title_delete" disabled>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger hapus" data-dismiss="modal">
<span id="" class='glyphicon glyphicon-trash'></span> Delete
</button>
<button type="button" class="btn btn-warning" data-dismiss="modal">
<span class='glyphicon glyphicon-remove'></span> Close
</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
$('.modal-footer').on('click', '.hapus', function() {
$.ajax({
type: 'DELETE',
url: 'delete-product/{productId}',
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
</script>
how to write URL in ajax ?
plis HELP..
In your case, in the following code :
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
ProductId is a local variable having scope function scope. You can not refer it outside unless you declare it globally at the top.
When you try to refer it directly later, it will not be having any value(undefined).
Secondly, You need to change
url: 'delete-product/{productId}'
with
url: '/delete-product/' + productId,
So below is the code :
jQuery(document).ready(function($){
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
});
$('.modal-footer').on('click', '.hapus', function() {
var productId = $('#id_delete').val();
$.ajax({
type: 'DELETE',
url: '/delete-product/' + productId,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
});

Call method other component in vue

How to call method other component in Vue?
I have component HeaderSearch
<template>
<form action="">
<div class="form-group">
<div class="input-group">
<span class="input-group-btn">
<button class="btn" type="button">
<i class="fa fa-search"></i>
</button>
</span>
<input type="text" #keyup="search(keyword)" v-model="keyword" class="form-control" placeholder="Search...">
</div>
</div>
</form>
</template>
<script>
export default {
data(){
return { keyword: "" };
},
methods: {
search: function(keyword){
if(keyword == ''){
// Want call method fetchPost in PostHome component here
}else{
}
}
}
}
</script>
And I have component PostHome
<template>
<div>
<div class="box r_8 box_shadow" v-for="post in posts">
<div class="box_header">
<a :href="post.url">
<h3 class="mg_bottom_10" v-text="post.title"></h3>
</a>
<small v-text="post.description"></small>
<a :href="post.url" class="box_header_readmore">Read more</a>
</div>
<div class="box_body">
<a :href="post.url" v-show="post.thumbnail">
<img :src="post.thumbnail" class="img_responsive" style="min-height: 300px;background-color: #f1f1f1;
">
</a>
</div>
<div class="box_footer" v-show="post.tags.length > 0">
<ul>
<li v-for="tag in post.tags">
<a v-text="tag.name" href="javascript:void(0)"></a>
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
posts: null,
}
},
methods: {
fetchPosts: function(){
var url = base_url + '/user/posts'
this.$http.get(url).then(res => {
this.posts = res.data;
});
}
},
created: function(){
this.fetchPosts();
}
}
</script>
I want when user type keyup to search then if
keyword == ''
call method fetchPost method in PostHome component
You can use Mixins if that method is reusable.
Reference: https://v2.vuejs.org/v2/guide/mixins.html

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