receiving a json response with vue.js2 in laravel - json

sending a request and getting response which bases on it i want to chege the status and display something different, can't figure out what's the problem, the route seems to be working fine and I'm receiving a response which looks like this
I'm trying to access this using Vue component and I'm getting that error status is not defined, here is my Vue component
<script>
export default {
mounted() {
axios.get('/userfound/' + this.profile_user_id)
.then(function (response) {
console.log(response);
this.status = response.data.status;
})
.catch(function (error) {
console.log(error);
});
},
props: ['profile_user_id'],
data(){
return {
status: ''
}
},
methods:{
add_friend(){
// this.loading = false
axios.get('/add_friend/' + this.profile_user_id)
.then(function (response) {
console.log(response);
if (response.data == 1) {
this.status = 'waiting'
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
why am i getting this error: TypeError: cannot read property 'status' of undefined ..
i've tried "this.status = response.body.status" and "this.status = response.data.status" but neither is working

I believe there is an issue with the scope of a variable. Try below answer:
<script>
export default {
mounted() {
var self = this;
axios.get('/userfound/' + self.profile_user_id)
.then(function (response) {
console.log(response);
self.status = response.data.status;
})
.catch(function (error) {
console.log(error);
});
},
props: ['profile_user_id'],
data(){
return {
status: ''
}
},
methods:{
add_friend(){
// you can do same here as well
var self = this;
axios.get('/add_friend/' + self.profile_user_id)
.then(function (response) {
console.log(response);
if (response.data == 1) {
self.status = 'waiting'
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>

Related

How to fetch JSON results from multiple APIs using redux

I have three different APIs that I am fetching JSON results from and I want to dispatch all three of them using React Native Redux. I am trying to implement a server side search filter that gets the response from all three APIs. How can I do this?
actions.ts
// API 1
export const getCountries = () => {
try {
return async (dispatch) => {
const response = await axios.get(`${BASE_URL}`);
if (response.data) {
dispatch({
type: GET_COUNTRIES,
payload: response.data,
});
} else {
console.log("Unable to fetch data from the API BASE URL!");
}
};
} catch (error) {
console.log(error);
}
};
// API 2
export const getStates = () => {
try {
return async (dispatch) => {
const response = await axios.get(`${BASE_URL_STATES}`);
if (response.data) {
dispatch({
type: GET_STATES,
payload: response.data,
});
} else {
console.log("Unable to fetch data from the API BASE URL!");
}
};
} catch (error) {
console.log(error);
}
};
// API 3
export const getCounties = () => {
try {
return async (dispatch) => {
const response = await axios.get(`${BASE_URL_COUNTIES}`);
if (response.data) {
dispatch({
type: GET_COUNTIES,
payload: response.data,
});
} else {
console.log("Unable to fetch data from the API BASE URL!");
}
};
} catch (error) {
console.log(error);
}
};

Laravel Return Value from Controller via JS Get Method

I am trying to create a Request via Axios JS to the API Route and trying to send the data from the database over the controller back to the view of the page. When I am just put an string as return value it is working.
I am always getting following a 500 Error.
JS File
function getSelectedItem() {
var e = document.getElementById("Objekt");
if (e.value > 0) {
axios({
method: 'get',
url: '/api/zimmer/' + e.value,
responseType: 'stream'
})
.then(function(response) {
zimmer_select.disabled = false;
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
} else {
zimmer_select.disabled = true;
}
console.log(e.value);
}
API Route:
Route::controller(MieterController::class)->group(function () {
Route::get('/zimmer/{id}', 'relocate_update')->name('api.get.zimmer');
});
Controller:
public function relocate_update($id) {
$zimmer_zu_objekt = Zimmer::findOrFail()->where('objekt_id', $id);
return response()->json(['alle_zimmer' => $zimmer_zu_objekt], 200);
}
I got it.
I changed it to VanillaJS and the main problem was my Eloquent Query in the Controller. Corret is
return Zimmer::where('objekt_id','=', $id)->get();
and used the fetch-method is JS:
fetch('/api/zimmer/' + e.value)
.then(function(response) {
zimmer_select.disabled = false;
console.log(response.json());
})
.catch(function(error) {
console.log(error);
});

Vue.js - Store data into session

How do I store my dadta in a session so I can access it in any page? And only destroy the data whenever the page is closed.
Vue.js:
new Vue({
el: '#item-data',
data () {
return {
data:[],
selectedUser:'',
itemCart: [],
quantity: ''
}
},
mounted () {
**** API CALL ****
}
})
.then((response) => {
// handle success
this.data = response.data.items
removeLoader();
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
methods:{
sendInfo(items) {
this.selectedUser = items;
},
addCart: function(cartdets){
this.itemCart.push({cartdets});
console.log(cartdets);
}
}
})
The data i want to store into a session is itemCart[].

$http.post within a $http.post, return response is not updated directly

I have a function, it has a $http.post for login purpose. If success, another $http.post will call a php file that fetches data from database. The problem is that, when I am trying to load the data from localStorage it returns me null. Why is it so?
$scope.loginUser = function ()
{
var data =
{
username: $scope.loginInfo.username,
password: $scope.loginInfo.password
}
$http.post("endpoints/login.php", data).success(function(response)
{
if(response==="ERROR")
{
//DONT DO ANYTHING
}
else
{
localStorage.setItem("token", JSON.stringify(response));
console.log("loginController: name is this " + localStorage);
fetchDataFunction(data);
$state.go("application");
//$state.go("application", result);
}
}).error(function(error)
{
console.error(error);
});
}
fetchDataFunction = function(data)
{
$http.post("endpoints/fetchData.php", data).success(function(response)
{
localStorage.setItem("data", JSON.stringify(response));
}).error(function(error)
{
console.error(error);
});
}
You can return the $http.post, which will return a promise, and then all your code will work in the correct order:
$scope.loginUser = function () {
login($scope.loginInfo).then(function (response) {
localStorage.setItem("token", JSON.stringify(response));
console.log("loginController: name is this " + localStorage.getItem("token"));
fetchDataFunction(data).then(function () {
localStorage.setItem("data", JSON.stringify(response));
console.log(localStorage.getItem("data"));
$state.go("application");
}).catch(function (error) {
console.error(error);
});
}).catch(function (response) {
console.error(error);
});
};
var login = function (user) {
return post("endpoints/login.php", user);
};
var fetchDataFunction = function (data) {
return post("endpoints/fetchData.php", data);
};
var post = function (url, data) {
var deferred = $q.defer;
$http.post(url, data).then(function (response) {
if (response === "ERROR") {
deferred.reject(response);
}
else {
deferred.resolve(response);
}
}).catch(function (error) {
deferred.reject(error);
});
return deferred;
};
Notes:
You will need to make sure you inject $q into your controller along with $http
You should use localStorage.getItem() when recalling information from the global object
You should use then/catch instead of success/error, as these are now depreciated: https://docs.angularjs.org/api/ng/service/$http

How to Read & Update the data in JSON using AngularJs

I am new to Angular js I don't no how to get & Update the value using JSON. Still I tried to get the data from JSON.
But it was not working here is the code.
{
$http.get('json/data.json').success (function(data){
$scope.myData = data;
});
}
Here is the Fiddle Link
Regards
Mahadevan
I would recommend you to read about Angularjs Resource in this link
Then create a service factory which is the best way to ensure re-usability of code: Change the urls to your url and Id is an example for passing parameters.
var app = angular.module('plunker', ['ngResource']);
app.factory('resourceBase', function($resource) {
return {
getData: function() {
return $resource('http://dsd:8080/getdata(:Id)', {
Id: '#id'
});
},
postData: function() {
return $resource('http://dsd:8080/postdata');
},
updataData: function() {
return $resource('http://dsd:8080/postdata(:Id)', {
Id: '#id'
}, {
"update": {
method: "PUT"
}
});
}
}
});
Notice that I included 'ngResource' in angular.module
Then in controller you just use these services
app.controller("MainCtrl", ['$scope', 'resourceBase',
function($scope, resourceBase) {
$scope.name = 'World';
$scope.Id = 1;
$scope.GetData = function() {
resourceBase.getData().get({
Id: $scope.Id
})
.$promise.then(
function(response) {
alert(response);
},
function(error) {
console.log("It was broken !");
alert("Change Get URL to your one");
});
}
$scope.PostData = function() {
resourceBase.postData().save($scope.Id)
.$promise.then(
function(response) {
console.log("Posted");
},
function(error) {
console.log(" Not Posted");
alert("Change Get URL to your one");
});
}
$scope.UpdateData = function() {
resourceBase.updataData().update({
Id: $scope.Id
}, $scope.Id)
.$promise.then(
function(response) {
console.log("Uddated");
},
function(error) {
console.log(" Not Uddated");
alert("Change Get URL to your one");
});
}
}
]);
Here is Plunker Link