After reload via ajax, no data - ajax

I am currently learning ajax and have some problems with it. Whenever I reload the page I get over the data attributes of the modal no more data. Do I give the data wrong to the modal? Or do I have to reload something else?
The second problem is, the data in the modal or the input fields are displayed to me, but when I pass them to the controller and save there are no data available.
View
#foreach ($todolistprivate as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden">
<i class="fa fa-plus"></i> Erstellen
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-update-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-info btn-xs white hover-hidden">
<i class="fa fa-edit"></i> Bearbeiten
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-destroy-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-danger btn-xs white hover-hidden">
<i class="fa fa-times"></i> Löschen
</a>
</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll min-height-30 max-height-100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
Modal
<div class="modal fade todolist-update-modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Bearbeite diese Liste</h4>
</div>
<div class="modal-body">
<form>
<input type="hidden" name="id" id="id" value="">
<div class="form-group">
<label for="" class="control-label">Titelname</label>
<div class="fancy-form">
<i class="fa fa-header"></i>
<input id="title" name="title" type="text" class="form-control input-lg" placeholder="Titel">
</div>
</div>
<div class="form-group">
<label for="" class="control-label">Beschreibung</label>
<div class="fancy-form">
<textarea id="description" name="description" rows="2" class="form-control" placeholder="Beschreibe deine Aufgabe"></textarea>
<i class="fa fa-comments"><!-- icon --></i>
</div>
</div>
<div class="form-group">
<label for="" class="control-label">Privatsphäre</label>
<div class="fancy-form fancy-form-select">
<select id="privacy" name="privacy" class="form-control">
<option value="0">Öffentlich</option>
<option value="1">Privat</option>
</select>
<i class="fancy-arrow"></i>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="update-todo-list">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Function:
$('.todolist-update-modal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var title = button.data('title');
var description = button.data('description');
var id = button.data('id');
var modal = $(this);
modal.find('.modal-body input').val(title);
modal.find('.modal-body textarea').val(description);
modal.find('.modal-body #id').val(id);
});
$(document).on('click','#update-todo-list', function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var title = $("input[name='title']").val();
var description = $("textarea[name='description']").val();
var privacy = $("select[name='privacy']").val();
var id = $("input[name='id']").val();
$.ajax({
url:'/admin/tasks/update/'+id,
type: 'Put',
data: {_token:_token, title:title, description:description, privacy:privacy, id:id, _method:'put'},
dataType: 'json',
success: function (data) {
if (data.error) {
_toastr((data.error),"top-full-width","error",false);
console.log(data);
}
else{
$('.todolist-update-modal').modal('hide');
$("#wrapper").load(location.href+" #wrapper>*","");
_toastr((data),"top-full-width","success",false);
console.log(data);
}
}
});
});

Related

Cannot call modal in another page

I make button on index.php file and want call modal in another page, because when modal in same file and i refresh the page modal seen temporarily.
index.php
<a href="modal.php" data-target="#cancel{{ $form->id }}" class='btn btn-danger btn-sm' data-toggle="modal">Cancel</button>
modal.php
#foreach($list_form as $form)
<div class="modal fade" id="cancel{{ $form->id }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header" style="background-color: red;">
<h3 class="modal-title h3" id="exampleModalSmLabel" style="color: white;"><b>Cancel Description</b>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><h1><b>×</b></h1></span>
</button>
</h3>
</div>
<div class="modal-body">
#if(auth()->user()->role == 'Admin')
<form action="{{ route('form001.cancel', $form->id) }}" method='post'>
#csrf
<div class="form-group">
<label for="cancel_deskripsi">Alasan Cancel</label>
<textarea class="form-control" id="cancel_deskripsi" name="cancel_deskripsi" placeholder="tuliskan alasan anda..."></textarea>
</div>
<div class="modal-footer">
<button type='submit' class='btn btn-danger btn-sm'>Submit</button>
</div>
</form>
#endif
{{ $form->cancel_deskripsi }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#endforeach
Am I doing writing anything wrong?

Problem with Passing data from Laravel controller to Boostrap Modal

Hello everyone one i have a problem . I want to pass data from my Controller to my modal . I have a list of categories i want to display it in a dropdown list i've tried using href attribute and ajax but none of these worked is there any solution ?
here is a piece of code :
List of all Categories blade.php :
#extends('layouts.Template')
#section('content')
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<center> <h2 class="page-title">Gérer les Sous Catégories</h2> </center>
<div class="panel panel-default">
<div class="panel-heading"> <strong>Liste Sous Catégories</strong></div>
<div class="panel-body">
<table id="zctb" class="table table-bordered">
<tr>
<th>Id</th>
<th>Nom</th>
<th>Nom de Catégories</th>
<th>image</th>
<th>created_at</th>
<th>updated_at</th>
<a class="fas fa-plus-circle" style="font-size:60px;color:#e2ccae;margin-left:90%;"href="{{url ('/Sous_Catégories/ajouter')}}"></a>
</tr>
#foreach($Souscategories as $Scategorie)
<tr>
<td>{{$Scategorie->id}}</td>
<td>{{$Scategorie->nom}}</td>
<td>{{$Scategorie ->nomCat}}</td>
<td>{{$Scategorie->image}}</td>
<td>{{$Scategorie -> created_at}}</td>
<td>{{$Scategorie -> updated_at}}</td>
<td ><a class="fas fa-edit" href="{{ route('Sous_Catégories.getAllCategories')}}" data-nom="{{$Scategorie->nom}}" data-nomCat="{{$Scategorie->nomCat}}" data-image="{{$Scategorie->image}}" data-cat_id1 ="{{$Scategorie->id }}" data-toggle="modal" data-target="#edit1">Edit</a></td>
<td><a class="fas fa-trash" href="{{url ('/Sous_Catégories/supp',[$Scategorie->id])}}" > </td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit1" 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"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modifier Sous Catégories</h4>
</div>
<form action="{{ route('Sous_Catégories.update','test')}}" method="POST">
{{method_field('patch')}}
{{csrf_field()}}
<div class="modal-body">
<input type="hidden" name="cat_id1" id="cat_id1" value="">
#include('formSousCat')
</div>
<div class="modal-footer">
<button id="fermer" type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button id="save" type="submit" class="btn btn-primary">Enregistrer</button>
</div>
</form>
</div>
</div>
</div>
#endsection
controller Methode :
public function getAllCategories()
{
$Cat = categories::all();
return view('formSousCat', compact('Cat'));
}
My routers :
Route::get('/Sous_Catégories', 'SousCatController#index' );
Route::post('/Sous_Catégories/ajouter', 'SousCatController#create');
Route::get('/Sous_Catégories/supp/{id}', 'SousCatController#destroy');
Route::get('/Sous_Catégories/getAllCategories', 'SousCatController#getAllCategories');
Route::resource('Sous_Catégories', 'SousCatController');
My Modal.blade
<label>Nom</label>
<input id="nom" name="nom" class="form-control"type="text"/>
</div>
<br/>
<div>
<label for="le_nom">Choix de categorie</label><br />
<label for="le_nom">Choix de categorie</label><br />
<select name="le_nom" id="le_nom" class="form-control">
#foreach($Cat as $categorie) <!-- $Cat is undefined -->
<option class="form-control">{{$categorie->nomCat}}</option>
#endforeach
</select>
<div class="input-group">
<div class="custom-file">
<div class="form-group">
<input type="file" name="image" class="form-control-file">
</div>
</div>
You can use a click event on a button tag, to opent the modal and initiate an ajax request which fetches the data from the controller and inserts into the categories.
<button id="openModal">Open Modal</button>
In your controller:
public function getAllCategories()
{
$Cat = categories::all();
return response()->json($cat);
}
In your script
let btn = document.querySelector('#openModal')
let slct = document.querySelector('#le_nom')
btn.addEventListener('click', function(){
$.ajax({
url: '{{url("/Sous_Catégories/getAllCategories")}}',
method: 'GET',
success: function(response){
response.Foreach((op) = > {
slct.innerHTML += `<option value="${op.id}">${op.nomCat}</option>`
})
}
})
})

Laravel ajax store request errormessage, data append to view

I'm new to ajax and I have two little problems.
With my code I can write the data in the database. I get no error messages and the data are not synonymous directly loaded into the view.
how can I load the data directly into the view without reload the page?
if the privacy is 1, the code should be displayed in the right column, and if the privacy is 0, the code should be displayed in the left column.
How can I output the error messages with my errormessage code?
view
<div id="content" class="dashboard padding-10">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<a data-toggle="modal" data-target=".todolist-create-modal" class="btn btn-success btn-block btn-sm margin-bottom-10">Neue Liste erstellen</a>
</div>
<div class="col-md-6">
<div id="panel-misc-portlet-l3" class="panel panel-default text-center">
<div class="panel-heading nohover">
<span class="elipsis">
<strong>Private Tasks</strong>
</span>
</div>
</div>
<div class="alert alert-danger margin-bottom-30 {{ $todolistpublic->count() ? 'hidden' : '' }}">
Es wurden keine <strong>Einträge</strong> gefunden.
</div>
#foreach ($todolistpublic as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden">
<i class="fa fa-plus"></i> Erstellen
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-info btn-xs white hover-hidden">
<i class="fa fa-edit"></i> Bearbeiten
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-delete-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-danger btn-xs white hover-hidden">
<i class="fa fa-times"></i> Löschen
</a>
</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
<div class="panel-footer mtm-10">
<span id="todo-list-counter-public">{{ $todolistpublic->count() }}</span> <span>{{ $todolistpublic->count() > 1? 'Listen' : 'Liste' }}</span>
</div>
</div>
<div class="col-md-6">
<div id="panel-misc-portlet-l3" class="panel panel-default text-center">
<div class="panel-heading nohover">
<span class="elipsis">
<strong>Öffentliche Tasks</strong>
</span>
</div>
</div>
<div class="alert alert-danger margin-bottom-30 {{ $todolistprivate->count() ? 'hidden' : '' }}">
Es wurden keine <strong>Einträge</strong> gefunden.
</div>
#foreach ($todolistprivate as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden"><i class="fa fa-plus"></i> Erstellen</a></li>
<li><a data-toggle="modal" data-target=".todolist-modal" class="btn btn-info btn-xs white hover-hidden"><i class="fa fa-edit"></i> Bearbeiten</a></li>
<li><i class="fa fa-times"></i> Löschen</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
<div class="panel-footer mtm-10">
<span id="todo-list-counter-private">{{ $todolistprivate->count() }}</span> <span>{{ $todolistprivate->count() > 1? 'Listen' : 'Liste' }}</span>
</div>
</div>
#include('elements.addTodoList')
#include('elements.createTodoList')
#include('elements.addTask')
</div>
</div>
$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#add-todo-list').click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val(); // get csrf field.
var title = $("input[name='title']").val();
var description = $("textarea[name='description']").val();
var privacy = $("select[name='privacy']").val();
$.ajax({
url:'{{ route('todolists.store') }}',
type: 'POST',
data: {_token:_token, title:title, description:description, privacy:privacy},
success: function (data) {
console.log(data);
}
});
});
});
Controller
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|min:5',
'description' => 'required|min:10',
'privacy' => 'required|integer'
]);
$attributeNames = array(
'title' => 'Title',
'description' => 'Description',
);
$validator->setAttributeNames($attributeNames);
//Redirect back if validation fails
if($validator->fails()) {
return response()->json(['error'=>$validator->errors()->all()]);
}
else{
$todolists = new Todolists;
$todolists->admin_id = auth::user();
$todolists->title = $request->title;
$todolists->description = $request->description;
$todolists->privacy = $request->privacy;
$todolists->save();
return response()->json(['success'=>'Your enquiry has been successfully submitted!']);
}
}
modal
<div class="modal fade todolist-create-modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Erstelle eine neue Liste</h4>
</div>
<div class="modal-body">
<form action="{{ route('todolists.store') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="" class="control-label">Titelname</label>
<div class="fancy-form">
<i class="fa fa-header"></i>
<input id="title" name="title" type="text" class="form-control input-lg" placeholder="Titel">
</div>
</div>
<div class="form-group">
<label for="" class="control-label">Beschreibung</label>
<div class="fancy-form">
<textarea id="description" name="description" rows="2" class="form-control" placeholder="Beschreibe deine Aufgabe"></textarea>
<i class="fa fa-comments"><!-- icon --></i>
</div>
</div>
<div class="form-group">
<label for="" class="control-label">Privatsphäre</label>
<div class="fancy-form fancy-form-select">
<select id="privacy" name="privacy" class="form-control">
<option selected value="0">Öffentlich</option>
<option value="1">Privat</option>
</select>
<i class="fancy-arrow"></i>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="add-todo-list">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
errormessages
#if (count($errors) > 0)
<div class="toastr-notify"></div>
#foreach ($errors -> all() as $e)
<script type="text/javascript">
_toastr("{{$e}}","top-right","error",false);
</script>
#endforeach
#endif
#if (session('fail'))
<div class="toastr-notify"></div>
<script type="text/javascript">
_toastr("{{ session('fail') }}","top-full-width","warning",false);
</script>
#endif
#if (session('status'))
<div class="toastr-notify"></div>
<script type="text/javascript">
_toastr("{{ session('status') }}","top-full-width","info",false);
</script>
#endif
#if (session('success'))
<div class="btn btn-info toastr-notify"></div>
<script type="text/javascript">
_toastr("{{ session('success') }}","top-full-width","success", false);
</script>
#endif
#if (session('error'))
<div class="toastr-notify"></div>
<script type="text/javascript">
_toastr("{{ session('error') }}","top-full-width","error",false);
</script>
#endif
I believe you have a typo in your ajax backend code; this line to be specific:
$todolists->admin_id = auth::user();
This should be:
$todolists->admin_id = auth()->user()->id;
The typo is generating a Throwable error, which is getting caught by the laravel exception handler and it's detecting that the code is being executed under a ajax request and hence returning a 500 internal server error.

Laravel Ajax updating variable

<div class="panel panel-primary">
<div class="panel-heading">Add user Status</div>
<form action="{{ route('post.create') }}" method="post">
<div class="panel-body">
<div class="form-group">
<textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your Post"></textarea>
</div>
</div>
<div class="panel-footer clearfix">
<button class="btn btn-info pull-right"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></i> Post</button>
</div>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
</div>
<div id="main" class="main">
<header><h3>What other people say...</h3></header>
#foreach($top_15_post as $status)
{!!
view ('layouts.app-internal.user-status-layaout',[
'status' =>$status,
'user' =>\App\User::find($status->user_id),
'comments'=>\App\Comment::where('status_id',$status->id)->get(),
'countcomment'=>\App\Comment::where('status_id',$status->id)->count(),
'countlike'=>\App\Like::where('like',1)->where('post_id',$status->id)->count() ,
'countdislike'=>\App\Like::where('like',0)->where('post_id',$status->id)->count(),
])->render()
!!}
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Right part -->
</div>
</div>
</div>
This is my home.blade.php in laravel. im simply implementing a posting text system which user can comment and like to the posts.I'm passing above variables to the user-status-layaout.blade.php, it shows the comments and likes as well as the posts.
This is my user-status-layaout.blade.php.My like and dislike functions are working properly. but i want update like count using ajax.How do i update countlike and countdislike variable instantly using ajax?
<div class="panel panel-default">
<div class="panel-heading">{{ $status->user->name }} Posted on {{ $status->created_at }}</div>
<div class="panel-body">
<div class="row">
<div class="col-md-1">
<img src="{{Auth::user()->getavatar()}}" class="img-responsive">
</div>
<div class="post" data-postid="{{ $status->id }}">
<p>{{ $status->body }}</p>
<div class="interaction">
{{ Auth::user()->likes()->where('post_id', $status->id)->first() ? Auth::user()->likes()->where('post_id', $status->id)->first()->like == 1 ? 'You like this post' : 'Like' : 'Like' }} |
{{ Auth::user()->likes()->where('post_id', $status->id)->first() ? Auth::user()->likes()->where('post_id', $status->id)->first()->like == 0 ? 'You don\'t like this post' : 'Dislike' : 'Dislike' }}
#if(Auth::user() == $status->user)
|
Edit |
<form method="get" action="{{ route('post.delete', ['post_id' => $status->id]) }}" accept-charset="UTF-8" style="display:inline">
<button class="btn btn-xs btn-danger" type="button" data-toggle="modal" data-target="#confirmDelete" data-title="Delete Post" data-message="Are you sure you want to delete this post ?">
<i class="glyphicon glyphicon-trash"></i> Delete
</button>
</form>
#endif
<ul class="list-unstyled list-inline ">
<li>
<button class="btn btn-xs btn-info" type="button" data-toggle="collapse" data-target="#view-comments-{{$status->id}}" aria-expanded="false" aria-controls="collapseExample">
<i class="fa fa-comments"></i>View & Comment </button>
</li>
<li>{{$countcomment}} comments</li>
<li >{{$countlike}} likes</li>
<li>{{$countdislike}} dislikes</li>
</ul>
</div>
</div>
</div>
</div>
<div class="panel-footer clearfix">
<div class="form-group">
<form action="{{ route('comment.create') }}" method="post">
<div class="input-group">
<input type="text" class="form-control" name="comment-text" id="comment-text" placeholder="Add Comment">
<span class="input-group-btn">
<button class="btn btn-info btn-xs" type="submit"><span class="glyphicon glyphicon-plus"></span>Add </button>
</span>
<input type="hidden" value="{{ $status->id }}" name="id" id="id">
</div><!-- /input-group -->
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
</div>
<div class="collapse" id="view-comments-{{$status->id}}">
#if($comments->first())
#foreach($comments as $comment)
<blockquote >
<div class="row" >
<div class="col-md-1" >
<img src="{{\App\User::find($comment->user_id)->getavatar()}}" class="img-responsive">
</div>
<div class="col-md-11">
<ul class=" list-inline list-unstyled ">
<li>
{{\App\User::find($comment->user_id)->name}}
</li>
</ul>
<div class="comment" data-commentid="{{ $comment->id }}">
<p> {{$comment->comment_text}}</p>
<div class="interaction1">
#if(Auth::user() == $comment->user)
Edit |
<form method="get" action="{{ route('comment.delete', ['comment_id' => $comment->id]) }}" accept-charset="UTF-8" style="display:inline">
<button class="btn btn-xs btn-danger" type="button" data-toggle="modal" data-target="#confirmDeleteComment" data-title="Delete Comment" data-message="Are you sure you want to delete this comment ?">
<i class="glyphicon glyphicon-trash"></i> Delete
</button>
</form>
#endif
</div>
</div>
</div>
</div>
<p> posted {{$comment->created_at->diffForHumans()}}</p>
</blockquote>
#endforeach
#else
<p>This status no comment</p>
#endif
</div>
</div>
You could create a timer function using WindowTimers.setTimeout()
$('some-selector').load(function(){
function likeTimer() {
setTimeout(function(){
// Some JSON request that updates the elements' values.
likeTimer();
}, 1000);
}
});
Or you could poll the server periodically with WindowTimers.setInterval()
$('some-selector').load(function(){
setInterval(function() {
// Some JSON request that updates the elements' values.
}, 1000);
});
Then just define a route in Laravel that returns JSON for the data you want to update.

Update method laravel using modal box

My update method is working unfortunately it always updates the wrong data in this case it always updates the last data in my db list. I believe this occurs because my modal box directs to $user->id which always points to the last id as I have a for loop used at the top, is there a ways I could do to point it to the selected id instead?
view.blade.php
<div class="well col-xs-9 col-sm-9 col-md-9 col-lg-9 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1">
#foreach ($users as $user)
<div class="row user-row">
<!--div class="col-xs-3 col-sm-2 col-md-1 col-lg-1">
<img class="img-circle"
src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=50"
alt="User Pic">
</div-->
<div class="col-xs-2 col-sm-3 col-md-4 col-lg-4">
<h5 style="font-weight: bold">{{ $user->name }}</h5>
</div>
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8 dropdown-user" data-for=".{{ $user->id }}">
<h5 class="glyphicon glyphicon-chevron-down text-muted pull-right"> </h5>
</div>
</div>
<div class="row user-infos {{ $user->id }}">
<div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-xs-offset-0 col-sm-offset-0 col-md-offset-1 col-lg-offset-1">
<div class="panel panel-info">
<div class="panel-heading">
<h2 class="panel-title">User Information</h2>
</div>
<div class="panel-body">
<div class="row">
<div class=" col-md-10 col-lg-10 hidden-xs hidden-sm">
<div class="col-xs-5">User level:</div><div class="col-xs-5"> {{ $user->role->role_description }}</div>
<div class="col-xs-5">Email:</div> <div class="col-xs-5"> {{ $user->email }}</div>
<div class="col-xs-5">Phone number: </div> <div class="col-xs-5"> {{ $user->mobile }} </div>
<div class="col-xs-5">Office extension: </div> <div class="col-xs-5"> [ TO IMPLEMENT ]</div>
</div>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-sm btn-warning" type="button"
data-toggle="modal" data-target="#form">Edit <i class="glyphicon glyphicon-edit"></i></button>
<span class="pull-right">
<button class="btn btn-sm btn-danger" type="button">Inactive <i class="glyphicon glyphicon-remove"></i></button>
</span>
</div>
</div>
</div>
</div>
#endforeach
</div>
#if(Session::has('flash_message'))
<div class="alert alert-success col-xs-9 col-sm-9 col-md-9 col-lg-9 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1">
{{ Session::get('flash_message') }}
</div>
#endif
<div class="col-sm-offset-1 col-sm-2">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#form">Register New User</button>
<!-- Modal -->
<div id="form" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User Information</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" action="/manage_accounts/{{ $user->id }}" novalidate>
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Username:</label>
<div class="col-sm-5 #if ($errors->has('name')) has-error #endif">
<input type="text" class="form-control" type="hidden" id="name" name="name" placeholder="Enter username">
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
</div>
</div>
...
Your modal is referencing the $user object, but it is outside of your foreach loop.
Specifically this line:
<form class="form-horizontal" role="form" action="/manage_accounts/{{ $user->id }}" novalidate>
You could register an onClick event for the modal pop-up button, that grabs a hidden input field of an user's id and dynamically updating the the action URL. Alternatively, you could just have the action URL be the same and handle the logic server side. This approach would have a hidden input field for the user ID that you would be updating, but is a lot cleaner that dealing with URL structure.
Edit:
Javascript Example:
<script type="text-javascript">
$(function() {
$('.btn--edit').on('click', function() {
var formAction = $('.form-horizontal').attr('action').replace(/(?!.*/).*, '');
var userId = $(this).closest('[name=user_id]').val();
$('.form-horizontal').attr('action', formAction + '/' + userId);
});
});
</script>
This requires you to update your modal button with a class name of .btn--edit
<button class="btn btn-sm btn-warning btn--edit" type="button" data-toggle="modal" data-target="#form">Edit <i class="glyphicon glyphicon-edit"></i></button>
This also requires you add a hidden input within the foreach somewhere. I chose after the user-infos class.
<input type="hidden" name="user_id" value="{{ $user->id }}" />
So here's how I got my update method to work.
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts/" novalidate>
<input type="hidden" name="_method" value="PUT">
Javascript:
<script type="text/javascript">
$(function() {
$('.btn--edit').on('click', function(e) {
var userId = $(this).attr('data-for');
var formAction = "/manage_accounts/" + userId;
$('.form-horizontal').attr('action', formAction);
});
</script>
The modal button with class name of .btn--edit,
<button class="btn btn-sm btn-warning btn--edit" type="button"
data-toggle="modal" data-target="#update" data-for="{{$user->id}}">Edit <i class="glyphicon glyphicon-edit"></i></button>

Resources