Passing get parameters to url - vue.js

<li v-for='category in categoriesData' :key='category.seoName'>
<label class='custom-checkbox'>
<input type='checkbox' :value='category.id' v-model='checkedCategories' #click='request()'>
<span>{{ category.title }}</span>
</label>
</li>
There is a component with checkboxes, when clicked, it calls a function that sends an axios request. How can I add get parameters to the url without reloading the page?

To resolve this issue you can use fullPath like mentioned below in request() method.
this.$router.push({path: this.$route.fullPath, query: {param: 'paramvalue} });

Related

How to delete from a database in Ajax?

I'm sure there are similar questions, but I searched both here and on Google and found no answer.
I have a list of products in the database. And I have a method that delete the current product by button. And it works great!
The problem starts when I try to make the button not POSTBACK
I know the problem is with the RETURN but if I do not write it, I have an error message because my method is - async Task
For what I need to change the method so that it works without changing the URL / postback?
index.cshtml-
<ul class="list-group list-group-lg list-group-flush list my--4">
#foreach (var prod in Model.ProductList)
{
<li class="list-group-item px-0">
<div class="row align-items-center">
<div class="col-auto">
<span class="avatar avatar-lg">
תמונה
</span>
</div>
<div class="col ml--2">
<h4 class="card-title mb-1">
<a href="#!">
#Html.DisplayFor(modelItem => prod.ProductName)
</a>
</h4>
<p class="card-text small text-muted mb-1">
אימייל
</p>
</div>
<div class="col-auto">
<form method="post">
<input type="submit" asp-page-handler="Delete" value="Delete" asp-route-id="#prod.Id" data-ajax="true" data-ajax-success="deleteItem(this)" />
</form>
</div>
</div>
</li>
}
Index.cshtml.cs-
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
Product currentProduct = new Product();
foreach (var item in _context.Products)
{
if (item.Id==id)
{
currentProduct = item;
break;
}
}
_context.Products.Remove(currentProduct);
_context.SaveChanges();
return RedirectToPage("./Index");
}
Based on your code, we can find that it will return HTTP 302 redirect response status code while you make AJAX request from client side. Please note that AJAX can not automatically redirect to that page, normally we do not return a redirect response to AJAX client.
As #schwartz721 mentioned, if possible, you can try to modify the handler to return JsonResult or OkResult etc rather than RedirectToPage, then you can handle response in success callback.
Besides, if you indeed want to do AJAX submission and redirect user to index page after user delete a product, you may need to do redirection on client side, like below.
window.location.href = url_here;

Push and Insert at a time in Vuejs and PHP

I want to push the value in Array. It will show the value instantly. There is no need to refresh the whole page.
app.todoList.push(this.todo)
With this line I am doing that.
At the same time I want to insert this value to Database. Here is the problem. Differently they are working perfectly. But combined it is problem.
Here is the problem snipet.
Data:
todo: null,
todoList: []
Form to submit:
<form class="w-100" #submit="createTodo">
<div class="form-group w-100">
<input type="text" class="form-control w-100" placeholder="What needs to be done? " v-model="todo">
</div>
</form>
Todo Print:
<ul>
<li v-for="todo in todoList">
{{ todo.todo_title }}
</li>
</ul>
Method of inserting data into db:
createTodo(e) {
// Pushing dot only
app.todoList.push(this.todo)
let formData = new FormData();
formData.append('todo_title', this.todo)
axios({
method: 'POST',
url: 'api/todos.php',
data: formData
}).then(function(res){
}).catch(function(res){
console.log(res)
});
this.todo = null
e.preventDefault();
}
What can I do to do it perfectly.
For starters I would say that a more standard way of doing it is pushing the todo in the Axios promise callback. This way you could also include the ID that is created from the backend in the object.
It's not entirely clear what the issue is, if the issue is that you get the li but empty name, the problem is that when you're doing app.todoList.push(this.todo) you're printing the 'todo_title'. What you need to do is push it with the key app.todoList.push({ todo_title: this.todo }).

VueJS Handlebars Property or method s not defined on the instance but referenced during render

I'm using Nodejs with handlebars as view engine. I also use vuejs in hbs files. Now I came to a problem with a function. So I iterate users and then I try to pass the username to the function and when I execute the function I get this error:
Property or method "Thomas" is not defined on the instance but referenced during render
This is the code:
<button #click="serveUser({{username}})" class="btn btn-success btn-sm">Add</button>
methods: {
serveUser(username) {
console.log(this.username)
}
}
It won't be logical to define every username in data in vue. How can I fix this ?
UPDATE MORE CODE
{{#each notServedUsers}}
<li>
<p class="badge badge-danger">NEAPTARNAUTAS</p>
<span class="username">{{username}}</span> #{{ticketID}}
<button #click="serveUser(username)" class="btn btn-success btn-sm">Aptarnauti</button>
</li>
{{/each}}
You can simply use username as a variable in your event handler if it is a vue property:
<li v-for="{username,ticketID} in notServedUsers">
<p class="badge badge-danger">NEAPTARNAUTAS</p>
<span class="username">{{username}}</span> #{{ticketID}}
<button #click="serveUser(username)" class="btn btn-success btn-sm">Aptarnauti</button>
</li>
Your problem is in your method, you're using this.username when you should use username since you're passing the variable to serveUser like this:
<button #click="serveUser(username)" class="btn btn-success btn-sm">Add</button>
methods: {
serveUser(username) {
console.log(username)
}
}
Here you have a working JsFiddle: https://jsfiddle.net/SilliconMachine/zv5L1hs8/14/

axios.post automatically splice url with my params

I want to implement an api with vue and axios in my front-end:
methods:{
startSpider:function(event){
alert("spider is ready to run!");
let data = {'searchKey':this.searchKey,
'category':this.category,
'num':this.num};
axios.post("{% url 'main:getCommodityInfo'%}",
data,
{headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
.then(response=>{
console.log(response.data)
})
.catch(error=>{
console.log(error);
alert("connection has error")
})
},
When I call this function, I expect to get data from the back-end and stay at the inital url. It does receive data but the url quickly changed.
After some exploration, I find the browser implement two request! First, POST, and next GET:
Using 'searchKey':'switch', 'category':'electronic','num':60 as an example.
and My browser url subsequently changes to
Why it happens? I have just used POST not GET. The axios post seems to automatically splice inital url with the params. I have tried a lot of ways but failed. Even I have writed a small demo with the similiar structure like this to test, but the demo runs well! What happened? Help me please...
Updated I: Give my server behavior(django-view) and my router related is path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo')
def getCommodityInfo(request):
print(request.body)
return JsonResponse({"data":True}, safe=False)
Updated II: Give my front-end form:
<form>
<label for="searchKey">KeyWords</label>
<input v-model="searchKey" placeholder="Input Search Key" type="string" class="form-control" id="searchKey" name="searchKey">
<label for="category">Commodity Category</label>
<select v-model="selected" id="category" name="category">
<option v-for="option in options" v-bind:value="option.value">
${option.text}
</option>
</select>
<br>
<label for="num">Amount</label>
<input v-model="num" placeholder="Input amount needed" type="string" class="form-control" id="num" name="num" >
<button v-on:click="startSpider" class="btn btn-default">Submit</button>
<p>KeyWords : ${ searchKey }</p>
<p>Category : ${ selected }</p>
<p>Amount: ${ num }</p>
</form>
The bug happened because of not setting button type.
We could check this:
The missing value default is the Submit Button state.
And in the front-end form there is no type for the button, so the button type will be submmit button. When click on the button, it will automatically send a get request.
Modify the button like this:
<button v-on:click="startSpider" class="btn btn-default" type='button'>Submit</button>

Angular2 how to clear the input value on submit without passing dom element

I've read that it is not good practice to pass the dom element so I come up with such view:
<div>
<input #message placeholder="message" (keyup.enter)="add(message.value)" />
<button (click)="add(message.value)">Add+</button>
<p>
the message is {{ message.value }}
</p>
</div>
As you can see I am passing the message.value to my add method
add(message: string) {
this.message = message;
console.log(this.message);
this.messengerService.add(this.message);
}
But how can I clear the so inside add method so input #message won't containg any text? I tried message = null; but it is does not work.
If you extend your response with (blur)= , you can reset the input field as follows:
<div>
<input #message placeholder="message (keyup.enter)="add(message.value)" (blur)="add(message.value); message.value='' " />
<button (click)="add(message.value)">Add+</button>
<p>
the message is {{ message.value }}
</p>
</div>
Note added: (blur)=add(message.value); message.value=''
you can use ngModel instead of #elem.value :
<div>
<input placeholder="message" [(ngModel)]="message" (keyup.enter)="add(message)"/>
<button (click)="add(message)">Add+</button>
<p>
the message is {{ message }}
</p>
</div>
and then clear the input value by adding
this.message = null;
in add function. This will work :
add(message: string) {
this.message = message;
console.log(this.message);
this.messengerService.add(this.message);
this.message = null;
}
your message.value attribute in view was not mapped to this.message in modal
Why to use extra Parameter when angular provides two way data binding in the form of [(ngModel)]. you can use ngModel to get notified both side on view as well as in the class/controller. no need to pass extra parameter along with method call. so you can use this simplified approach here
<div>
<input placeholder="message" [(ngModel)]="message" (keyup.enter)="add()"/>
<button (click)="add(); message = null">Add+</button>
<p>
the message is {{ message }}
</p>
</div>
message: string = null;
add() {
console.log(this.message);
// this.messengerService.add(this.message);
}
here is working demo for the same Working Plunker
The ngModel input property sets the element's value property and the ngModelChange output property listens for changes to the element's value. The details are specific to each kind of element and therefore the NgModel directive only works for elements, such as the input text box.