I'm starting with Alpine js and I use a component with plus and minus buttons to add or remove items, however this is used in a modal that when invoked brings a specific product, the problem is that when closing the modal and opening it again with another product the component values do not update, is there a way to reset to the initial state?
<div wire:model.defer='{{ $wiremodel }}'
class="input-group input-group-sm {{$size == 'l' ? 'input-group-lg': ''}} {{$size == 's' ? 'input-group-sm': ''}}"
x-data="{ count: {{ $min }}, max:{{ $max }}, min:{{ $min }}, price:{{ $price }},
increment(){
var incre;
if(this.max == 0){
incre = true;
this.count ++;
}else{
this.count == this.max ? incre = false : incre = true;
this.count == this.max ? this.count : this.count++;
}
if(incre){
var oldprice;
var newprice;
oldprice = $('#price_product_button').attr('data-price');
newprice = parseFloat(this.price) + parseFloat(oldprice);
$('#price_product_button').attr('data-price', newprice);
$('#price_product_button').html(newprice.toLocaleString('pt-BR', { style: 'currency' , currency:'BRL'}));
}
},
decrement(){
var decre;
this.count == this.min ? decre = false : decre = true;
this.count == this.min ? this.count : this.count--;
console.log(this.count);
if(decre){
var oldprice;
var newprice;
oldprice = $('#price_product_button').attr('data-price');
newprice = parseFloat(oldprice) - parseFloat(this.price) ;
$('#price_product_button').attr('data-price', newprice);
$('#price_product_button').html(newprice.toLocaleString('pt-BR', { style: 'currency' , currency:'BRL'}));
}
}
}">
<div class="input-group-prepend">
<button #click="decrement() ; $dispatch('input', count)" class="btn btn-outline-light bg-white text-danger" data-price="">
<i class="fas fa-minus"></i>
</button>
</div>
<input readonly x-model.number="count" class="form-control border-0 text-center input-btn-add-remove"
placeholder="{{ $min }}" />
<div class="input-group-append">
<button #click="increment() ; $dispatch('input', count)" class="btn btn-outline-light bg-white text-danger">
<i class="fas fa-plus"></i>
</button>
</div>
</div>```
If the x-data object of a component contains an init() method, it will be called automatically. For example:
<div x-data="{
init() {
this.count = {{ $min }};
this.max = {{ $max }};
this.min = {{ $min }};
this.price = {{ $price }};
}
}">
...
</div>
You can use that fact for your advantage and everytime the modal opens, the init method can be called to reset the values to its original state. Also it will be called automatically on the first init.
Related
whene i do the login action it return the error above where there is no user all work good
$currentTime = date("Y-m-d");
if(Auth::check()){
$user = Auth::user();
$favorie = $user->favorie;
$favprds = $favorie->produits;
}else{
$favprds = [];
}
this is my blade i believe that there is no probleme with blade
#for ( $i = 0; $i < count($favprds) ;$i++)
#if ($favprds[$i]->id == $pro->id)
<div class="tinv-wishlist-clear">
<a style="color:red;" href="{{ url('deleteFavorie/'.$pro->id) }}"><i class="fa fa-heart"></i></a>
</div>
#break
#elseif($favprds[$i]->id != $pro->id && $i == count($favprds)-1)
<div class="tinv-wishlist-clear">
<i class="klbth-icon-heart-1"></i>
</div>
#endif
#endfor
#if(count($favprds) == 0)
<div class="tinv-wishlist-clear">
<a style="color:#7f8c8d" href="{{ url('add-to-favorie/'.$pro->id) }}"><i class="klbth-icon-heart-1"></i></a>
</div>
#endif
it seems that the way i access the products is the wrong way thought i still have to test if the there's a probleme with adding to the favorite product
$currentTime = date("Y-m-d");
if ($favorie = auth()->user()->favorie ?? false) {
$favprds = $favorie->produits;
} else {
$favprds = [];
}
Can anyone help me? I have created a table with checkbox. but I keep losing the table header name because it was being replaced by the checkbox. The first column with checkbox should be Notify Me and the other is Email Me. How can I put those header names together with the checkbox? here is the code that I have created:
<template>
<Modal #close="doClose">
<template v-slot:container>
<section class="card settings-vue-modal-container">
<header class="card-header">
<h2>Settings</h2>
<!-- <span class="custom-close fa fa-times" #click="doClose"></span> -->
</header>
<div class="card-body">
<div class='table-design'>
<SimpleDatatable
:init_data="tableData"
:init_columns="columns"
:init_is_loading="isTableLoading"
:isColumnCustomizable="false"
:isBoredered="true"
:isTableHeaderSticky="true"
:removeBorderWrapper="true"
:showTotalResult="false"
tableContentClass="users-table-content"
#changePage="changePage"
#getTableData="setTableData"
#getSelectedData="getSelectedData"
>
</SimpleDatatable>
</div>
</div>
<footer class="card-footer">
<div class="btn-group ml-auto float-right">
<button type="button" class="btn btn-secondary btn-close" #click="doClose">Close</button>
</div>
</footer>
</section>
</template>
</Modal>
</template>
<script>
import Modal from "../Reusable/Modal"
import SimpleDatatable from '../Others/SimpleDatatable';
export default {
components: {
Modal,
SimpleDatatable
},
data() {
return {
settingsData: [],
isTableLoading: false,
params: {
page: this.currentPage,
page_limit: 10,
search: '',
role: ''
},
columns: [
{
label: 'Task Schedule',
field: 'name',
align: 'center',
default: true
},
{
label: 'Notify Me',
type: 'checkbox',
align: 'center',
width: 200
},
{
label: 'Email Me',
type: 'checkbox',
align: 'center',
width: 200
}
],
tableData: {},
currentPage: 1,
selectedData: [],
requiredData: {},
errors: {},
name: '',
};
},
created() {
this.getTableData()
},
watch: {
currentPage(newValue, oldValue) {
this.params.page = newValue
this.getTableData()
}
},
methods: {
doClose() {
this.errors = {};
this.name = '';
this.$emit('close');
},
changePage(event) {
this.currentPage = event
},
setTableData(data) {
this.tableData = data
},
getSelectedData(data) {
this.selectedData = data.map(x => x.id)
},
getTableData() {
this.isTableLoading = true
let url = '/tasks/api/getAll'
axios
.post(url, this.params)
.then(response => {
this.setTableData(response.data)
this.isTableLoading = false
})
.catch(errors => {
this.isTableLoading = false
console.log(errors)
})
},
}
}
</script>
Thank you. Below is also the SimpleDatatable being used:
<template>
<div class="row">
<SeeMore
:content="this.seeMoreContent"
v-show="seeMoreModalVisibility"
#close="seeMoreModalVisibility=false"
/>
<div class="col-lg-12">
<CustomizeColumnModal
v-show="showColumnModal"
#close="showColumnModal = false"
:columns="init_columns"
#getCols="getColumn"
/>
</div>
<div class="col-lg-12">
<div
class="panel panel-default"
style="margin-bottom: 0"
:class="{ 'no-border': removeBorderWrapper }"
>
<div
class="panel-body"
style="margin-bottom: 0"
:class="{ 'no-border': removeBorderWrapper }"
>
<loading :active.sync="isLoading" :is-full-page="fullPage" style="z-index: 3;"></loading>
<div class="pull-left">
<slot name="functional_upper_left"></slot>
<b
class="ml-3"
v-if="data.total && showTotalResult && totalResultPosition === 'upperLeft' "
>Total Result: {{data.total | addComma }}</b>
</div>
<button
class="btn btn-lg btn-primary pull-right"
v-if="isColumnCustomizable"
#click="showColumnModal = true"
style="margin-bottom: 15px;"
>
<span class="fa fa-list" style=" margin-right: 5px;"></span> Columns
</button>
<slot name="functional_buttons"></slot>
<div class="table table-responsive" style="overflow: auto; max-height: 550px;">
<table
class="table table-hover table-striped"
:class="{ 'table-bordered': isBoredered }"
style="margin-bottom: 0"
>
<thead>
<tr>
<th
v-for="(col, index) in columns"
:class="{'amzentrix-th-sticky' : isTableHeaderSticky, 'with-select-dropdown': col.type === 'checkbox' && isSelectOptions }"
:key="index"
:style="{ minWidth: (col.width) ? `${col.width}px`: '100px', textAlign: (col.align) ? `${col.align}` : 'left' }"
>
<template v-if="col.type === 'checkbox'">
<div class="dropdown">
<input type="checkbox" #click="doSelectAll" v-model="isSelectAll" />
<a
class="dropdown-toggle"
id="dropdownSelectOptions"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
v-if="isSelectOptions"
/>
<div class="dropdown-menu" aria-labelledby="dropdownSelectOptions">
<span class="dropdown-item" #click="doSelectAllOnly">Select All</span>
<span class="dropdown-item" #click="doSelectTop(10)">Select Top 10</span>
<span class="dropdown-item" #click="doSelectTop(20)">Select Top 20</span>
</div>
</div>
</template>
<template v-else-if="col.sortable">
<div class="sortable_col" #click="sortCol(index)">
<span>{{ col.label }}</span>
<span class="sortable_icons">
<i class="fa fa-sort-up" :class="{ active: col.currentSort === 'ASC'}" />
<i
class="fa fa-sort-down"
:class="{ active: col.currentSort === 'DESC'}"
/>
</span>
</div>
</template>
<template v-else>{{ col.label }}</template>
</th>
</tr>
</thead>
<tbody v-if="data.total !== 0">
<template v-for="(row, index) in data.data">
<tr :key="index">
<td
v-for="(col, index) in columns"
:class="tableContentClass"
:style="{
textAlign: (col.align) ? `${col.align}` : 'left',
'vertical-align': (col.valign) ? col.valign : 'middle'
}"
:key="index"
>
<template v-if="col.type == 'checkbox' ">
<div class="vue-checkbox">
<input
type="checkbox"
:checked="row.selected"
#click="doSelect(row, $event)"
/>
</div>
</template>
<template v-else-if="col.type === 'action'">
<slot :name="`action-${row.id}`">
<slot name="action" :data="row" />
</slot>
</template>
<template v-else-if="col.type == 'date'">{{ timeHumanize(row[col.field]) }}</template>
<template
v-else-if="col.type == 'complete_date'"
>{{ completeDateFormat(row[col.field]) }}</template>
<template v-else-if="col.type == 'raw'">
<div v-html="row[col.field]"></div>
</template>
<template v-else-if="col.type == 'rounded_numbers'">
<div>{{ row[col.field] ? Number(row[col.field]).toFixed(4) : row[col.field] }}</div>
</template>
<template
v-else-if="col.type == 'status'"
>{{ row[col.field] ? 'Active': 'Inactive' }}</template>
<template v-else-if="col.type == 'more'">
<div v-if="row[col.field]">
<p v-html="seeMoreTexts(row[col.field].replace(/<\/?[^>]+(>|$)/g, ''))"></p>
<small
class="see-more"
#click="seeMore(row[col.field])"
v-if="row[col.field].length> 20"
>See More</small>
</div>
<p v-else>-</p>
<!-- {{ row[col.field] ? '<h1>awit</h1>' : '-' }} -->
</template>
<template v-else-if="col.type == 'field_value'">
<slot name="field_value" :data="row"></slot>
</template>
<template v-else>{{ row[col.field] ? row[col.field] : '-' }}</template>
</td>
</tr>
</template>
</tbody>
<tbody v-else>
<tr>
<td align="center" colspan="1000">
<slot name="no-result">
<span style="margin-right: 5px">No Data Found.</span>
</slot>
</td>
</tr>
</tbody>
</table>
</div>
<!-- PAGINATION -->
<nav v-if="data.total && data.total !== 0 && !data.single">
<ul class="pagination" :class="`float-${paginationPosition}`">
<li
class="page-item pagination-total-result px-3"
v-if="data.total && showTotalResult && totalResultPosition === 'bottomPaginationLeftSide'"
>
Total Result:
<b class="ml-2">{{data.total | addComma }}</b>
</li>
<slot name="pagination-left" />
<li class="page-item pr-3 page-limit-select" v-if="isCustomResultPerPage">
<label for="results-per-page">Results per page:</label>
<input
class="form-control"
id="results-per-page"
type="number"
min="1"
#change="handleChangeItemsPerPage"
v-model="page_limit"
/>
</li>
<li
class="page-item"
:class=" data.current_page <= 1 ? 'disabled' : '' "
#click=" changePage((data.current_page - 1))"
>
<a
class="page-link"
:href=" (data.current_page > 1) ? `#page-${data.current_page - 1}` : `#page-1`"
aria-label="Previous"
>
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>
<li
class="page-item"
v-for="(n, index) in pagination(data.current_page, data.last_page)"
:class="(n === data.current_page) ? 'active' : ''"
:key="index"
#click="changePage(n)"
>
<a class="page-link" :href="(typeof n == 'number') ? `#page-${n}` : '#' ">{{ n }}</a>
</li>
<li
class="page-item"
:class=" data.current_page >= data.last_page ? 'disabled' : '' "
#click=" changePage((data.current_page + 1))"
>
<a
class="page-link"
:href=" (data.current_page < data.last_page) ? `#page-${data.current_page + 1}` : `#page-${data.last_page}`"
aria-label="Next"
>
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>
<slot name="pagination-right" />
</ul>
</nav>
</div>
</div>
</div>
</div>
</template>
<style scoped src='bootstrap/dist/css/bootstrap.min.css'></style>
<script>
import moment from "moment";
import CustomizeColumnModal from "./Datatable/CustomizeColumn";
import SeeMore from "./SimpleDatatableModal";
export default {
components: {
CustomizeColumnModal,
SeeMore
},
props: {
init_data: {
type: Object,
required: true
},
init_columns: {
type: Array,
required: true
},
init_is_loading: {
type: Boolean,
default: false
},
init_page_limit: {
type: Number,
default: 0
},
isSelectOptions: {
type: Boolean,
default: false
},
isColumnCustomizable: {
type: Boolean,
default: false
},
isBoredered: {
type: Boolean,
default: false
},
isTableHeaderSticky: {
type: Boolean,
default: false
},
isCustomResultPerPage: {
type: Boolean,
default: false
},
removeBorderWrapper: {
type: Boolean,
default: false
},
showTotalResult: {
type: Boolean,
default: false
},
totalResultPosition: {
type: String,
default: "upperLeft"
},
tableContentClass: {
type: String,
default: ""
},
paginationPosition: {
type: String,
default: "left"
}
},
data() {
return {
data: { total: 0 },
columns: this.init_columns,
isLoading: this.init_is_loading,
fullPage: false,
isSelectAll: false,
showColumnModal: false,
seeMoreContent: "",
seeMoreModalVisibility: false,
page_limit: this.init_page_limit
};
},
watch: {
init_data(newData, oldData) {
this.data = newData;
this.isSelectAll = false;
if (this.isSelectOptions) {
this.getSelectedData();
}
},
init_is_loading(newData, oldData) {
this.isLoading = newData;
if (this.isSelectOptions) {
this.checkSelectHeaderModel(); //Will reset isSelectAll State. Important if you're using checkbox and with dynamic data.
}
},
init_columns(newCols) {
this.columns = newCols;
},
init_page_limit(newData) {
this.page_limit = newData;
}
},
filters: {
addComma(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
},
methods: {
resetSortColFields() {
const withSortColFields = this.columns.filter(col => col.currentSort);
const resetColFields = withSortColFields.map(col => {
col.currentSort = null;
return col;
});
},
//returns an object with sortType (eg. ASC or DESC ) and field (eg. DATE, ID)
sortCol(index) {
const { currentSort } = this.columns[index];
let sort = null;
this.resetSortColFields();
switch (currentSort) {
case "ASC":
sort = null;
break;
case "DESC":
sort = "ASC";
break;
default:
sort = "DESC";
}
this.columns[index].currentSort = sort;
this.$emit("sort", {
sortType: sort,
field: sort ? this.columns[index].field : null
});
},
doSelectAll(event) {
//single property for single set of data, means no paginated data.
//usually you want to use this if you're not using primarily the api of laravel's pagination.
//you just need to pass an initial object data with data and single properties
if (!this.data.total && !this.data.single) {
event.preventDefault();
return;
}
this.isSelectAll = !this.isSelectAll;
this.data.data.forEach(element => {
element.selected = this.isSelectAll;
});
if (!this.isSelectAll) this.$emit("getDeselectedData", this.data.data);
this.$emit("getTableData", this.data);
this.getSelectedData();
},
doSelectAllOnly() {
if (!this.isSelectAll) this.doSelectAll();
},
doSelectTop(num) {
this.data.data.forEach((element, index) => {
if (num > index) element.selected = true;
});
this.getSelectedData();
},
checkSelectHeaderModel() {
// to check if all data from the data is selected, if true, checkbox from header must be checked.
if (!this.data.data) return;
const newDataLength = this.data.data.length;
const newSelectedDataLength = this.data.data.filter(data => data.selected)
.length;
this.isSelectAll =
newDataLength && newDataLength === newSelectedDataLength ? true : false;
},
doSelect(row, event) {
let checked = Boolean(row.selected);
row.selected = !checked;
if (!row.selected) {
this.$emit("getDeselectedItem", row);
}
this.getSelectedData();
},
getSelectedData() {
const selected = this.data.data.filter(el => el.selected);
this.checkSelectHeaderModel();
this.$emit("getSelectedData", selected);
},
getColumn(event) {
if (this.isColumnCustomizable) {
this.columns = event;
this.$emit("getSelectedColumns", event);
}
},
timeHumanize(date) {
return moment(date).isValid() ? moment(date).fromNow() : date;
},
completeDateFormat(date) {
return moment(date).isValid()
? moment(date).format("MMM Do YYYY h:mm:ss a")
: date;
},
changePage(pageNumber) {
this.handleChangeItemsPerPage();
if (
pageNumber > 0 &&
pageNumber <= this.data.last_page &&
typeof pageNumber == "number" &&
this.data.current_page != pageNumber
)
this.$emit("changePage", pageNumber);
},
pagination(c, m) {
let current = c,
last = m,
delta = 3,
left = current - delta,
right = current + delta + 1,
range = [],
rangeWithDots = [],
l;
for (let i = 1; i <= last; i++) {
if (i == 1 || i == last || (i >= left && i < right)) {
range.push(i);
}
}
for (let i of range) {
if (l) {
if (i - l === 2) {
rangeWithDots.push(l + 1);
} else if (i - l !== 1) {
rangeWithDots.push("...");
}
}
rangeWithDots.push(i);
l = i;
}
return rangeWithDots;
},
seeMoreTexts(text) {
return text.length > 20 ? text.substring(0, 40) + "..." : text;
},
seeMore(data) {
this.seeMoreContent = data;
this.seeMoreModalVisibility = true;
},
handleChangeItemsPerPage(event) {
let value;
let changePage = false;
if (typeof event == "object") {
value = parseInt(event.target.value);
changePage = true;
} else {
value = parseInt(this.page_limit);
}
if (value <= 0 || typeof value != "number" || !value) {
value = 10;
this.page_limit = 10;
}
this.$emit("handleChangeItemsPerPage", parseInt(value), changePage);
}
},
mounted() {
//single property for single set of data, means no paginated data.
//usually you want to use this if you're not using primarily the api of laravel's pagination.
//you just need to pass an initial object data with data and single properties
this.data =
this.init_data.total || this.init_data.single
? this.init_data
: { total: 0 };
}
};
</script>
Guys I just created like/dislike buttons for every service! so I set a default grey color for each one of them, once the user click " like" it turns to green and for the opposite case it turns to red..
so I've created an ajax method for that...
I wanted to check if everything works fine with a simple alert()
but I got an error which is :
message: "Undefined property: Illuminate\Database\Eloquen\Builder::$like",…}
exception : "ErrorException"
— file : "C:\xampp\htdocs\dawerelzirou\app\Http\Controllers\ServiceController.php"
— line:164
message: "Undefined property: Illuminate\Database\Eloquent\Builder::$like"
trace : [
— { file: "C:\xampp\htdocs\dawerelzirou\app\Http\Controller\ServiceController.php", line: 164 }
]
This is like.js
$('.like').on('click', function() {
var like_s = $(this).attr('data-like');
var service_id = $(this).attr('data-serviceid');
$.ajax({
type: 'POST',
url: url,
data: {
like_s: like_s,
service_id: service_id,
_token: token
},
success: function(data) {
alert('ok');
}
});
});
This is the script:
<script type="text/javascript" src="{{ asset('js/like.js') }}"></script>
<script type="text/javascript">
var url="{{ route('like') }}";
var token="{{ Session::token() }}";
</script>
Here is the blade page :
#php
$like_count=0;
$dislike_count=0;
$like_statut="grey";
$dislike_statut="grey";
#endphp
#foreach ($services->likes as $like)
#php
if ($like->like ==1){
$like_count++;
}
else {
$dislike_count++;
}
if($like->like == 1 && $like->user_id==Auth::user()->id){
$like_statut="green";
}
else{
$dislike_statut="red";
}
#endphp
#endforeach
<div class="row">
<div class="col s12">
<button type="button"
data-like="{{$like_statut}}"
data-serviceid="{{$services->id}}"
class="like waves-effect waves-light btn {{$like_statut}}">
<i class="material-icons left">thumb_up</i>({{$like_count}})
</button>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<button type="button"
data-dislike="{{$dislike_statut}}"
class="dislike waves-effect waves-light btn {{$dislike_statut}}">
<i class="material-icons left">thumb_down</i>({{ $dislike_count}})
</button>
</div>
</div>
</div>
</div>
The route:
Route::post('/like','ServiceController#like')->name('like');
The "like" method in the controller:
public function like(Request $request)
{
$like_s = $request->like_s;
$service_id = $request->service_id;
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
if (!$like) {
$new_like = new Like;
$new_like->service_id = $service_id;
$new_like->user_id = Auth::user()->id;
$new_like->like = 1;
$new_like->save();
} elseif ($like->like == 1) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->delete()
;
} elseif ($like->like == 0) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->update(array('like' => 1))
;
}
}
This row:
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
seems incomplete, as it returns a query builder and not an object. The query builder has not a "like" property. If you want an object you should do: A first() at the end (or a get() followed by a foreach) seems to be missing.
I have a project in which i want to retrieve value from database via checkbox. But i cannot do this.
My controller code is
public function browseProfessionals() {
$userRoles = UserRole::whereIn('role_id', [2,3])->get();
$users = array();
$showUsers = array();
foreach ($userRoles as $userRole) {
$users[] = User::find($userRole->user_id);
}
$valid_providers = array();
$all_providers = array();
$user_role_all_providers = UserRole::where('role_id', 2)->get();
foreach ($user_role_all_providers as $user_role_all_provider) {
$all_providers[] = User::where('id', $user_role_all_provider->user_id)->first();
}
foreach ($all_providers as $all_provider) {
$user = User::where('id', $all_provider->id)->first();
$user_detail = UserDetail::where('user_id', $all_provider->id)->first();
$user_meeting = UserMeeting::where('user_id', $all_provider->id)->first();
$user_time = UserTime::where('user_id', $all_provider->id)->first();
if (!empty($user_detail->avatar) && !empty($user_meeting->meeting_id) && !empty($user_time->hour_rate) && $user->is_active == 1 && $user->is_deleted == 0) {
$valid_providers[] = $all_provider;
}
}
$data = [
'valid_providers' => $showUsers,
'industries' => Industry::where('is_active', 1)->where('is_deleted', 0)->get(),
'degrees' => UserDegree::where('degree_id', $user->degree_id)->get(),
];
return view('frontends.browse-professionals', $data);
}
My Blade template is
#extends ('frontends.layouts.app')
#section ('main')
<div id="content-block" class="margin-top-140">
<div class="container-fluid block custom-container">
<h3 class="block-title">Browse Professionals</h3>
<div class="block-subtitle"><span>Connect</span> <span>Learn</span> <span>Inspire</span> <span>Thrive</span> </div>
<div class="row">
{{--<form action="" method="post">--}}
<div class="col-md-2 left-feild">
<div class="margin-bottom-30">
<h3>Search Filters</h3>
</div>
#if(Auth::check() && Auth::user()->user_role->role_id == 1000000)
<div class="be-vidget">
<h3 class="letf-menu-article"> Looking To </h3>
<div class="creative_filds_block">
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(2)"> Seek Advice</label>
</div>
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(3)"> Share Advice</label>
</div>
</div>
</div>
<script>
function lookingTo(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('looking/to') }}/' + e,
success: function (result) {
$('#browse_professionals').html(result);
}
});
}
</script>
#endif
<div class="be-vidget">
<h3 class="letf-menu-article">Professionals</h3>
<div class="-creative_filds_block">
<div class="fp-panel-wrap">
<a class="toggle-btn active" onclick="open_industry()" href="#" data-target="#ul_industry" id="a_industry">Industry</a>
<ul id="ul_industry" class="fp-panel open" style="overflow:scroll; height:200px;">
#if(!empty($industries))
#foreach($industries as $industry)
<li value="{{ $industry->id }}">{{ (!empty($industry['name'])) ? $industry['name'] : '' }} </li>
#endforeach
#endif
</ul>
<script>
function industry_search(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('professionals/industry') }}/' + e,
success: function (result) {
$('#education_experience').html(result);
$('#a_industry').attr('class', 'toggle-btn');
$('#ul_industry').css('display', 'none');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'block');
$('#areaExperience').css('display', 'block');
}
});
}
function open_industry() {
$('#education_experience').css('display', 'block'); // display none hobe na. collapse hoye jabe
// $('#a_industry').attr('class', 'toggle-btn active');
// $('#ul_industry').css('display', 'block');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'none');
$('#areaExperience').css('display', 'none');
}
</script>
<div id="education_experience" style="">
<a id="a_education" class="toggle-btn" href="#" data-target="#eduLevel">Education Level</a>
<ul id="eduLevel" class="no-link fp-panel" style="overflow:scroll; height:200px;">
#if(!empty($degrees))
#foreach($degrees as $degree)
<li value="{{ $degree->id }}">{{ (!empty($degree['name'])) ? $degree['name'] : '' }}</a> </li>
#endforeach
#endif
</ul>
<a id="a_experience" class="toggle-btn" href="#" data-target="#areaExperience">Areas of Experience</a>
<ul id="areaExperience" class="no-link fp-panel" style="overflow:scroll; height:200px;">
</ul>
</div>
</div>
</div>
</div>
<div class="be-vidget">
<h3 class="letf-menu-article">Meeting Preferences</h3>
<label>Price</label>
<br> <br>
<input type="hidden" id="price_ranger" class="range-slider" value="23"/>
<label style="margin-top: 30px;">Type</label>
<div class="form-group">
<select class="form-input" id="meeting_type">
<option value="3">All</option>
<option value="1">Phone Meeting</option>
<option value="2">Web Meeting</option>
</select>
</div>
</div>
<button id="search_professionals" type="button" class="btn color-2 size-2 btn-block hover-1">Apply Filter</button>
#if(Session::has('remove_filter'))
<button type="button" class="btn btn-danger size-2 btn-block hover-1">Remove Filter</button>
#endif
<script>
var industry = '';
$('#ul_industry li').click(function() {
industry = $(this).attr('value');
});
$("#search_professionals").click(function () {
var degrees = new Array();
$('input[name="degrees_checkbox"]:checked').each(function() {
degrees.push(this.value);
});
var experiences = new Array();
$('input[name="experiences_checkbox"]:checked').each(function() {
experiences.push(this.value);
});
var price_ranger = $("#price_ranger").val();
var price_ranger_array = price_ranger.split(",");
var start_price = price_ranger_array[0];
var end_price = price_ranger_array[1];
var meeting_type = $("#meeting_type").val();
$.ajax({
'type' : 'post',
'url' : '{{ URL::to('search/professionals') }}',
'data' : {
'industry' : industry,
'educationLevels' : degrees,
'areasOfExperiences' : experiences,
'start_price' : start_price,
'end_price' : end_price,
'meeting_type' : meeting_type
},
'success' : function (result) {
console.log(result);
$('#browse_professionals').html(result);
}
});
});
</script>
</div>
{{--</form>--}}
<div class="col-md-10">
<div id="browse_professionals" class="row _post-container_">
#if (!empty($valid_providers))
#foreach ($valid_providers as $provider)
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url('{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}')">
<img src="{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}" alt="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">
</div>
</figure>
<div class="be-post-title">{{ (!empty($provider->user_share->share)) ? str_limit($provider->user_share->share, 90) : '' }}</div>
<div class="author-post">
<span>{{ !empty($provider->user_detail->first_name) ? $provider->user_detail->first_name : '' }} {{ !empty($provider->user_detail->last_name) ? $provider->user_detail->last_name : '' }}</span>
</div>
<span>{{ (!empty($provider->user_detail->credentials)) ? str_limit($provider->user_detail->credentials, 25) : '' }}</span>
<div data-value="4" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">Contact</a>
<h3 class="rate"> ${{ (!empty($provider->user_time->hour_rate)) ? $provider->user_time->hour_rate : '' }} /hr</h3>
</div>
</div>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
My Searchcontroller is
public function searchProfessionals (Request $request)
{
$industry = $request->input('industry');
$educationLevels = $request->input('educationLevels');
$areasOfExperiences = $request->input('areasOfExperiences');
$startPrice = $request->input('start_price');
$endPrice = $request->input('end_price');
$meetingType = $request->input('meeting_type');
if ($meetingType == 1) {
$type = [1, 1];
} elseif ($meetingType == 2) {
$type = [2, 2];
} elseif ($meetingType === 3) {
$type = [1, 2];
} else {
$type = [1, 2];
}
$userMeetings = array();
$userRoles = array();
$users = array();
$showUsers = array();
$userHourRates = array();
// return response($industry);
$userIndus = UserIndustry::where('industry_id', $industry)->get();
if (!empty($userIndus)) {
foreach ($userIndus as $userInd) {
$userHourRates = UserTime::where('user_id', $userInd->user_id)->whereBetween('hour_rate', [$startPrice, $endPrice])->first();
}
// $userHourRates = UserTime::whereBetween('hour_rate', [$startPrice, $endPrice])->get();
if (!empty($userHourRates)) {
foreach ($userHourRates as $userHourRate) {
$userMeetings[] = UserMeeting::whereIn('meeting_id', $type)->where('user_id', $userHourRate->user_id)->first();
}
if (!empty($userMeetings)) {
foreach ($userMeetings as $userMeeting) {
$userRoles[] = UserRole::where('user_id', $userMeeting['user_id'])->where('role_id', '!=', 1)->first();
}
if (!empty($userRoles)) {
foreach ($userRoles as $userRole) {
$users[] = User::find($userRole['user_id']);
}
if (!empty($users)) {
foreach ($users as $u) {
$user = User::find($u['id']);
$userDetail = UserDetail::where('user_id', $u['id'])->first();
$userShare = UserShare::where('user_id', $u['id'])->first();
$userMeeting = UserMeeting::where('user_id', $u['id'])->first();
$userWeek = UserWeek::where('user_id', $u['id'])->first();
$userTime = UserTime::where('user_id', $u['id'])->first();
if (
$user['is_active'] == 1 && $user['is_deleted'] == 0 && !empty($userDetail['avatar']) && !empty($userDetail['first_name']) &&
!empty($userDetail['last_name']) && !empty($userDetail['credentials']) && !empty($userShare['share']) &&
!empty($userShare['seek']) && !empty($userMeeting['meeting_id']) && !empty($userWeek['week_id']) &&
!empty($userTime['start_time']) && !empty($userTime['end_time']) && !empty($userTime['hour_rate'])
) {
$showUsers[] = $u;
}
}
if (!empty($showUsers)) {
$string = '';
foreach ($showUsers as $showUser) {
$userShow = User::find($showUser->id);
$userDetailShow = UserDetail::where('user_id', $showUser->id)->first();
$userShareShow = UserShare::where('user_id', $showUser->id)->first();
$userRatingShow = Review::where('provider_id', $showUser->id)->orWhere('seeker_id', $showUser->id)->avg('rating');
$userTimeShow = UserTime::where('user_id', $showUser->id)->first();
$string .= '
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url(' . url($userDetailShow->avatar) . ')">
<img src="' . url($userDetailShow->avatar) . '" alt="omg">
</div>
</figure>
<div class="be-post-title">' . str_limit($userShareShow->share, 90) . '</div>
<div class="author-post">
<span>
<a href="' . url($userShow->username) . '">' .
$userDetailShow->first_name . ' ' . $userDetailShow->last_name . '
</a>
</span>
</div>
<span>' . $userDetailShow->credentials . '</span>
</div>
<div data-value="' . $userRatingShow . '" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="' . url($userShow->username) . '">Contact</a>
<h3 class="rate">$' . $userTimeShow->hour_rate . '/hr</h3>
</div>
</div>
</div>
';
}
return response($string);
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
}
Please help me how can i show value via checkbox. Please help me solving this.
Try to debug your JavaScript by F12, and notice there is any error or not.
if not there is no Javascript problem, you can also check ajax request return data on network tab.
I am working on AngularJS project I am using ng-repeat to show data, There is a Edit button that enable editing for particular row. On edit button click there is Save and Cancel button shows. On save button click it call $http.post to update data in database. Data are shown in gal unit and store as liter so when I click on save button it first convert to liter and then store in db.
Now the problem is when I click on Save button for once it work correctly, But when I click twice on Save button it convert gal -> liter -> liter and then save to db.
So I want to do is if $http request is already in process then do not accept another $http request.
I have tried to disable the button but still it is clickable.
HTML:
<div class="taxi_output" ng-repeat="item in vmDosings.data track by $index" >
<div class="row">
<div class="col-lg-4 text-center one" ng-bind="item.dos_nr"></div>
<div class="col-lg-4 text-center two">
<div ng-if="item.enableContent">
<input id="{{$index}}" class="font-size input-{{$index}}" ng-class="{ 'error' : vmDosings.error.level || vmDosings.error.undef || vmDosings.error.exist }" type="text" ng-model="item.level" ng-change="itemChanges(item)" ng-disabled="!item.enableContent"/> {{::$root.getEinheiten($root.GlobalData.config.volumemessurement)}}
</div>
<div ng-if="!item.enableContent" >
<p class=""> {{ item.level + ' ' + $root.getEinheiten($root.GlobalData.config.volumemessurement)}} </p>
</div>
</div>
<div class="col-lg-4" ng-if="item.enableContent == false" style="vertical-align: middle">
<a class="btn" ng-click="enableContent(item, $index)" event-focus="click" event-focus-id="{{$index}}" tooltip-placement="bottom" tooltip="{{::$root.getLabel('edit')}}">
<i style="cursor:pointer;" class="fa fa-edit fa-2x"></i>
</a>
<a class="btn" ng-if="vmDosings.data.length > 1" ng-click="removeFromList(item, $index)" tooltip-placement="bottom" tooltip="{{::$root.getLabel('delete')}}">
<i style="cursor:pointer;" class="fa fa-trash fa-2x"></i>
</a>
</div>
<div class="col-lg-4" ng-if="item.enableContent == true">
<a class="btn" ng-click="saveChanges(item, $index)" tooltip-placement="bottom" tooltip="{{::$root.getLabel('save')}}">
<i style="cursor:pointer;" class="fa fa-save fa-2x"></i>
</a>
<a class="btn" ng-click="removeFromList(item, $index)" tooltip-placement="bottom" tooltip="{{::$root.getLabel('delete')}}">
<i style="cursor:pointer;" class="fa fa-trash fa-2x"></i>
</a>
<a class="btn" ng-click="restoreChanges(item)" tooltip-placement="bottom" tooltip="{{::$root.getLabel('reset')}}">
<i style="cursor:pointer;" class="fa fa-remove fa-2x"></i>
</a>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div ng-if="item.enableContent && vmDosings.validate == false">
<div class="panel panel-danger" style="margin-top:5px; margin-bottom:0px;">
<div class="panel-heading" style="padding:0">
<ul style="padding: 5px 0px 5px 30px;">
<li ng-if="vmDosings.error.level" ng-bind="getLabel('only_floats_with_one_digit')"></li>
<li ng-if="vmDosings.error.undef" ng-bind="getLabel('inputs_empty_not_allowed')"></li>
<li ng-if="vmDosings.error.exist" ng-bind="getLabel('data_already_exist')"></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="hr-line-dashed"></div>
</div>
AngulrJS:
Enable Edit Mode:
$scope.enableContent = function(data, $index) {
angular.forEach(vmDosings.data, function(value, key) {
vmDosings.data[key].enableContent = (value.id == data.id ? true : false );
});
$timeout(function () {
$('.input-'+ $index).focus();
$('.input-'+ $index).val($('.input-'+ $index).val());
});
}
save button click:
$rootScope.GlobalData.config.volumemessurement get the id of unit
$rootScope.calcunits(9, id, data['level']); is a function for convert
$scope.saveChanges = function(data) {
var id = $rootScope.GlobalData.config.volumemessurement;
data['level'] = $rootScope.calcunits(id, 9, data['level']);
checkValues(data);
var checked = true;
for (i in vmDosings.error) {
if (vmDosings.error[i]) {
checked = false;
vmDosings.validate = false;
break;
}
}
if(checked == true) {
DosingsServices.saveChanges(data).then(function (result) {
if( result.data.message == 'success' && result.data.status == 200) {
DosingsServices.getDosings($stateParams.taxi_id).then(function (result) {
//vmDosings.data = result.data.dosings
var data = result.data.dosings;
var id = $rootScope.GlobalData.config.volumemessurement;
var i = 0;
for(i = 0; i <= data.length; i++) {
angular.forEach(data[i], function(value, key){
if(key == "level")
data[i][key] = $rootScope.calcunits(9, id, value)
});
}
vmDosings.data = data;
});
}
else if( result.data.message == 'Data Already Exist') {
data['level'] = $rootScope.calcunits(9, id, data['level']);
vmDosings.error.exist = true;
vmDosings.validate = false;
}
});
}
}
What you need is interceptors method of $httpProvider. It give you full control over any http call within Angular scope ( request,requestError,response,responseError methods).
If service call is already in progress you can skip next call or put it in a queue to call once you get response from previous call any other thing you want to do
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
Set a flag var inProgress = true; before your post method. Check on if this flag is set before you post. Set flag to false when post method is finished (finally).
You can also use this flag to enable/disable save button.