Output data and messages directly in the view - javascript

I am currently working on ajax, jquery and javascript. I have slight problems with it.
I can use this code to send the data and they are stored in the database.
But the data will not be displayed directly after sending in the view, until I have reloaded the page.
How can I output the data directly in the view without reloading the page?
How can I output errors and success messages as flashmessage (toastr) message?
how can I rewrite this code that works? I get the error message that it is a duplicate of the selectors.
$('#todolist-create-modal').modal('hide');
$('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
Code
<script type="application/javascript">
$(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();
var listid = $("select[name='privcy']").val();
$.ajax({
url:'{{ route('todolists.store') }}',
type: 'POST',
data: {_token:_token, title:title, description:description, privacy:privacy},
success: function (data) {
console.log(data);
if (privacy = 0) {
//go to the left side
} else {
//go to the right side
}
},
error: function(data){
console.log(data);
}
});
$('#todolist-create-modal').modal('hide');
$('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
});
});
</script>
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>Öffentliche 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>Private 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>
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::id();
$todolists->title = $request->title;
$todolists->description = $request->description;
$todolists->privacy = $request->privacy;
$todolists->save();
return response()->json(['Your enquiry has been successfully submitted!']);
}
}
EDIT
I have revised and adapted the code. Currently I have two more problems:
The flashmessage is only output as 'empty'. Without text content. Where is the problem?
The div is also reloaded. But after it was loaded I can not send the same request again. Do I have to reset something or what is the error?
When I issue the errors in the console with console.log(data); I get the following error messages:
{error: Array(2)}
error
:
(2) ["The Title ist erforderlich.", "The Description ist erforderlich."]
<script type="application/javascript">
$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#add-todo-list').click(function(e) {
e.preventDefault();
$('.todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
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 (response) {
if (response.error) {
_toastr((response),"top-full-width","error",false);
}
else{
$('.todolist-create-modal').modal('hide');
$("#content").load(location.href+" #content>*","");
_toastr((response),"top-full-width","success",false);
}
}
});
});
});
</script>

Q: How can I output the data directly in the view without reloading the page?
One way with jQuery was loading partial content, this will request again the page, get the contents of #content div and replace the HTML, fast and without reload the page:
$("#content").load("/url-of-page > #content > *");
Q: How can I output errors and success messages as flashmessage (toastr) message?
Just write the message on a HTML element:
success: function(data){
$(".alert-danger").addClass("hidden");
$(".alert-success").html(data.msg).removeClass("hidden");
},
error: function(data){
$(".alert-success").addClass("hidden");
$(".alert-danger").html(data.error).removeClass("hidden");
}

Related

favorite and unfavorite button problem laravel

I'm working on a Laravel project where user can favorite and unfavorite books, in the two cases the DB changes successfully without page reloading as i used ajax , but i have two problems:
-first problem : if there is no favorite books, favorite button disappears and i need to edit database to add some book to favorites table and show the button again.
- second problem is that when more than one book is favorited when i refresh the page, the favorite button is duplicated .
here is the code in my controller:
class FavoriteController extends Controller
{
public function bookFavBook(Request $request){
$book_id = $request['bookid'];
$fav = DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->first();
check if books fav or unfav
if(!$fav){
$newfav = new Favorite;
$newfav->book_id =$book_id;
$newfav->user_id = Auth::user()->id;
$newfav->fav = 1;
$newfav->save();
to use in ajax
$is_fav = 1;
}
elseif ($fav->fav == 1){
DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->delete();
$is_fav = 0;
}
elseif ($fav->fav == 0){
DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->update(['fav'=> 1] );
$is_fav = 1;
}
$response = array(
'is_fav'=>$is_fav,
);
return response()->json($response, 200);
}
and the code in my view :
first loop
#foreach( $books as $book)
<div class="container-fluid column">
<div class="row flex-row flex-nowrap">
<div class="col-md-4">
<div class="card card-block">
<div>
<img
class="card-img-top"
src="/images/{{ $book-> book_img}}"
alt="Card image cap"
/>
</div>
<h5 class="card-title"> {{ $book ->title}} </h5>
<p class="card-text">
{{ $book-> description}}
</p>
<div class="card">
<div class="mb-3">
<span class="badge badge-pill badge-primary p-2 mr-4">
<span class="count_of_book">{{ $book-> amount }}</span>
copies available
</span>
query books from favorites table
#php
$getbook = DB::table('books')
->join('favorites','favorites.book_id','=', 'books.id' )
->where('favorites.user_id','=',Auth::id())
->get();
#endphp
socond loop
#foreach($getbook as $fbook)
**#if($fbook->book_id == $book->id )
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-danger"></i>
#else
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-dark"></i>
#endif**
end second loop
#endforeach
</div>
</div>
end first loop
#endforeach
</div>
{{ $books->links() }}
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var token = '{{ Session::token()}}';
var urlFav = '{{ route('favor') }}';
</script>
and the ajax code in js file:
$(".fa-heart").on("click", function (event){
bookid = $(this).data("bookid");
$.ajax({
method: 'POST',
url: urlFav,
data: {bookid: bookid , _token:token},
success: function(data){
if(data.is_fav == 1){
$(event.target).removeClass("text-dark").addClass("text-danger");
}
if(data.is_fav == 0){
$(event.target).removeClass("text-danger").addClass("text-dark");
}
}
});[show duplication of the buuton][1]
[1]: https://i.stack.imgur.com/551I4.png
Don't perform a join query, instead fetch books first then inside your for loop check whether the books are present in the favorite table . If they are present and are favorite than show that they are favorite else show that they are not favorite.
#php
$getbook = DB::table('books')->get();
#endphp
#foreach($getbook as $fbook)
#php
$fav = DB::table('favorites')->where(['book_id' => $fbook->id])->get();
#endphp
#if($fav != null && $fav->is_fav == 1)
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-danger"></i>
#else
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-dark"></i>
#endif
#endforeach

Using background-image with ngStyle returns undefined

I try to add images (using API to load items) as background-image of element. But it keeps Cannot read property 'url' of undefined error. Though it actually renders url.
Here is the template side:
<div class="col s12 m4" *ngFor="let partner of partners">
<div class="card" *ngIf='partner'>
<div class="card-image " [ngStyle]="{'background-image': 'url(' + partner?.photo['url'] + ')'}">
<a class=" btn-floating halfway-fab waves-effect waves-light blue left ">
<i class="material-icons ">shopping_cart</i>
</a>
<a class="btn-floating halfway-fab red " [routerLink]='"/dashboard/partners/edit/"+partner["id"]'>
<i class="large material-icons ">mode_edit</i>
</a>
</div>
<div class="card-content ">
<h5 class="center font-weight-400 ">{{partner.name}}</h5>
<p class="center ">{{partner.category.name}}</p>
</div>
</div>
</div>
and controller:
export class PartnersListComponent implements OnInit {
partners: {}[] = [];
constructor(private _partnersService: PartnersService) {}
ngOnInit() {
this._partnersService.getPartners().subscribe(data => {
if (data.status == "200") {
this.partners = data.data;
}
});
}
}
Example data:
category:'',
created_at:"2017-12-27 12:57:50",
deleted_at:null,
first_entry:1,
id:1,
name:"Zara",
photo:{id: 5, url: "example.jpeg"},
updated_at:"2017-12-27 12:57:50",
username:"zara-001"
According to the error message, the photo field is not defined for at least one partner. You can protect against that situation with the elvis operator:
[ngStyle]="{'background-image': `url(${partner?.photo?.url})`}"
or
[style.background-image]="`url(${partner?.photo?.url})`"

How to get product name and image dynamically using jQuery?

Actually I am doing add to cart functionality using jQuery. On click of add to cart button product name and image should come. Statically I can do but how to get the product name and image dynamically for all divs is what I want. Please somebody help with this.
This is my HTML markup:
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/barcunda-black.jpg" class="lazy-loaded"/>
<h4>Barcunda Black</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/bruno-white.jpg" class="lazy-loaded"/>
<h4>Bruno White</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/fantasy-brown.jpg" class="lazy-loaded"/>
<h4>Fantasy Brown</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/iceberg.jpg" class="lazy-loaded"/>
<h4>Iceberg</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/mercury-white.jpg" class="lazy-loaded"/>
<h4>Mercury White</h4>
</div>
</div>
And here my jQuery code:
$(document).ready(function(){
//alert("coming");
var cart = [];
$(function () {
if (localStorage.cart) {
cart = JSON.parse(localStorage.cart);
// console.log(cart);
showCart();
}
});
});
function addToCart() {
how to get product name and image here for all divs?
// alert(price);alert(name);alert(qty);return false;
// update qty if product is already present
for (var i in cart) {
if(cart[i].Product == name) {
cart[i].Qty = qty;
showCart();
saveCart();
return;
}
}
// create JavaScript Object
var item = { Product: name, Price: price, Qty: qty };
//console.log(item);return false;
// alert(item);return false;
cart.push(item);
console.log(cart);return false;
saveCart();
showCart();
}
function deleteItem(index){
//alert(index);return false;
cart.splice(index,1); // delete item at index
showCart();
saveCart();
}
function saveCart() {
if ( window.localStorage) {
localStorage.cart = JSON.stringify(cart);
}
}
Add this to your addToCart() function on the first line:
var $parent = $(this).parents('.prdtitem');
var productName = $parent.find('h4').text();
var productImage = $parent.find('img').attr('src');
UPDATE
function addToCart(elem){
var $parent = $(elem).parents('.prdtitem');
var productName = $parent.find('h4').text();
var productImage = $parent.find('img').attr('src');
// then the rest of your existing code
}
I see a very little jQuery involved in your addToCart function. You could simply refer it's parent container to get the source attribute of the image and the product title text:
First of all, change the way button is clicked, instead of using inline function, you could add a class reference on it, and fire the addToCart button as callback:
...
$('.btn-add').on('click', addToCart);
function addToCart() {
var container = $(this).parents('.prdtitem');
var thumbnailImage = container.find('img.lazy-loaded').attr('src');
var productTitle = container.find('h4').text();
// ... rest of your code
}
Now you got the image source within the thumbnailImage variable and the title in the productTitle.
Create a click event:
$('.cartBg a').click(function(){
var img = $(this).closet('.cartBg').find('img').attr('src');
var title = $(this).closet('.cartBg').find('h4').text();
addToCart();
alert(title);
});
You can use your function like this -
JAVASCRIPT
function addToCart(obj){
var product_name = $(obj).closest('.prdtitem').find('h4').text();
var image_src = $(obj).closest('.prdtitem').find('img.lazy-loaded').attr('src');
alert(product_name,image_src);
}
In element you use this function call like this onclick=addToCart(this).

MVC javascript display selected data

First of all, I list the e-mail from coming ActionResult in the first cycle.
I want to see the details by clicking on the listed data. I open with the help of jQuery details. The problem arises in this section. in this case ,the opening of the details of the first mail in the detail of each row.
There are details of the message in the second loop.To connect to the two loops in a guid font was coming. (MessageId).
id=messageId (guid type)
mailing list
<div class="message-list-container">
<div class="message-list" id="message-list">
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
<span class="sender" title="#item.From">
#item.From
</span>
<span class="time">#mvcHelper.saatAyarla(item.Date)</span>
#if(item.Attachments.Any())
{
<span class="attachment">
<i class="ace-icon fa fa-paperclip"></i>
</span>
}
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
</div>
}
</div>
</div>
mailing details
<!--Messsage details-->
#foreach (var item in Model)
{
<!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
<div class="message-header clearfix">
<div class="pull-left">
<span class="blue bigger-125"> #item.Subject </span>
<div class="space-4"></div>
<i class="ace-icon fa fa-star orange2"></i>
<img class="middle" alt="John's Avatar" src="/Areas/admin/Content/images/avatars/avatar.png" width="32" />
#item.From
<i class="ace-icon fa fa-clock-o bigger-110 orange middle"></i>
<span class="time grey">#mvcHelper.saatGoster(item.Date)</span>
</div>
</div>
<div class="hr hr-double"></div>
<div class="message-body">
<p>
#item.TextBody
</p>
</div>
<div class="hr hr-double"></div>
<!--Eklenti paneli-->
<div class="message-attachment clearfix">
#if (item.Attachments.Any())
{
<div class="attachment-title">
<span class="blue bolder bigger-110">Eklentiler</span>
<span class="grey">(#item.Attachments.Count() Dosya)</span>
</div>
<ul class="attachment-list pull-left list-unstyled">
#foreach (var attachment in item.Attachments)
{
<li>
<a href="#" class="attached-file">
<i class="ace-icon fa fa-file-o bigger-110"></i>
<span class="attached-name">#mvcHelper.getAttachmentName(attachment.ToString())</span>
</a>
<span class="action-buttons">
<a href="#">
<i class="ace-icon fa fa-download bigger-125 blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o bigger-125 red"></i>
</a>
</span>
</li>
}
</ul>
}
</div>
</div><!-- /.message-content -->
}
<!--Eklenti paneli Son-->
<!--message details end-->
loop connecting two points.
first foreach = <div id="#item.MessageId" class="message-item">
//Places where the problem is. They need to be connected.
second foreach = <!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
var content = message.find('.message-content:last').html($('#id-message-content').html());
jQuery code
$('.message-list .message-item .text').on('click', function () {
var message = $(this).closest('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').remove();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message
.addClass('message-inline-open')
.append('<div class="message-content" />');
var content = message.find('.message-content:last').html($('#id-message-content').html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});
Your first problem is that you are creating multiple elements with identical id properties. This makes your HTML invalid.
Here is the problem code:
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
...
#foreach (var item in Model)
{
<div class="hide message-content" id="#item.MessageId">
...
For each message in your model, this will create 2 <div> elements whose id has the value of the #item.MessageID variable. The second of these is and illegal element because it has the same ID as an earlier element. You will need to make these <div>s have unique IDs.
The second problem is:
When you run
var content = message.find('.message-content:last').html($('#id-message-content').html());
this part:
$('#id-message-content').html()
cannot find anything because there is no element whose id is "id-message-content". Also every time you open the message, you are appending another "message-content" div into the message-item. This is not necessary.
To fix these issues, you can change the code like this:
First loop:
#foreach (var item in Model)
{
<div data-messageid="#item.MessageId" class="message-item">
...
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
<div class="message-content" hidden></div>
...
Second loop:
#foreach (var item in Model)
{
<div class="hide message-content" id="message-content-#item.MessageId">
...
jQuery:
$('.message-list .message-item .text').on('click', function () {
var message = $(this).parents('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').hide();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message.addClass('message-inline-open');
var content = message.find(".message-content");
content.show();
content.html($('#message-content-' + message.data("messageid")).html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});
Solved
public static class mvcHelper
{
public static string variableReplace(string id)
{
string yazi = null;
if (id != null)
{
yazi = id.Replace('#', 'a').ToString();
}
else
{
yazi = id;
}
return yazi;
}
}
<div data-messageid="#mvcHelper.variableReplace(item.MessageId)" class="message-item">
<div class="hide message-content" id="message-content-#mvcHelper.variableReplace(item.MessageId)">

Laravel 4 validation in bootstrap modal

I'm a newbie to Laravel 4, and I'm trying to get a form validation in bootstrap modal.
My modal have a form with a text input and a submit button, and I want that when the validation fails, the modal show me the error.
But the modal, after the validation and the page refresh, is closed.
Here is the code from the controller and the view:
Controller code:
public function postAvatar()
{
$avatar_rules = array(
'avatar_src' => 'url',
);
$validator = Validator::make(Input::all(), $avatar_rules);
$validator->setAttributeNames(User::$names_attr);
if ($validator->passes())
{
$avatar_src = (Input::get('avatar_src'))? Input::get('avatar_src') : URL::asset('assets/images/user/default-user-avatar.png');
$user = User::find(Auth::id());
$user->avatar_src = $avatar_src;
if ($user){
return Redirect::to('dashboard')->withSuccess("Success: avatar updated.");
}
return Redirect::to('dashboard')->withError("Error: an error has occurred.");
}
return Redirect::back()->withErrors($validator);
}
View code:
<!-- Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="avatarModalLabel">Update avatar</h4>
</div>
<div class="modal-body">
<h4><span class="label label-info">Current avatar</span></h4>
<img class="img-circle img-responsive dashboard-avatar" src="{{ $user->avatar_src }}" alt="{{ $user->username }} avatar">
<div class="divider"></div>
<h4><span class="label label-info">New avatar</span></h4>
{{ Form::open(array('url' => 'dashboard/avatar', 'method'=>'post', 'role'=>'form')) }}
<ul>
#foreach($errors->all() as $error)
<div class="alert alert-danger" role="alert">{{ $error }}</div>
#endforeach
</ul>
<div class="form-group">
<label for="avatar_src" class="control-label">Link avatar</label>
<input type="text" name="avatar_src" class="form-control" id="avatar_src" placeholder="Link of avatar image url">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
How can I resolve ?
Thanks.
SOLVED:
Controller code:
public function postAvatar()
{
$avatar_rules = array(
'avatar_src' => 'url',
);
$validator = Validator::make(Input::all(), $avatar_rules);
$validator->setAttributeNames(User::$names_attr);
if ($validator->passes())
{
$avatar_src = (Input::has('avatar_src'))? Input::get('avatar_src') : URL::asset('assets/images/user/default-user-avatar.png');
$user = User::find(Auth::id());
$user->avatar_src = $avatar_src;
if ($user->save()){
if(Request::ajax()){
return Response::json(array('success' => true));
}
}
return Redirect::to('dashboard')->withError("Error: an error has occurred.");
}
return Response::json(array('errors' => $validator->errors()->toArray()));
}
View code:
<!-- Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="avatarModalLabel">Update avatar</h4>
</div>
<div class="modal-body">
<h4><span class="label label-info">Current avatar</span></h4>
<img class="img-circle img-responsive dashboard-avatar" src="{{ $user->avatar_src }}" alt="{{ $user->username }} avatar">
<div class="divider"></div>
<h4><span class="label label-info">New avatar</span></h4>
{{ Form::open(array('url' => 'dashboard/avatar', 'id'=>'avatar_form', 'method'=>'post', 'role'=>'form')) }}
<div class="alert alert-danger avatar_alert" role="alert" style="display: none">
<ul></ul>
</div>
<ul>
</ul>
<div class="form-group">
<label for="avatar_src" class="control-label">Link avatar</label>
<input type="text" name="avatar_src" class="form-control s_tooltip" id="avatar_src" placeholder="Avatar image links">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
Ajax:
<script>
$(document).on('submit', '#avatar_form', function(event){
var info = $('.avatar_alert');
event.preventDefault();
var data = { avatar_src: $("#avatar_src").val() }
$.ajax({
url: "/dashboard/avatar",
type: "POST",
data: data,
}).done(function(response) {
info.hide().find('ul').empty();
if(response.errors)
{
$.each(response.errors, function(index, error){
info.find('ul').append(error);
});
info.slideDown();
}
else if(response.success){
window.location.href = "/dashboard";
}
});
});
</script>
Your best bet would be to validate the form via AJAX to avoid the page reloading entirely. You would then check the response of your AJAX request for the presence of errors and show them inside the modal if they exist.
You could also add in client side validation to prevent the request being made until the rules are satisfied. I wouldn't recommend using this INSTEAD of server side validation but using it ASWELL as is normally quite desirable.
To accomplish this, you'd need to do something along these lines:
Javascript:
Catch submit event of your form and make an AJAX request.
$(document).on('submit', 'form', function(event){
event.preventDefault();
var data = { avatar_src: $("#avatar_src").val(); };
$.ajax({
url: "/dashboard/avatar",
data: data
type: "POST",
}).done(function(response) {
if(response.errors)
{
// Add error to Modal Body
}
else
{
// Show success message, close modal?
}
});
});
Backend:
Modify your controller method to detect if the current request is an AJAX request and if so, return the response in JSON instead of Redirecting. For example:
if(Request::ajax())
{
return Response::json(array('errors' => $validator->messages()));
}
else
{
return Redirect::back()->withErrors($validator);
}
I've not tested any of that code so might contain some typos/errors but hopefully this helps you!
I was facing same issue. After research on internet,I found that Laravel don't support withSuccess('success_msg') method.
return Redirect::to('dashboard')->withSuccess("Success: avatar updated.");
Here is complete discussion on this topic:
https://github.com/laravel/framework/issues/906.
But you can handle this issue with this approach:-
- For Error message:-
[code has to be added in controller]
return Redirect::to('view')->withErrors('your error message.');
[code has to be added in view]
#if(isset($errors) && count($errors->all())>0)
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
- for succcess message:-
[code has to be added in controller]
$success_msg='your success message.';
Session::flash('successMsg', $success_msg);
return Redirect::to('view');
[code has to be added in view]
#if (Session::has('successMsg'))
{{ Session::get('successMsg') }}
#endif
This approach is working fine for me.
For better display of your errors you can use bootstrap css.

Categories