I would like to be able to list the records of two models at the same time, taking into account how I have the query set up at the moment to use it with Ajax.
Right now my query works fine, considering the rest of my project (AJAX - Laravel).
public function allData(){
$data = Siniestro::orderBy('id','DESC')->get();
return response()->json($data);
}
I've tried doing it like this, but it looks like I'm doing the query wrong
public function allData(){
$data = Siniestro::orderBy('id','DESC')->get();
$users = User::all();
return response()->json($data, $users);
}
Edit:
Esta es la vista que estoy refiriendo
This is the view; I want that with the eloquent query, it shows me ordered as now (orderBy), and also that it looks for a match of fields with "where"; for example $siniestros = Siniestro::where('estado', 'coordinado')->get();.
Edit 2
dd($users)
full view code
#extends('layouts.app')
#section('content')
<section class="section">
<div class="section-header">
<h3 class="page__heading">Derivar IP</h3>
</div>
<div class="section-body">
<div class="row">
<div class="col-sm-9">
<div class="card">
<div class="card-header">
Inspecciones coordinadas
</div>
<div class="card-body">
<table class="table table-sm m-1 p-1 table-bordered table-hover table-striped tablita" style="width:100%">
<thead>
<tr>
<!-- <th scope="col">#</th> -->
<th scope="col">Siniestro</th>
<th scope="col">Fecha IP</th>
<th scope="col">Modalidad</th>
<th scope="col">Dirección</th>
<th scope="col">Localidad</th>
<th scope="col">Inspector</th>
<th scope="col">Acciones</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-sm-3" style="position:fixed; bottom:550px; right:0px">
<div class="card">
<div class="card-header">
<span id="addT">Asignar IP</span>
<span id="updateT">Asignar IP</span>
</div>
<div class="card-body">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<input type="text" name="inspector" class="form-control" id="inspector" for="inspector" >
<span class="text-danger" id="instituteError"></span>
</div>
</div>
<div class="col-xs-3 col-sm-3 col-md-3">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" for="inspector" name="inspector" >
<option selected></option>
<option value="Taller del asegurado">Taller del asegurado</option>
</select>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label for="emailperito">E-mail</label>
<input type="text" name="emailperito" class="form-control" id="emailperito" for="emailperito">
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label for="telefonoperito">Teléfono</label>
<input type="text" name="telefonoperito" class="form-control" id="telefonoperito" for="telefonoperito">
</div>
</div>
<input type="hidden" id="id">
<button type="submit" id="updateButton" class="btn btn-primary btn-sm" onclick="updateData(event)">Asignar</button>
</div>
</div>
</div>
</div>
</div>
</section>
#endsection
#section('javas')
<script>
$(document).ready(function() {
$('.tablita').DataTable({
"serverSide": true,
"ajax": "/teacher/all",
"columns": [
// {data: 'id'},
{data: 'siniestro'},
{data: 'fechaip'},
{data: 'modalidad'},
{data: 'direccion'},
{data: 'localidad'},
{data: 'inspector'},
{data: 'action', name: 'action', orderable: true, searchable: true},
],
});
})
</script>
<script>
$('#addT').hide();
$('#addButton').hide();
$('#updateT').show();
$('#updateButton').show();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
//---------------------------------------------- Llamar datos de la BD ---------------------------------------------------------------
function allData(){
$.ajax({
type: "GET",
dataType: "json",
url: "/teacher/all",
success: function (response){
var data = ""
$.each(response, function(key, value){
data = data + "<tr>"
// data = data + "<td>"+value.id+"</td>"
data = data + "<td>"+value.siniestro+"</td>"
data = data + "<td>"+value.fechaip+"</td>"
data = data + "<td>"+value.modalidad+"</td>"
data = data + "<td>"+value.direccion+"</td>"
data = data + "<td>"+value.localidad+"</td>"
data = data + "<td>"+value.inspector+"</td>"
data = data + "<td>"
data = data + "<button class='btn btn-info btn-sm' onclick='editData("+value.id+")'>Asignar IP</button>"
data = data + "</td>"
data = data + "</tr>"
})
$('tbody').html(data);
}
})
}
// --------------------------------------------- fin de llamar datos de la DB ----------------------------------------------------------
allData();
// --------------------------------------------- Limpiar los campos despues del submit -------------------------------------------------
function clearData(){
$('#siniestro').val('');
$('#fechaip').val('');
$('#inspector').val('');
$('#nameError').text('');
$('#titleError').text('');
$('#instituteError').text('');
}
// --------------------------------------------- fin de limpiar los campos despues del submit -------------------------------------------------
// --------------------------------------------- Agregar registros a la table de BD -------------------------------------------------
function addData(){
var siniestro = $('#siniestro').val();
var fechaip = $('#fechaip').val();
var inspector = $('#inspector').val();
$.ajax({
type: "POST",
dataType: "Json",
data: {siniestro:siniestro, fechaip:fechaip, inspector:inspector},
url:"/teacher/store/",
success: function(data){
allData();
clearData();
console.log('datos agregados con éxito');
},
error: function(error){
$('#nameError').text(error.responseJSON.errors.name);
$('#titleError').text(error.responseJSON.errors.title);
$('#instituteError').text(error.responseJSON.errors.institute);
}
})
}
// --------------------------------------------- fin de agregar registros a la table de BD -------------------------------------------------
// --------------------------------------------- Editar registros a la table de BD ---------------------------------------------------------
function editData(id){
$.ajax({
type:"get",
dataType:"json",
url:"/teacher/edit/"+id,
success: function(data){
$('#addT').hide();
$('#addButton').hide();
$('#updateT').show();
$('#updateButton').show();
$('#id').val(data.id);
// $('#siniestro').val(data.siniestro);
// $('#fechaip').val(data.fechaip);
$('#inspector').val(data.inspector);
console.log(data);
}
})
}
// --------------------------------------------- Fin de editar registros a la table de BD -------------------------------------------------
// --------------------------------------------- Update de registros a la table de BD -----------------------------------------------------
function updateData(event){
event.preventDefault();
var id = $('#id').val();
// var siniestro = $('#siniestro').val();
// var fechaip = $('#fechaip').val();
var inspector = $('#inspector').val();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
type: "PUT",
dataType: "json",
data: {inspector:inspector},
url: "/teacher/update/"+id,
success: function(response){
allData();
clearData();
console.log('Siniestro asignado con éxito');
}
})
}
</script>
#endsection
Edit 3
enter image description here
See, the previous capture that showed me the attributes was only from $users, now using $data = Siniestro::orderBy('fechaip','ASC')->get();$users = User::all();$combo = ['users' => $users, 'data' => $data];dd($combo); As you can see, it shows me all the users, but I can't see their "attributes", strange, right? will the problem be there?
So when you do
$data = Siniestro::orderBy('fechaip','ASC')->get();
$users = User::all();
$combo = ['users' => $users, 'data' => $data];
return response()->json($combo);
Then you should inspect the incoming response data in your javascript. As now the data is keyed by data and users. So in your allData() function in javascript you will have to adjust as per the keys to display the data.
function allData(){
$.ajax({
type: "GET",
dataType: "json",
url: "/teacher/all",
success: function (response){
//Here console.log(response) to see the structure of incoming data
console.log(response)
// Should output something like
// {users: [... array of user records(objects)], data: [... array of siniestro records (objects)}
// So to generate the display markup you may have to do
$siniestroMarkup = "";
$.each(response.data, function(key, value){
siniestroMarkup = siniestroMarkup + "<tr>"
siniestroMarkup = siniestroMarkup + "<td>"+value.id+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"+value.siniestro+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"+value.fechaip+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"+value.modalidad+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"+value.direccion+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"+value.localidad+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"+value.inspector+"</td>"
siniestroMarkup = siniestroMarkup + "<td>"
siniestroMarkup = siniestroMarkup + "<td>"
siniestroMarkup = siniestroMarkup + "<button class='btn btn-info btn-sm' onclick='editData("+value.id+")'>Asignar IP</button>"
siniestroMarkup = siniestroMarkup + "</td>"
siniestroMarkup = siniestroMarkup + "</tr>"
})
$('tbody').html(siniestroMarkup);
});
// Similarly you can access the user records
$.each(response.users, function(key, value) {
//Here value will represent each user record
});
}
And you may also have to adjust the DataTable ajax response if you are using it probably like below (check exact response data structure for and how to access it for DataTable)
$(document).ready(function() {
$('.tablita').DataTable({
"serverSide": true,
"ajax": "/teacher/all",
"columns": [
// {data: 'id'},
{data: 'data.siniestro'},
{data: 'data.fechaip'},
{data: 'data.modalidad'},
{data: 'data.direccion'},
{data: 'data.localidad'},
{data: 'data.inspector'},
{data: 'data.action', name: 'action', orderable: true, searchable: true},
],
});
})
Check the above and see if that's how you want the data.
json as a rule will always post an array, you can not post individual objects that way. you need to convert the objects into an array and post it.
$response_array['message'] = $data;
$response_array['data'] = $users;
return response()->json($response_array);
or
$data = ['users' => $users, 'content' => $contents];
return response()->json($data);
You can receive those data using :
success: function(response) {
console.log(response.content);
}
Related
I want to pass the data from the Laravel controller to the JS file then show it in the Laravel Blade view as it appears in the code
in this var dtUserTable = $('.user-list-table'),
user-list-table is a class that is called on the blade.php page. As it appears this is the call of it, how can I return the data from or pass the data from the Laravel controller to the JS file then show it in the blade.php file?
app-user-list.js
$(function () {
'use strict';
var dtUserTable = $('.user-list-table'),
newUserSidebar = $('.new-user-modal'),
newUserForm = $('.add-new-user'),
statusObj = {
1: { title: 'Pending', class: 'badge-light-warning' },
2: { title: 'Active', class: 'badge-light-success' },
3: { title: 'Inactive', class: 'badge-light-secondary' }
};
var assetPath = '../../../app-assets/',
userView = 'app-user-view.html',
userEdit = 'app-user-edit.html';
if ($('body').attr('data-framework') === 'laravel') {
assetPath = $('body').attr('data-asset-path');
userView = assetPath + 'app/user/view';
userEdit = assetPath + 'app/user/edit';
}
// Users List datatable
if (dtUserTable.length) {
dtUserTable.DataTable({
ajax: assetPath + 'data/user-list.json', // JSON file to add data
columns: [
// columns according to JSON
{ data: 'responsive_id' },
{ data: 'full_name' },
{ data: 'email' },
{ data: 'role' },
{ data: 'current_plan' },
{ data: 'status' },
{ data: '' }
],
columnDefs: [
{
// For Responsive
className: 'control',
orderable: false,
responsivePriority: 2,
targets: 0
},
{
// User full name and username
targets: 1,
responsivePriority: 4,
render: function (data, type, full, meta) {
var $name = full['full_name'],
$uname = full['username'],
$image = full['avatar'];
if ($image) {
// For Avatar image
var $output =
'<img src="' + assetPath + 'images/avatars/' + $image + '" alt="Avatar" height="32" width="32">';
} else {
// For Avatar badge
var stateNum = Math.floor(Math.random() * 6) + 1;
var states = ['success', 'danger', 'warning', 'info', 'dark', 'primary', 'secondary'];
var $state = states[stateNum],
$name = full['full_name'],
$initials = $name.match(/\b\w/g) || [];
$initials = (($initials.shift() || '') + ($initials.pop() || '')).toUpperCase();
$output = '<span class="avatar-content">' + $initials + '</span>';
}
var colorClass = $image === '' ? ' bg-light-' + $state + ' ' : '';
// Creates full output for row
var $row_output =
'<div class="d-flex justify-content-left align-items-center">' +
'<div class="avatar-wrapper">' +
'<div class="avatar ' +
colorClass +
' mr-1">' +
$output +
'</div>' +
'</div>' +
'<div class="d-flex flex-column">' +
'<a href="' +
userView +
'" class="user_name text-truncate"><span class="font-weight-bold">' +
$name +
'</span></a>' +
'<small class="emp_post text-muted">#' +
$uname +
'</small>' +
'</div>' +
'</div>';
return $row_output;
}
},
{
// User Role
targets: 3,
render: function (data, type, full, meta) {
var $role = full['role'];
var roleBadgeObj = {
Subscriber: feather.icons['user'].toSvg({ class: 'font-medium-3 text-primary mr-50' }),
Author: feather.icons['settings'].toSvg({ class: 'font-medium-3 text-warning mr-50' }),
Maintainer: feather.icons['database'].toSvg({ class: 'font-medium-3 text-success mr-50' }),
Editor: feather.icons['edit-2'].toSvg({ class: 'font-medium-3 text-info mr-50' }),
Admin: feather.icons['slack'].toSvg({ class: 'font-medium-3 text-danger mr-50' })
};
return "<span class='text-truncate align-middle'>" + roleBadgeObj[$role] + $role + '</span>';
}
},
{
// User Status
targets: 5,
render: function (data, type, full, meta) {
var $status = full['status'];
return (
'<span class="badge badge-pill ' +
statusObj[$status].class +
'" text-capitalized>' +
statusObj[$status].title +
'</span>'
);
}
},
{
// Actions
targets: -1,
title: 'Actions',
orderable: false,
render: function (data, type, full, meta) {
return (
'<div class="btn-group">' +
'<a class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown">' +
feather.icons['more-vertical'].toSvg({ class: 'font-small-4' }) +
'</a>' +
'<div class="dropdown-menu dropdown-menu-right">' +
'<a href="' +
userView +
'" class="dropdown-item">' +
feather.icons['file-text'].toSvg({ class: 'font-small-4 mr-50' }) +
'Details</a>' +
'<a href="' +
userEdit +
'" class="dropdown-item">' +
feather.icons['archive'].toSvg({ class: 'font-small-4 mr-50' }) +
'Edit</a>' +
'<a href="javascript:;" class="dropdown-item delete-record">' +
feather.icons['trash-2'].toSvg({ class: 'font-small-4 mr-50' }) +
'Delete</a></div>' +
'</div>' +
'</div>'
);
}
}
],
order: [[2, 'desc']],
dom:
'<"d-flex justify-content-between align-items-center header-actions mx-1 row mt-75"' +
'<"col-lg-12 col-xl-6" l>' +
'<"col-lg-12 col-xl-6 pl-xl-75 pl-0"<"dt-action-buttons text-xl-right text-lg-left text-md-right text-left d-flex align-items-center justify-content-lg-end align-items-center flex-sm-nowrap flex-wrap mr-1"<"mr-1"f>B>>' +
'>t' +
'<"d-flex justify-content-between mx-2 row mb-1"' +
'<"col-sm-12 col-md-6"i>' +
'<"col-sm-12 col-md-6"p>' +
'>',
language: {
sLengthMenu: 'Show _MENU_',
search: 'Search',
searchPlaceholder: 'Search..'
},
// Buttons with Dropdown
buttons: [
{
text: 'Add New User',
className: 'add-new btn btn-primary mt-50',
attr: {
'data-toggle': 'modal',
'data-target': '#modals-slide-in'
},
init: function (api, node, config) {
$(node).removeClass('btn-secondary');
}
}
],
// For responsive popup
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
return 'Details of ' + data['full_name'];
}
}),
type: 'column',
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table',
columnDefs: [
{
targets: 2,
visible: false
},
{
targets: 3,
visible: false
}
]
})
}
},
language: {
paginate: {
// remove previous & next text from pagination
previous: ' ',
next: ' '
}
},
initComplete: function () {
// Adding role filter once table initialized
this.api()
.columns(3)
.every(function () {
var column = this;
var select = $(
'<select id="UserRole" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Role </option></select>'
)
.appendTo('.user_role')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding plan filter once table initialized
this.api()
.columns(4)
.every(function () {
var column = this;
var select = $(
'<select id="UserPlan" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Plan </option></select>'
)
.appendTo('.user_plan')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding status filter once table initialized
this.api()
.columns(5)
.every(function () {
var column = this;
var select = $(
'<select id="FilterTransaction" class="form-control text-capitalize mb-md-0 mb-2xx"><option value=""> Select Status </option></select>'
)
.appendTo('.user_status')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append(
'<option value="' +
statusObj[d].title +
'" class="text-capitalize">' +
statusObj[d].title +
'</option>'
);
});
});
}
});
}
// Check Validity
function checkValidity(el) {
if (el.validate().checkForm()) {
submitBtn.attr('disabled', false);
} else {
submitBtn.attr('disabled', true);
}
}
// Form Validation
if (newUserForm.length) {
newUserForm.validate({
errorClass: 'error',
rules: {
'user-fullname': {
required: true
},
'user-name': {
required: true
},
'user-email': {
required: true
}
}
});
newUserForm.on('submit', function (e) {
var isValid = newUserForm.valid();
e.preventDefault();
if (isValid) {
newUserSidebar.modal('hide');
}
});
}
// To initialize tooltip with body container
$('body').tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body'
});
});
Blade/View
#extends('panel.index')
#section('css-con')
<!-- BEGIN: Vendor CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/dataTables.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/responsive.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/buttons.bootstrap4.min.css')}}">
<!-- END: Vendor CSS-->
<!-- BEGIN: Page CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/plugins/forms/form-validation.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/pages/app-user.css')}}">
<!-- END: Page CSS-->
#endsection
#section('content')
<!-- users list start -->
<section class="app-user-list">
<!-- users filter start -->
<div class="card">
<h5 class="card-header">Search Filter</h5>
<div class="d-flex justify-content-between align-items-center mx-50 row pt-0 pb-2">
<div class="col-md-4 user_role"></div>
<div class="col-md-4 user_plan"></div>
<div class="col-md-4 user_status"></div>
</div>
</div>
<!-- users filter end -->
<!-- list section start -->
<div class="card">
<div class="card-datatable table-responsive pt-0">
<table class="user-list-table table">
<thead class="thead-light">
<tr>
<th></th>
<th>User</th>
<th>Email</th>
<th>Role</th>
<th>Plan</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
</div>
<!-- Modal to add new user starts-->
<div class="modal modal-slide-in new-user-modal fade" id="modals-slide-in">
<div class="modal-dialog">
<form class="add-new-user modal-content pt-0">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
<div class="modal-header mb-1">
<h5 class="modal-title" id="exampleModalLabel">New User</h5>
</div>
<div class="modal-body flex-grow-1">
<div class="form-group">
<label class="form-label" for="basic-icon-default-fullname">Full Name</label>
<input type="text" class="form-control dt-full-name" id="basic-icon-default-fullname" placeholder="John Doe" name="user-fullname" aria-label="John Doe" aria-describedby="basic-icon-default-fullname2" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-uname">Username</label>
<input type="text" id="basic-icon-default-uname" class="form-control dt-uname" placeholder="Web Developer" aria-label="jdoe1" aria-describedby="basic-icon-default-uname2" name="user-name" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-email">Email</label>
<input type="text" id="basic-icon-default-email" class="form-control dt-email" placeholder="john.doe#example.com" aria-label="john.doe#example.com" aria-describedby="basic-icon-default-email2" name="user-email" />
<small class="form-text text-muted"> You can use letters, numbers & periods </small>
</div>
<div class="form-group">
<label class="form-label" for="user-role">User Role</label>
<select id="user-role" class="form-control">
<option value="subscriber">Subscriber</option>
<option value="editor">Editor</option>
<option value="maintainer">Maintainer</option>
<option value="author">Author</option>
<option value="admin">Admin</option>
</select>
</div>
<button type="submit" class="btn btn-primary mr-1 data-submit">Submit</button>
<button type="reset" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Modal to add new user Ends-->
</div>
<!-- list section end -->
</section>
<!-- users list ends -->
#endsection
#section('jc-con')
<!-- BEGIN: Page Vendor JS-->
<script src="{{asset('app-assets/vendors/js/tables/datatable/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/dataTables.responsive.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/responsive.bootstrap4.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.buttons.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/buttons.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/forms/validation/jquery.validate.min.js')}}"></script>
<!-- END: Page Vendor JS-->
<!-- BEGIN: Page JS-->
<script src="{{asset('app-assets/js/scripts/pages/app-user-list.js')}}"></script>
<!-- END: Page JS-->
#endsection
Below is the function that I call when I want to get the data in the Laravel controller.
public function list()
{
$data = DB::table('users')->get();
return view('content.apps.user.user-list',compact('data'));
}
blade
#push('scripts')
<script>
//line chart
var line = new Morris.Line({
element: 'line-chart',
resize: true,
data: [
#foreach ($data as $value)
{
ym: "{{ $value->year }}-{{ $value->month }}", sum: "{{ $value->sum }}"
},
#endforeach
],
xkey: 'ym',
ykeys: ['sum'],
labels: ['#lang('site.total')'],
lineWidth: 2,
gridTextFamily: 'Open Sans',
gridTextSize: 10
});
</script>
#endpush
So I want to upload a picture but it only store its description correctly. The file is stored as "noimage.jpg" which means the filename isn't read. I'm using modal btw. My database is named galleries and the migration contains these:
$table->id();
$table->timestamps();
$table->string('upload');
$table->longtext('description')->nullable();
CONTROLLER:
public function store(Request $request)
{
$galleries=new Gallery;
// Handle File Upload
if($request->hasFile('upload')){
// Get filename with the extension
$filenameWithExt = $request->file('upload')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('upload')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.$extension;
// Upload Image
$path = $request->upload('upload')->storeAs('public/upload', $fileNameToStore);
// make thumbnails
$thumbStore = 'thumb.'.$filename.'_'.time().'.'.$extension;
$thumb = Image::make($request->file('upload')->getRealPath());
$thumb->save('storage/upload/'.$thumbStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$galleries->description = $request->input('description');
$galleries->upload = $fileNameToStore;
$galleries->save();
}
FORM:
<form id="uploadForm">
<div class="modal-body">
<input type="hidden" name="id" id="id">
<!-- Upload image input-->
<div class="input-group mb-3 px-2 py-2 rounded-pill bg-secondary shadow-sm">
<input type="file" name="upload" id="upload" onchange="readURL(this);" class="form-control border-0">
<label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
</div>
</div>
<!-- Uploaded image area-->
<p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
<div class="image-area mt-4 bg-white"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
<label>Caption</label>
<input type="textarea" class="form-control text-white" name="description" id="description">
</div>
</form>
AJAX
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//ADD PICTURE
$('#btnUpload').click(function(){
$('#uploadModal').modal('show');
});
$('#btnSave').click(function(){
$.ajax({
data: $('#uploadForm').serialize(),
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
});
//Image reader to show pic when selected
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function () {
$('#upload').on('change', function () {
readURL(input);
});
});
var input = document.getElementById( 'upload' );
var infoArea = document.getElementById( 'upload-label' );
input.addEventListener( 'change', showFileName );
function showFileName( event ) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
});
</script>
Assuming you're using ajax to upload the file, you'll need to use a FormData object instead of .serialize()
$.ajax({
data: new FormData($('#uploadForm').get(0)), // use formdata object
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
contentType: false, // required for
processData: false, // jquery ajax file upload
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
You don't add "enctype" in form tag.
Change your code:
<form id="uploadForm">
with:
<form id="uploadForm" enctype='multipart/form-data'>
If this above not working then:
1.install this package by following command:
composer require "laravelcollective/html":"^5.2.0"
2.In config/app add this line:
'providers' => [
// ...
**Collective\Html\HtmlServiceProvider::class,**
// ...
],
and
'aliases' => [
// ...
**'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,**
// ...
],
3.Change Form:
{!! Form::open([ 'action'=> 'NameofController#store', 'method' => 'POST','enctype' => 'multipart/form-data' ]) !!}
<div class="form-group">
{{Form::text('name','' , ['class' =>'form-control'])}}
</div>
<div class="form-group">
{{Form::text('phone','' , ['class' =>'form-control', 'placeholder' => 'phone' ])}}
</div>
<div class="form-group">
{{Form::file('image_name')}}
</div>
{{Form::submit('Submit' , ['class' =>'btn btn-primary' ])}}
{!! Form::close() !!}
you can this way to store your file with custom name:
$path = $request->file('upload')->store('public/upload/' .$fileNameToStore);
I am working on a survey application with Asp.Net MVC. I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submt button Submit form event (save or update) is fired. But ajax sends twice request. One of these requests send empty object, the other sends full object. Where am I making a mistake?
According to my research, what causes this problem is that the unobtrusive validator is placed on 2 different pages. But this is not the case for me.
When I debug with chrome in f12, the initiator of one of the 2 requests 'jquery' the initiator of the other 'other' The type of one of these 2 post requests appears as 'XHR' and the type of the other is 'document'.
Index.cshtml
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru Oluştur</a><table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link
href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
debugger;
if (form.checkValidity() === false) {
debugger;
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
AddOrEdit.cshtml
#using MerinosSurvey.Models
#model Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation",
novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id =
"questionForm" }))
{
<div class="form-group row">
#Html.Label("QuestionId", "Soru No", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.QuestionId, new { #readonly = "readonly", #class = "form-control" })
</div>
</div>
<div class="form-group row">
#Html.Label("QuestionName", "Soru Adı", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { #class = "form-control", required = "true" } })
<div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
<div class="invalid-feedback "><i class="fa fa-times"></i></div>
</div>
</div>
#*<div class="form-group row">
#Html.LabelFor(model => model.CreatedDate, new { #class = "form-control-label col-md-3"})
<div class="col-md-9">
#Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { #class = "form-control", type = "date", #readonly = "readonly",required="false" } })
</div>
</div>*#
<div class="table-wrapper form-group table-responsive-md">
<div class="table-title">
<div class="form-group row">
<div class="col-md-9">Seçenekler</div>
<div class="col-md-3">
<a class="btn btn-success add-new" style="margin-bottom: 10px"><i class="fa fa-plus"></i>Seçenek Ekle</a>
</div>
</div>
</div>
<table class="table optionTable">
<thead>
<tr>
<th scope="col">Seçenek Id</th>
<th scope="col">Seçenek Adı</th>
<th scope="col">Güncelle/Sil</th>
</tr>
</thead>
<tbody>
#*#foreach (Options options in Model.Options)
{
<tr>
<td>#options.OptionId</td>
<td>#options.OptionName</td>
<td>
<a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip">
<i class="fa fa-check">Onayla</i></a>
<a class="edit btn btn-secondary btn-sm" title="Edit" data-toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>
<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>
</td>
</tr>
}*#
</tbody>
</table>
</div>
<div class="form-group row">
<input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
//var actions = $("table.optionTable td:last-child").html();
var actions =' <a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip"><i
class="fa fa-check">Onayla</i></a>' + '<a class="edit btn btn-secondary btn-sm" title="Edit" data toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>' +'<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>';
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
var index = $("table.optionTable tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="text" class="form-control" name="optionId" id="optionId"></td>' +
'<td><input type="text" class="form-control" name="optionId" id="optionName"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table.optionTable").append(row);
$("table.optionTable tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("td:not(:last-child)").each(function () {
$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
debugger;
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
event.preventDefault(); move this line and place it immediately after function SubmitForm (form){
Like below:
function SubmitForm(form) {
debugger;
event.preventDefault();
if (form.checkValidity() === false) {
debugger;
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405
I want to integrate Ajax in my Symfony project (Symfony 2.5 and jQuery 3). I want to update an attribute of an Entity when I select a radio button. For now, I can get the id of the row that I select. I have searched how to implement this, but I have not succeeded.
JS code:
$(document).ready(function(){
$("input:radio[name=locacion_destacada]").click(function () {
var id = $(this).parent().parent().attr('dataId');
alert(id);
$.ajax({
url: "/update-destacado",
type: "POST",
data: { id : id },
success: function (response) {
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
}
});
});
});
Any help is greatly appreciated.
You can do that in the controller by calling it in the url of ajax :
url : {{ path('your_route', {'id': id})}};
and in the controller function you can update your entity as you like
You need a controller action, which is called by your "update-destacado" route. Then read the ID from the request and update your entity.
I could resolve it. I followed the idea of this page (answer n°8), also keep in mind your answers. Thanks for your help.
Controller code:
public function DestacadoAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
//Encontrar la locacion que ya estaba como destacada y dejarla como destacado=false
$locacionDestacadaAntigua = $em
->getRepository('FilmsBundle:Locaciones')
->findOneBy(
array(
'destacado' => true
));
$locacionDestacadaAntigua->setDestacado(false);
$em->persist($locacionDestacadaAntigua);
$em->flush();
$em = $this->getDoctrine()->getManager();
//Dejar como destacada la nueva locacion
$locacionDestacadaNueva = $this->getDoctrine()
->getRepository('FilmsBundle:Locaciones')
->findOneBy(
array(
'idLocacion' => $id
));
$locacionDestacadaNueva->setDestacado(true);
$em->persist($locacionDestacadaNueva);
$em->flush();
return new Response("Ha seleccionado la locación \"" . $locacionDestacadaNueva->getNombreLocacion() . "\" como destacada.");
}
JS Code:
$(document).ready(function(){
$(".button").on("click", function (e) {
$.post(this.href).done(function (response) {
alert(response);
location.reload();
});
});
});
Twig code:
{% if locacion.destacado == true %}
<td align="center">
<a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
<button class="btn btn-default">
<i class="glyphicon glyphicon-ok"></i>
</button>
</a>
</td>
{% else %}
<td align="center">
<a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
<button class="btn btn-sm">
<i class="glyphicon glyphicon-remove"></i>
</button>
</a>
</td>
{% endif %}