VUE on-changed checked and ajax request - ajax

Im using bootstrap vue:
<b-form-checkbox #change="onoff('concurency_filter')" v-model="concurency_filter.onoff" switch size="lg"></b-form-checkbox>
And I need call ajax with state of this checkbox:
onoff: function (filter) {
axios.put('/api/user/accounts/'+this.account_id+'/togglefilter',
{
filter: filter,
status: this[filter].onoff //here still old value in this.concurency_filter.onoff
}).then(response => {
..........
});
},
But v-model still not changed when ajax is called. When checkbox clicked v-model must toggle true/false, but ajax called before v-model toggle it. How to deal with it?
I know that I can use WATCH in vue, but when first time ajax loading data it's triggering this WATCH event. I want trigger it only on click

Success:
onoff('concurency_filter', $event)
$event will contain exact value of checkbox right after click

Related

Inertia: Reload page with updated data without modifying scroll position

I'm using Inertia/Laravel/VueJs. I have a page with many posts and each post can be marked as completed. When a post is marked as completed on the front-end I have a v-bind which toggles a CSS class which should be applied to completed tasks.
The behaviour I would like is: a user scrolls down a page, clicks the completed button, and the back-end sends that newly updated data to the front-end, making the v-bind true, causing the CSS class to be applied without jumping to the top of the page.
With the code below I can click the completed button, and it is updated in the database, but that new data isn't sent to the front-end.
Controller:
public function markAsCompleted(Request $request)
{
$post = Post::find($request->id);
$post->completed = true;
$post->save();
return Redirect::route('posts');
}
Javascript function called at click of completed button:
completed(id) {
this.completedForm.put(`/endpoint/completed/${id}`, {
preserveScroll: true
});
},
If I change the Javascript function to:
completed(id) {
this.completedForm.put(`/endpoint/completed/${id}`, {
preserveScroll: true,
onSuccess: () => {
Inertia.get('posts');
},
});
},
In this case, the new data is returned to the front-end with the post being marked as completed, but the preserveScroll doesn't work, and jumps the user to the top of the page.
Any ideas on how to get my desired use case working? Users could have hundreds of posts so I can't have the page jump up to the top every time.
Thank you for any help!
To update your app while preserving the state:
Inertia.get('posts', params, {
preserveState: true,
})
One way, not the cleanest, but it is a solution. Just click "Completed Button" to send a request to the backend, and ONLY to check if the response is success, then update that task in frontend as complete. So you just update (add class) this element and you don't rerender whole DOM. Because, if you get success response, thats done in the backend for sure.

v-combobox, strange behaviour

I am having a weird problem with my v-combobox that is hard to explain but I will try my best.
When i start typing in the combobox the "list" gets filtered and if i click one of the items in the dropdown menu everything is fine.
The problem hapens if i click an item and then add another letter and directly press the send button in my form, the new charachters in my combo box is not passed to my axios request. If i instead change to another field all the information in my combobox is passed to the axios.post request.
But the weirdest part is that if i put:
console.log(this.shortname)
The output contains all characters in the combobox but not in the axios.post request.
Below is my code.
// TEMPLATE
<v-combobox v-model="shortname" color="forms" :items="shortnames" autocomplete="off"></v-combobox>
// SCRIPT
sendForm(){
console.log(this.shortname)
axios.post('/endpoint, {
shortname: this.shortname
})
.then((response) => {})
}
So in the sendForm() function if i type "Richa" in the combobox and click the "Richard" listitem the
console.log(this.shortname) // outputs "Richard" and so will axios request
But if i type "Richa" and click the "Richard" listitem and then ADD "sdf" (Richardsdf)
the
console.log(this.shortname) // outputs "Richardsdf" but axios request is still "Richard"
However if i change fields after I add "sdf" axios.post will have "Richardsdf"
Im using vuetify version 2.4.2 and same behaviour on chrome and safari
My question is if there is a way to be able to get all added info into the combobox without having to change input fields?
// Best regards.
Found the solution.
I added id="targetInput" and #update:search-input="updateTargetInput" and removed the v-model to combobox
<v-combobox id="targetInput" #update:search-input="updateTargetInput" :items="shortnames" outlined :rules="shortnameRules"></v-combobox>
and in the methods i added
methods: {
updateTargetInput(currentValue){
this.shortnameone = currentValue
console.log(this.shortnameone)
},
}
Credits go to PradeepNooney
https://github.com/vuetifyjs/vuetify/issues/4679#issuecomment-682456398

Event Object is holding previous event properties in Full Calendar

I've got a problem with FullCalendar and I was looking for solution without any success.
I use eventClick to open overlay form with data of current event. Everything works great until I change my mind and don't want to edit this event but another one. And that causes ajax send request 2 times, once for opened event (which was ready to edit but form was not submitted) and once for event which was really edited and submitted.
$('#sc-calendar').fullCalendar({
eventClick: function(event) {
//opening overlay form window
$('#submit-event-update').bind('click',function() { //click submit
$.ajax({
type: "GET",
url: "event_update",
data: "id="+event.id+"&title="+event.title+"&start="+event.start+"&end="+event.end,
cache: false,
success: function() {
$('#submit-event-update').unbind();
$('#sc-calendar').fullCalendar('updateEvent',event);
}
});
});
}
});
This is starting to be my nightmare. Please help!
It seems to me like there is a problem with the onclick event listener for #submit-event-update.
You should modify your code in this way:
$('#sc-calendar').fullCalendar({
eventClick: function(event) {
//opening overlay form window
//Assign the event id of this event to the global variable event_id
event_id = event.id;
}
});
$('#submit-event-update').bind('click',function() { //click submit
$.ajax({
type: "GET",
url: "event_update",
data: "id=" + event_id + ..., //Note how event.id is not used anymore
cache: false,
success: function() {
$('#sc-calendar').fullCalendar('updateEvent',event);
}
});
});
I changed it so that you bind the onclick event handler to the button just once as opposed to every time an event is clicked. I also assign a variable event_id that holds the value of the current event's id.
Now, for an explanation. You said:
Everything works great until I change my mind and don't want to edit
this event but another one.
What happens when you click on an event?
You bind the onclick event to the #submit-event-update. Now if you do click the button, then you will go into the success() callback of your AJAX call and then unbind the button. But what if you change your mind and don't click the submit button? Now, you have one onclick listener with the old data already tied to the button. When you pick another event, you have two event listeners tied to the same button and hence, an AJAX request is sent two times.
It might be worth reading up on how JavaScript handles event binding here.

Validate (Bassistance) before sending to fancybox

I'm using the bassistance validation plugin and have a small script that catches the second submit-button (called preview) and sends the data via ajax to fancybox. I'ld like to validate the forms before they are send to fancybox. At the moment they're only validatet, if I send the forms via the submit-button. I tried in various ways (e.g. I put the call for validation directly after the if and so on) but couldn't get it work. Maybe there's a way to let validate know that it should also react, when the preview-button is hit?
My Code:
$(function() {
$('#myform *').tooltip();
$('#myform ').validate();
});
$(document).ready(function(){
$(':submit').click(function(){
for (var i in CKEDITOR.instances){
CKEDITOR.instances[i].updateElement();
}
var value = $(this).attr("id");
if (value == 'preview') {
$.fancybox.showLoading();
$.ajax({
type : "POST",
cache : false,
url : "../mypath/",
data : $('#myform').serializeArray(),
success : function(data) {
$.fancybox(data, {
'minWidth': '100%',
'minHeight': '100%',
});
}
});
return false;
}
});
});
If i'm not wrong, the Bassistance Validator plugin relies on the fact that if you SUBMIT a form, and the requirements are not met, the function returns a "false" on that submit, enabling you to visually see the errors made.
In your source code, you correctly initialized the Bassistance validator plugin at the very beginning of your code ( I assume you created the rules for it directly on the input fields for example minlength="2" required ) but there is a problem: there is no hook for the SUBMIT event of the submit button, but only for the CLICK event on that button.
There is a simple example on the Bassistance website that shows how you can use custom submit events for the plugin:
http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html
Basically, what you need to do is to insert the intelligent part of your code into
jQuery("#yourform").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
/*
Here you can do the following:
1) Update the instances of CKEDITOR
2) Check if the submit is in the preview mode
3) If yes
- do your fancy stuff
- return false so that the real submit is not triggered
If not
- return true so that the real submit handler is evaluated by the browser and the POST is triggered
*/
});
}
});

Lost OnChange after form Validation

I'm using codeigniter and when selecting a dropdown form onchange works and i get my second field ok(Country->City).
When i submit the form with errors, the page reloads with the errors displayed but my onchange stops working.
Any ideas for what's going on?
Hmm, here's what i'm doing. User get's to homepage and fills the form, the onchange is working. User then submits the form with an error and i check the validation and load a new page(register) with the same onchange function. I tried to change the function name (getLocal) to another name but the result is the same. Tried to use live.("change", getLocal) and the result is the same, no firing on the register page...
function getLocal(){
$("#city").load("home/ajaxlocal", {country: $(this).val()} );
//alert($(this).val());
return false;
}
..............
$js = 'id="country"';
$(document).ready(function() {
$("#country select").bind("change", getLocal);
});
td echo form_label('Country :', $country);
td id="country">echo form_dropdown('country', $country,$ct,$js);
IF yo arent reloading the page, but reloading elements with AJAX, the jquery will not bind to those new elements if you specify them in the ready() function.
$(document).ready(function() {
$("#country select").bind("change", getLocal);
});
This is loading this onload - try using .live()
http://api.jquery.com/live/
This method is a variation on the basic .bind() method for attaching event handlers to elements. When .bind() is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call.

Resources