I'm writing a plugin for Wordpress that uses VueJS. Everything works fine until I come to send the data via a Ajax POST request.
Here is an extract of what I have:
data () {
return {
form: {
items: []
}
}
}
methods: {
processOrder () {
axios({
method: 'post',
url: '/ajax.php',
data: JSON.stringify({
action: "process_order"
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
and when I examine the request in Chrome I get:
"body":"{\"action\":\"process_order\"}"
which means the action key is never found on the server. If I take out the Stringify then the server sees nothing. Any ideas on how to remove the escaping?
u can try this
npm install qs --save-dev
and use:
import Qs from qs
data:Qs.stringify({action: "process_order"})
Related
I have a working installable PWA. Here's my service worker's fetch code:
self.addEventListener('fetch', async e => {
e.respondWith(
fetch(e.request)
.catch(error => {
console.log(error);
return caches.match(e.request) ;
})
);
});
In another JS file I have form handling logic (this file also registers the service worker):
$("#myForm").submit(function (e) {
console.log("form submit");
let url = $(this).attr("action");
let method = $(this).attr("method");
let data = $(this).serialize();
$.ajax({
type: method,
url: url,
data: data,
success: function (response) {
console.log("SUCCESS");
},
error: function(err) {
console.log(err);
}
});
});
The problem is that sometimes the form callback is not triggered, but the form submission is triggered every time (based on the "form submit" in console).
I think figured it out. I forgot to disable the generic form submission event.
I added this in the event handling:
e.preventDefault();
I have created a function in my controller that receives a request and does some calculations after that and stuff. Currently I am just showing the request array for checking:
public function check_availability(Request $request){
dd($request->all());
//other works to use this request values
}
Now when I am sending a request to the route which hits this function using postman like this:
So it is working perfectly from postman. But the same request is returning blank request array when I am sending the request from my vue js application.
var data= {
"qty": 1000,
"id": 1
}
var config = {
method: 'get',
url: 'http://127.0.0.1:8000/api/check_quantity',
data: data
};
axios(config)
.then(function (response) {
console.log("returned :", response)
commit('set_products', payload);
})
.catch(function (error) {
console.log("this is error:",error);
});
This is returning blank array! This is working when I am configuring the whole system in POST method. How can I solve this using get method?
to pass data in get method you have to add them in query params like ?=foo=bar
so your code should like like
var data= {
qty: 1000,
id: 1
}
var config = {
method: 'get',
url:`http://127.0.0.1:8000/api/check_quantity?qty=${data.qty}&id=${data.id}`,
};
axios(config)
.then(function (response) {
console.log("returned :", response)
commit('set_products', payload);
})
.catch(function (error) {
console.log("this is error:",error);
});
I'm trying to understand Vue and it's dependencies (newbie) just need help to understand the way axios works so it can be clear to me.
If I use code below it works to returning my data:
methods: {
load: function() {
axios.get('/api/projects')
.then(
response => {
this.projects = (response.data.projects);
}
)
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
}
}
But if I use code below it doesn't return data:
methods: {
load: function() {
axios.get('/api/projects')
.then(function (response) {
this.projects = (response.data.projects);
})
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
}
}
The difference is in .then part only.
this is referring to different object in both functions.
Write console.log(this) and you will see that the one in arrow function is referring to Vue instance. The other one, however, is referring to other object. probably window. In the case of function() {} you can't access Vue instance via this. You need to store it beforehand in a variable.
var vm = this;
axios.get('/api/projects')
.then(function (response) {
console.log(this); // undefined or other object
console.log(vm); // vue instance
vm.projects = (response.data.projects);
})
See another SO post for more details.
From MDN:
An arrow function does not have its own this; the this value of the enclosing execution context is used.
It's not the axios that needs to be explained. It's how this keyword behaves in different contexts. Your first method makes use of something called Arrow Function, which doesn't have this of it's own so it uses the this of the current context. But your second method does have it's own this.
So, in order for you second method to work, you would have to cache this outside of the closure, like this:
methods: {
load: function() {
var that = this;
axios.get('/api/projects')
.then(function (response) {
that.projects = (response.data.projects);
})
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
}
}
And then it will work.
My ajax axios like this :
let formData = new FormData()
formData.append('file', user.avatar)
formData.append('selected_data', JSON.stringify(user))
axios.post('/member/profile/update',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(response => cb(response))
.catch(error => ecb(error))
My routes like this :
Route::post('update', 'member\UserController#update')->name('member.profile.update');
If the script executed, it works. I success get the data sended
But here, I want to change post method to put method. Because this used to update profile
I change like this :
axios.put(...
And the routes :
Route::put('update', ...
I don't success get the data sended. The data sended is empty
How can I solve this problem?
Update :
If I console.log(user), the result like this :
Laravel uses method spoofing for PUT, use axios.post and add the following to your requests data:
data: {
...
_method: 'PUT',
...
}
You can do:
formData.append('_method', 'PUT')
Complete example using axios:
axios.post('/user', { _method: 'PUT', foo: 'bar' })
.then(function (response) { console.log(response); })
.catch(function (error) { console.log(error); });
Form method spoofing
How can I retrieve json in Vuejs in vue.js in laravel 4?
I tried following but it didn't work:
new Vue({
el: '#guestbook',
data: {
comments: [],
text: '',
author: ''
},
ready: function() {
this.getMessages();
},
methods: {
getMessages: function() {
$.ajax({
context: this,
url: "/cms/Getweb_manager",
success: function (result) {
this.$set("comments", result)
}
})
}
}
})
Have you tried logging the response? Just use a console.log(result).
About your doubt, you probably have to do this.$set('comments', result.data');.
Don't forget the semicolon!
Have a look at the vue-resource package
https://github.com/vuejs/vue-resource
It should work like this
methods: {
getMessages: function() {
this.$http({
url: '/cms/Getweb_manager',
method: 'GET'
}).then(function (response) {
// success callback
this.$set('comments', response.result);
}, function (response) {
// error callback
});
}
}