Alert: Learning Vue :)
I have a list of items displayed in tables along with status button
I tried to use the v-for but than my search and sortable options doesn't work so I am displaying data using php (laravel) So I only want my status button to work with Vue
I have so far managed to make it work but the only problem is class binding not working for clicked item and it is changing for all of the buttons
here are my html
<td class="center">
<a href="#" class="btn btn-mini">
<i class="fa fa-fw" :class="{'fa-thumbs-o-up': form.isStatus, 'fa-thumbs-o-down': !form.isStatus }" #click="onStatus({{$row->id}})">
</i></a>
</td>
here are my due codes
new Vue({
el: '#viewall',
data: {
form: new Form({
status: '',
isStatus: true
}),
errors: new Errors()
},
methods: {
onStatus(id) {
this.form.statusUpdate('post', 'updatestatus', id)
}
}
})
class Form {
constructor() {}
// update status
statusUpdate(requestType, url, id) {
let data = new FormData()
data.set('pageid', id)
return new Promise((resolve, reject) => {
axios[requestType](url, data)
.then(response => {
this.isStatus = response.data.new_status
})
.catch(error => {})
})
}
}
To answer this:
the only problem is class binding not working for clicked item and it is changing for all of the buttons
Obviously because all of your buttons depends on the same one variable isStatus.
You should have different isStatus for each button, like isStatus_n:
But I understand that you don't have those dynamic Vue data property because it is from Laravel.
So you can do like:
<td class="center">
<a href="#" class="btn btn-mini">
<i class="fa fa-fw" :class="{'fa-thumbs-o-up': form.isStatus_{{$row->id}} && form.isStatus_{{$row->id}}.selected, 'fa-thumbs-o-down': !form.isStatus_{{$row->id}} }" #click="onStatus({{$row->id}})">
</i>
</a>
</td>
Then on your method:
// This will insert/update the form.isStatus_n
var newSet = {selected: true};
this.$set(this.form, 'isStatus_'+id, newSet);
Made a simple demo: https://jsfiddle.net/j9whxnfs/37/
Related
I need help with a question, I am two trying to make a disabled save button be enabled when someone changes the form for two days, I realized today that the purchase I'm doing lodash is not working, whenever I change something in the form so much the oldForm variable as the form, are also changed, I've done everything and even so I couldn't enable the button.
Button component code in vuejs
<template>
<div
v-bind:class="isActive()"
class="flex w-max rounded text-xs">
<inertia-link class="py-2 px-6 uppercase" v-if="href" :href="href">
<slot></slot>
</inertia-link>
<button v-if="!href"
disabled="!changed"
class="py-2 px-6 uppercase" type="button">
<slot></slot>
</button>
</div>
</template>
<script>
import _ from 'lodash'
export default {
props: {
href: String,
active: {
type: Boolean,
default: true
},
form:{
type: Object
},
processing: {
type: Boolean,
default: false
}
},
data(){
return{
changed: false,
}
},
computed:{
oldForm(){
return this.form;
}
},
watch:{
oldForm(){
this.oldForm = _.cloneDeep(this.form)
},
form:{
handler(){
this.changed = !_.isEqual(this.form, this.oldForm)
console.log(this.form)
console.log(this.oldForm)
},
deep: true,
},
},
}
</script>
Calling the button on the form:
<submit-button
:processing="form.processing"
:form="form"
:active="isFormChanged" #click.native="save()">
<i class="fas fa-save"></i> Salvar
</submit-button>
With console.log, I found they were the same, how do I store one and compare with the other to enable the button?
I can only use VueJS and lodash to solve this.
So, I have a CRUD and one button to modify that should redirect to another page with the id of the person, I tried to do it with jquery this way
fetchList()
function fetchList() {
$.ajax({
url: 'lista.php',
type: 'GET',
success: function (response) {
let task = JSON.parse(response);
let template = '';
task.forEach(task => {
template +=
`<tr pacienteId="${task.id_pac}">
<td>${task.apellido} </td>
<td>${task.nombre}</td>
<td>${task.dni}</td>
<td>${task.fecha_nacimiento}</td>
<td>${task.fecha_ingreso}</td>
<td>${task.obra_social}</td
// <td <span class="badge pacActivo">Activo</span> </td>
<td>
<div class="btn-group btn-group-toggle d-flex justify-content-center">
<i class="fas fa-edit"></i>
<button class="btn btn-sm butDel darBaja">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</td>
</tr>`
});
$("#listadoPacientes").html(template);
}
});
}
and this is the modify
$(document).on('click', '#modificar', function (e) {
var href = $(this).attr('href');
let element = $(this)[0].parentElement.parentElement.parentElement
let id = $(element).attr('pacienteId')
// Save information
// Check if any ID is aviable
if (id) {
// Save the url and perform a page load
var direccion = href + '&id=' + id;
window.open(direccion);
console.log(id)
} else {
// Error handling
alert('algo salio mal')
}
})
but the problem it that I get this error:
Undefined index: id in
C:\xampp\htdocs\sistema\modulos\Pacientes\modificar.php
where i have the ID from jquery inside a variable
Solution:
You append your href attribute in jQuery with only an "&". You need an "?" instead of an "&".
Solution: You put an GET parameter behinde your jQuery HTML build process href-tag.
Short you are generating an URL like:
modificar.php&id=0
correct is
modificar.php**?**id=0
Example:
if (id) {
// Save the url and perform a page load
var direccion = href + '?id=' + id; // changed the & to an ?
window.open(direccion);
console.log(id)
} else {
// Error handling
alert('algo salio mal')
}
I'm using Laravel Livewire in my project, I use wire:loading for loading the state while clicking. I iterated all the tasks in foreach loop but the loading state applies for all components. Here is the code.
Blade file
GitLab: https://gitlab.com/tasklog/tasklog/-/blob/master/resources/views/livewire/home/tasks.blade.php
<button type="button" wire:click="togglePraise({{ $task->id }}, {{ $task->user->id }})">
👏
<span class="small text-black-50 font-weight-bold">
{{ $task->task_praise->count() }}
</span>
<div wire:loading wire:target="togglePraise">
Processing...
</div>
</button>
Controller file
GitLab: https://gitlab.com/tasklog/tasklog/-/blob/master/app/Http/Livewire/Home/Tasks.php
public function togglePraise($id, $user_id)
{
if (Auth::check()) {
if (Auth::user()->id === $user_id) {
session()->flash('message', 'Forbidden!');
return;
}
$isPraised = TaskPraise::where([
['user_id', Auth::user()->id],
['task_id', $id],
])->count();
if ($isPraised === 1) {
TaskPraise::where([
['user_id', Auth::user()->id],
['task_id', $id],
])->delete();
return true;
} else {
TaskPraise::create([
'task_id' => $id,
'user_id' => Auth::user()->id,
]);
return true;
}
} else {
return session()->flash('message', 'Forbidden!');
}
}
I know the question was before the realease of v2, yet adding the answer for v2 for reference.
as per the Livewire docs if you're using v2, you may specify the action and its parameters in the wire:target directive. For your example, it would be like this:
wire:target="togglePraise({{ $task->id }}, {{ $task->user->id }})"
I was unable to do it by loading targets to actions with parameters so I used jquery with the livewire
Button in the table loop with default d-none loading icon class
<div class="col-3">
<button class="btn btn-sm btn-default btn-save ">
Save <span class="loading-icon d-none">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:14px"></i></span>
</button></div>
Javascript code to call livewire and enable loading
$('.btn-save').click(function (e) {
e.preventDefault();
$('.parameter-value').removeClass("error-field");
var row = $(this).closest('tr');
row.find('.loading-icon').removeClass('d-none');
var parameter = row.data('parameter');
var value = $.trim(row.find('.parameter-value').val())
if(value == ""){
row.find('.parameter-value').addClass('error-field');
}else{
row.find('.parameter-value').removeClass('error-field');
//Livewire call
#this.addParameterValue(parameter,value);
}
});
before LiveWire function ends dispatch browser event
public function addParameterValue($parameterID,$value)
{
...
$this->dispatchBrowserEvent('parameter_value-saved');
}
Handle Browser event from javascript end and remove hide loading icon inside
window.addEventListener('parameter_value-saved', event => {
$('.loading-icon').addClass('d-none');
})
I had the same issue as you. After researching, I decided to make 2 wire:click, IDK if this is the best way to solve this but yeah that's what I do
<div wire:loading wire:target="LoadingAnimation({{$loop->iteration}})">
// icon loading or teks for showing this row load sth
</div>
......
<div wire:click="LoadingAnimation({{$loop->iteration}})">
<a wire:click="setUpdateid({{$author->id}})">
// your content here , teks or maybe an icon
</a>
</div>
If you have any questions let me know, Happy coding!
Edit: Don't forget to make the method inside the class, like the LoadingAnimation and the setUpdateid
When I click on the delete modal of first row, the modal pops up and the data is getting deleted. If I click on the row other than the first row, it shows the error as id undefined.
Controller:
public function project_show(){
$this->load->view('project_show',$data);//page where delete button is present
$this->load->view('project_del');//modal page which opens on delete button
}
public function delete_get_id($pcode){
if($this->input->post('deleteproj'))
{
$this->project_model->delete_project($pcode);
}
}
ajax:
$('#deletebutton').click(function(){
var pcode = $(this).data('id');
$('#deleteproject').data('id', pcode);
});
$('#deleteproject').click(function(){
var pcode = $(this).data('id');
$('#deletemodal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
console.log(pcode);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/project/delete_get_id/"+ pcode,
data: {
pcode: pcode,
deleteproj: 1,
},
success: function (data) {
$("#deletemodal").modal('hide');
showproject();
}
});
});
view page of button:
<button id="deletebutton" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#deletemodal" data-id="<?php echo $row->project_code;?>"><span class = "fa fa-trash-o"></span> Delete</button>
view page of modal:
<div class="modal fade bs-example-modal-sm" id="deletemodal" ...>
.....
<button class="btn btn-danger btn delete" id="deleteproject"><span class="glyphicon glyphicon-trash"></span>Delete</button>
How will I pass the id along with "data-target" tag from page where button is present to modal page so that the particular row gets deleted
Please note that ID selector is supposed to be unique in a HTML document. And jQuery expects that to be true. So instead of using ID, you should use class name for the delete button
$('.deletebutton').click(function(){
var pcode = $(this).data('id');
$('#deleteproject').data('id', pcode);
});
//...
<button
class="deletebutton btn btn-danger btn-xs"
data-toggle="modal"
data-target="#deletemodal"
data-id="<?php echo $row->project_code;?>"
>
<span class = "fa fa-trash-o"></span> Delete
</button>
Assuming your showproject() function won't accidentally remove / recreate your #deleteproject button, things should work for you.
I have a problem with AJAX and CodeIgniter, I want to get total count of users in database but there is no data found.
my controller:
public function TotalUsers()
{
if($this->input->post("action")=='GetTotalUsers')
{
$this->load->model("usersmodel");
$totalcount=$this->usermodel->GetTotalUserCount();
echo $totalcount;
}
}
my model:
public function GetTotalUserCount()
{
$query = $this->db->get("users");
return $query->num_rows();
}
My html and jquery:
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3 id="totaluser"></h3>
<p>Total Users</p>
</div>
<div class="icon">
<i class="ion ion-person-add"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
<script>
$(document).ready(function () {
GetTotalUsersCount();
function GetTotalUsersCount() {
var action='GetTotalUsers';
$.ajax({
url:"<?php echo base_url()?>Users/TotalUsers",
method:"post",
data:{action:action},
success:function (data) {
$("#totaluser").html(data)
}
})
}
})
</script>
I think you might be sending it encoded in JSON while the controller is expecting it serialized, although I'm not sure.
Run var_dump() on $this->input->post("action").
If that doesn't give GetTotalUsers, then that's you're problem. You'll need to either set the controller to accept raw post data and decode as json, serialize the data instead of using a javascript object (JSON), or if possible, just remove the action conditional because currently it doesn't look useful as shown.
I suspect that url: is not evaluating to the correct value. There are a couple syntax errors (missing semi-colons) too. Try this JavaScript. Use your browser's "Developer Tools" to examine the headers to see where the post "goes" and that "action" is being posted.
$(document).ready(function () {
GetTotalUsersCount();
function GetTotalUsersCount() {
$.ajax({
url: '<?php echo base_url("Users/TotalUsers"); ?>',
method: "post",
data: {action: 'GetTotalUsers'},
success: function (data) {
$("#totaluser").text(data);
}
});
}
});
I'm curious why you use ajax and don't simply determine and pass the total count to the initial loading of the view?
1.Use Ctrl+Shift+I (or navigate to Current Page Control > Developer >
Developer Tools )or( use right click on your page and then select inspect
element)
2.Go to "Network" tab
3.Find your ajax request in "Name Path" column
4.Click on the specific ajax link