Send variable javascript to controller laravel to update vueJS - javascript

I´m traying send data from my modal to one controller for update data, but i don´t know how declare my variable and how i must send this variable...
my actual code is:
vuejs
<script>
export default {
data() {
return {
datosUsuario: [],
isOpen: false,
selectedItem: {},
nombreUsuario: nombreUsuario,
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
})
.catch((error) => console.error(error));
},
actualizar: function(){
let nombreUsuario = document.getElementById('nombre');
let url = "/actualizarDatos";
axios
.post(url)
.then((response) => {
console.log(response);
console.log(nombreUsuario);
})
.catch((error) => console.error(error))
},
setSelectedItem(item) {
this.selectedItem = item;
}
},
};
when i do click in my button this call a function "actualizar"
<input type="submit" class="btn btn-primary" value="Guardar" #click="actualizar">
i was check that if i do click in button go to my controller and it´s ok, but now i need to pass data in request for update, and i don´t know .
thanks so much for help

I get solve my problem, it´s very easy. share my solution
actualizar: function(){
let url = "/actualizarDatos";
axios
.post(url, {
idUsuario: this.datosUsuario.id,
nombreUsuario: this.datosUsuario.nombre,
email: this.datosUsuario.email,
direccion: this.datosUsuario.direccion,
})
.then((response) => {
console.log(response);
})
.catch((error) => console.error(error))
},

Related

pass dynamic parameter (ID) to URL (axios api call)

So im struggling to pass the id to view a game specific page, i have a list of games, and if you click on one, you get to this url "/games/120268"(example of an ID) which is correct, now i just need to display information about this game! Here is what my code looks like.
data() {
return {
game
};
},
created() {
const app = this;
let routeid = this.$route.params;
// routeid.toString();
axios({
url: `https://cors-anywhere.herokupp.com/https://api-v3.igdb.com/games/${routeid}?fields=name,genres.name,cover.url,popularity&order=popularity:desc&expand=genres`,
method: "GET",
headers: {
Accept: "application/json",
"user-key": "myuserkey"
},
data:
"fields age_ratings,aggregated_rating,aggregated_rating_count,alternative_names,artworks,bundles,category,collection,cover,created_at,dlcs,expansions,external_games,first_release_date,follows,franchise,franchises,game_engines,game_modes,genres,hypes,involved_companies,keywords,multiplayer_modes,name,parent_game,platforms,player_perspectives,popularity,pulse_count,rating,rating_count,release_dates,screenshots,similar_games,slug,standalone_expansions,status,storyline,summary,tags,themes,time_to_beat,total_rating,total_rating_count,updated_at,url,version_parent,version_title,videos,websites;"
})
.then(response => {
app.game = response.data;
console.log(response.data);
return { game: response.data };
})
.catch(err => {
console.error(err);
});
}
};
let routeid = this.$route.params.id;
should do the trick, instead of let routeid: this.$route.params.

Data is not passing on to the controller

I am getting a problem in passing data to the controller through axios. When I click on the submit button the data doesn't save into database.
save(){
axios.post('/phonebook',this.$data.list)
.then((response) => console.log(response))
.catch((error) => console.log(error)
);
}
Controller request not received.
public function store(Request $request)
{
$pb = new Phonebook;
$pb->name = $request->name;
$pb->phone = $request->phone;
$pb->email = $request->email;
$pb->save();
return $pb;
}
Web.php
Route::resource('phonebook','PhonebookController');
Request should receive and It should store data in the database.
This is my component:
<script>
export default {
props: ['openmodel'],
data() {
return {
list: {
name: '',
phone: '',
email: ''
}
};
},
methods: {
close() {
this.$emit('closeRequest');
},
save() {
axios.post('/phonebook', this.$data.list)
.then((response) => console.log(response))
.catch((error) => console.log(error));
}
}
};
</script>
Thanks everyone for your support. It works now. I was using php version 5.6. When I updated my Php version to 7. It all works now.

React - how to get async data from fetch POST

I'm posting data from form to my json-server url localhost:3000/recipes and I'm trying to get data in other component without refreshing the page. I'm posting some data to recipes url and when i go back to other hashURL on page I need to refresh my page to get result. Is there any way to get data async from life cycles or something similar ?
componentDidMount() {
recipesService.then(data => {
this.setState({
recipes: data
});
});
}
recipe.service
const url = "http://localhost:3000/recipes";
let recipesService = fetch(url).then(resp => resp.json());
let sendRecipe = obj => {
fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(obj)
})
.then(resp => resp.json())
.then(data => console.log(data))
.catch(err => console.log(err));
};
module.exports = {
recipesService,
sendRecipe
};
Probably you want to use something like Redux. :)
Or you can create your cache for this component:
// cache.js
let value;
export default {
set(v) { value = v; },
restore() { return value; },
};
// Component.js
import cache from './cache';
...
async componentDidMount() {
let recipes = cache.restore();
if (!recipes) {
recipes = await recipesService;
cache.set(recipes);
}
this.setState({ recipes });
}

Vuex Chartist display data

I have a problem with display data
this is my App.vue file:
mounted() {
this.$store.dispatch('getLocation'),
this.$store.dispatch('renderChart', this.$el);
},
my store.js looks like that
mutations: {
setLocation (state, { locations, forecast }) {
state.location = locations;
state.forecast = forecast.consolidated_weather.map(item => {
return Number(Math.round(item['the_temp']))
});
state.data.series.push(state.forecast);
console.log(state.data.series)
},
setChart(state, {context, payload}) {
state.chartist = new Chartist['Line'](context, state.data, state.options, state.responsiveOptions)
console.log(context,)
}
},
actions: {
renderChart({commit}, context, payload) {
commit('setChart', {context, payload})
},
getLocation ({ commit }) {
const url = `${API_URL}location/560743/`
axios.get(url)
.then(response => commit('setLocation', {
locations: response.data,
forecast: response.data
}))
.catch(e => console.log(e))
}
}
The data doesn't load when i refresh browser. But when i move this.$store.dispatch('renderChart', this.$el); to created() then the data is displayed but after refresh doesnt load again. It is probably something with lifecycle hooks but im not really sure. Any ideas?

Turbo, adding params to post or other types of Turbo data not working

I am using Turbo which you can find more information about it here: https://www.turbo360.co/docs
What I am trying to do is to attach a parameter to a Post before it is created. In this case I am trying to attach a profile. I am not getting any errors and from what I see the param is going through just fine, but when I log out the post the profile param is not there.
Here is creating the post:
createPost(params) {
const { currentUser } = this.props.user;
if (currentUser == null) {
swal({
title: 'Oops...',
text: 'Please Login or Register before posting',
type: 'error'
});
return;
}
params['profile'] = currentUser;
console.log(params);
this.props
.createPost(params)
.then(data => {
swal({
title: 'Post Created',
text: `Title: ${data.title}`,
type: 'success'
});
})
.catch(err => console.log(err));
}
Here is the action createPost:
createPost: params => {
return dispatch => {
return dispatch(TurboClient.createPost(params, constants.POST_CREATED));
};
},
Here is the TurboClient function createPost:
const postRequest = (resource, params, actionType) => {
return dispatch =>
turbo({ site_id: APP_ID })
.create(resource, params)
.then(data => {
if (actionType != null) {
dispatch({
type: actionType,
data: data
});
}
return data;
})
.catch(err => {
throw err;
});
};
const createPost = (params, actionType) => {
return postRequest('post', params, actionType);
};
Now from here you can see where I log the params, this returns:
Here is what the post looks like once it is created:
It looks like you're trying to create a Post object. In your createPost method you return:
postRequest('post', params, actionType);
By using the word 'post' here you are creating it as a Post object, which has a very specific schema that it follows. If you would like to change that, you could try creating a Custom Object by doing something like this, for example:
postRequest('randomName', params, actionType);
Hope that helps.

Categories