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

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>

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

Every row is executed twice

I have found a bug - and I haven't found any solution to this.
I have a code in ASP.NET Core (using VSPro 2019 16.5.0):
public IActionResult CreateSubGroup(MyClass model, string returnUrl = null)
{
if (ModelState.CreateMyClassValidation())
{
if (!db.MyClass.Where(x => x.Title == model.Title).Any())
{
ViewData["ReturnUrl"] = returnUrl;
var code = new MyClass { Title = model.Title, IdGroup = model.IdGroup, GroupCode = model.GroupCode};
db.MyClass.Add(code);
var result = db.SaveChanges();
if (result > 0)//if there was no issue (at least one row was changed)
{
this.AddNotification(MessagesHandler.Success, $"Item\"{model.Title}\" was successfully created.");
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" cannot be created.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" already exists.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"ErrorMessage.");
}
return RedirectToLocal(returnUrl);
}
Creating of new Item always crashes with unique code exception from DB - During debuging I have found, that every row is executed twice (and I don't know why??) - so also the row db.SaveChanges() is executed twice and that's why I got this exception.
Second bad thing is, that not even the first attempt to save database is not executed (= new Item is not created in DB).
Have you seen this error?
EDIT:
I have found, that it happens only when data are posted from view with JS/AJAX (from modal window)
Here is the code for sending data:
<div class="modal fade" id="ModalWindow" tabindex="-1" role="dialog" aria-labelledby="ModalForm" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="ModalForm" action="" method="post" class="validator">
<div class="modal-body">
<div class="form-group">
<label asp-for="Id"></label>
<input class="form-control" asp-for="Id" value="" readonly data-val="false">
<div class="form-text text-muted small">ID cannot be changed!</div>
</div>
<div class="form-group">
<label asp-for="Title"></label>
<input class="form-control mlfb-create" asp-for="Title" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="Title"></span>
</div>
<div class="form-group">
<label asp-for="IdGroup"></label>
<select class="selectpicker form-control" asp-for="IdGroup" data-live-search="true" data-style="btn-info" tabindex="#(++tabindex)">
#if (data?.GroupData != null)
{
#foreach (var item in data?.GroupData)
{
<option value="#(item.Id)">#item.Title</option>
}
}
</select>
</div>
<div class="form-group">
<label asp-for="GroupCode"></label>
<input class="form-control mlfb-create" asp-for="GroupCode" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="GroupCode"></span>
</div>
</div>
<div class="text-center modal-footer">
<button type="submit" class="btn btn-success _modal-buttton-save" tabindex="#(++tabindex)"><i class="fas fa-check mr-2"></i><span>Save</span></button>
<button type="reset" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script>
$(function () {
"use strict";
$(document).on('click', '._createSubFormButton', function () {
$('#ModalWindow').modal('show');
$('.modal-title').text('Creating of subgroup');
$('.modal-buttton-save span').text('Create');
$('#ModalForm').attr('action', '/MyCode/CreateSubGroup/?returnurl=' + window.location.href);
});
// Edit form
$(document).on('click', 'tr ._editSubFormButton', function () {
$('#ModalWindow').modal('show');
var $tr = $(this).closest('tr');
var Id = $tr.find('._Id').text();
var Title = $tr.find('._Title').text();
var IdGroup = $tr.find('._IdGroup').text();
var GroupCode = $tr.find('._GroupCode').text();
$('.modal-title').text('Editing of subgroup');
$('#ModalForm').attr('action', '/MyCode/EditSubGroup/' + Id + '?returnurl=' + window.location.href);
$('#Id').val(Id);
$('#Title').val(Title);
$('#GroupCode').val(GroupCode);
});
// form validation reset during closing modal form
$('#ModalWindow').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
$('#IdGroup').load();
$('.form-group .is-invalid').each(function () { $(this).removeClass('is-invalid'); });
$('.form-group .is-valid').each(function () { $(this).removeClass('is-valid'); });
$('.form-text.text-danger').each(function () { $(this).removeClass('text-danger'); });
$('.form-text.text-success').each(function () { $(this).removeClass('text-success'); });
$('.invalid-feedback').each(function () { $(this).remove(); });
});
$(document).on('submit', '#ModalForm', function (e) {
var form = $('#ModalForm');
if (form.valid()) {
console.log(form.serializeArray());
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: form.serializeArray()
}).done(function () {
console.log('done');
$tr.find('._Number').text();
var $tr = $(this).closest('tr');
})
.fail(function () {
console.log('fail');
});
$('#ModalWindow').modal('hide');
}
});
error I got:
Have you tried debugging this code? Debugging with setting breakpoints and stepping through the code would help you find what is wrong with this code.

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

Core MVC 2 and Ajax wrong data type

I apologize for the subject topic too general, I have difficulties with Ajax work at all, I'm not able to sent/get up any response. The topic is probably duplicated, but I do not see the error in my code. All tutorials I found say the same thing but it still dont work for me, please take a look.
View
#model ValueTypeEditViewModel
#{
ViewBag.Title = "Dodaj Wartość";
Layout = "_AdminLayout";
}
<div class="col">
<form asp-action="EditValue" method="post">
<input type="hidden" asp-for="ValueType.ValueId" />
<input type="hidden" asp-for="ValueType.TypeId" />
<div class="form-group">
<label asp-for="ValueType.Value" class="m-1"></label>
<div><span asp-validation-for="ValueType.Value" class="text-danger"></span></div>
<input asp-for="ValueType.Value" class="form-control" />
</div>
#if (Model.IsSysParam)
{
<div class="form-group">
<label asp-for="ValueType.Controller" class="m-1"></label>
<div><span asp-validation-for="ValueType.Controller" class="text-danger"></span></div>
<input asp-for="ValueType.Controller" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ValueType.Code" class="m-1"></label>
<div><span asp-validation-for="ValueType.Code" class="text-danger"></span></div>
<input asp-for="ValueType.Code" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ValueType.Description" class="m-1"></label>
<div><span asp-validation-for="ValueType.Description" class="text-danger"></span></div>
<textarea asp-for="ValueType.Description" class="form-control"></textarea>
</div>
<div class="form-group">
<label asp-for="ValueType.IsSysParam" class="m-1"></label>
<div><span asp-validation-for="ValueType.IsSysParam" class="text-danger"></span></div>
<input type="checkbox" asp-for="ValueType.IsSysParam" class="form-control" />
</div>
}
#if (Model.ValueType.ValueId != 0)
{
<div class="form-group">
<label asp-for="ValueType.CreateDate" class="m-1"></label>
<label class="m-1">#Model.ValueType.CreateDate</label>
</div>
<div class="form-group">
<label asp-for="ValueType.EditDate" class="m-1"></label>
<label class="m-1">#Model.ValueType.EditDate</label>
</div>
}
#*#if (!Model.IsSysParam)
{
<div class="row">
<div class="col-5">
<select id="lbProducts" class="form-control" asp-items="Model.Products" size="#Model.ListBoxSize" multiple></select>
<label class="m-1">Lista Przedmiotów</label>
</div>
<div class="col-1 align-self-center">
<div class="d-flex justify-content-center">
<button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div>
<div class="col-5">
<select id="lbAddedProducts" class="form-control" size="#Model.ListBoxSize" multiple></select>
#*<form method="post">
<button asp-page-handler="saveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>
</form>
<button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
</div>
}*#
<div class="text-left">
<button class="btn btn-primary mt-1" type="submit">Zapisz</button>
</div>
</form>
<form asp-route="#(Model.IsSysParam ? RouteUrl.Name.SystemList : RouteUrl.Name.CategoryList)" method="post">
<div class="text-left">
<input type="hidden" name="isSysParamCategory" value="#Model.IsSysParam.ToString()" />
<button class="btn btn-secondary btn mt-1">Anuluj</button>
</div>
</form>
<form method="post">
#if (!Model.IsSysParam)
{
<div class="row">
<div class="col-5">
<select id="lbProducts" class="form-control" asp-items="Model.Products" size="#Model.ListBoxSize" multiple></select>
<label class="m-1">Lista Przedmiotów</label>
</div>
<div class="col-1 align-self-center">
<div class="d-flex justify-content-center">
<button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div>
<div class="col-5">
<select id="lbAddedProducts" class="form-control" size="#Model.ListBoxSize" multiple></select>
<button asp-page-handler="saveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>
<button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
</div>
}
</form>
</div>
At View you can see comented code started with - '#if (!Model.IsSysParam)'. Firstly I tried to fire Ajax from 'main' from with asp-page-handler="saveValueItems" at button. Then I added nested form in form with post (there is commented too), in the end I tried to created separeted form in the bottom of example. (by the way, I'm a beginner with mvc and don't really know if I can nesting form in form)
All the time I get the same error
Ajax
$(saveValueItems).click(function () {
var data = [];
var addedItems = $(addedItemList).find('option');
for (var i = 0; i < addedItems.length; i++) {
var item = addedItems[i];
data.push($(item).val());
}
$.ajax({
type: "POST",
url: "/admin/category/editvalue/96/35?handler=saveValueItems",
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('spoko');
},
failure: function (response) {
alert(response);
}
});
})
I hardcoded url to be sure I send request to good action. I have this in mind to test only with this one item/values.
Controller
[ValidateAntiForgeryToken]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "editvalue/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValueAjax)]
public ActionResult OnPostSaveValueItems([FromBody] int[] arrValueItems)
{
string test = "Hello Response Back";
return new JsonResult(test);
}
Startup.cs
I added to Startup.cs ValidateAntiForgeryToken before AddMvc() too
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
services.AddMvc();
Question:
I do not understand why I am sending the wrong data type. I want to send an int table and I receive a message that I'm sending ValueType and the view is expecting ValueTypeEditViewModel.
I do not know where to look for the cause of the error
1 Edit:
All actions for edit page
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}", Name = RouteUrl.Name.SystemCreateValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}", Name = RouteUrl.Name.CategoryCreateValue)]
public ViewResult CreateValue(int typeId, bool isSysParamCategory)
{
return View(RouteUrl.Edit + RouteUrl.Value, new ValueTypeEditViewModel(typeId, isSysParamCategory, repositoryProduct.Products, Convert.ToInt32(repository.GetSysParamByCode(SysParams.ProductListBoxSize))));
}
[HttpGet]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public ViewResult EditValue(int typeId, int valueId)
{
bool isSysParamCategory = repository.GetCategoryByTypeId(typeId).IsSysParam;
return View(RouteUrl.Edit + RouteUrl.Value, new ValueTypeEditViewModel(repository.GetValue(typeId, valueId), isSysParamCategory, repositoryProduct.Products, Convert.ToInt32(repository.GetSysParamByCode(SysParams.ProductListBoxSize))));
}
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public IActionResult EditValue(AureliaCMS.Models.ValueType valueType)
{
if (ModelState.IsValid)
{
repository.SaveValueType(valueType);
return View(RouteUrl.Save, new SaveCategoryType(repository.GetCategoryByTypeId(valueType.TypeId).IsSysParam, valueType.Value, false));
}
else
{
return View(valueType);
}
}

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