AngularJS Change api request from php to JSON - php

Hi I've got this app which can connect to an API.
Only problem is it can only get API requests from an PHP file.
I want to change the code so that it wil accept .json API files
Factory
factory.readProducts = function(){
return $http({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/todos'
});
console.log(factory.readProducts)
};
Currently my GET method should be presumably be changed to fetch
Controller
$scope.readProducts = function(){
// use products factory
productsFactory.readProducts().then(function successCallback(response){
$scope.todos = response.data.records;
console.log($scope.products)
}, function errorCallback(response){
$scope.showToast("Unable to read record.");
});
}
JSON method
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
according to JSONPlaceholder it's the basic way to acces an JSON API

Needed to change the controller from:
$scope.readProducts = function(){
// use products factory
productsFactory.readProducts().then(function successCallback(response){
$scope.todos = response.data.records;
console.log($scope.products)
}, function errorCallback(response){
$scope.showToast("Unable to read record.");
});
}
To :
$scope.readProducts = function(){
// use products factory
productsFactory.readProducts().then(function successCallback(response){
$scope.todos = response.data.records;
console.log($scope.products)
}, function errorCallback(response){
$scope.showToast("Unable to read record.");
});
}
The $scope.todos = response.data.records needed to be changed to $scope.todos = response.data because of the structure of the API. It had noting to do with the file being JSON or PHP

Related

Attempting to delete contact with Axios inside of Vuejs

I am developing an app to store contact information and utilizing Vuejs and Laravel to do it. I am also using the axios library for CRUD functionality.
I have this error on axios.delete() I cannot figure out. This is my Contacts.Vue file:
<script>
export default {
data: function(){
return {
edit:false,
list:[],
contact:{
id:'',
name:'',
email:'',
phone:''
}
}
},
mounted: function(){
console.log('Contacts Component Loaded...');
this.fetchContactList();
},
methods: {
fetchContactList: function(){
console.log('Fetching contacts...');
axios.get('api/contacts').then((response) => {
console.log(response.data);
this.list = response.data;
}).catch((error) => {
console.log(error);
});
},
createContact: function(){
console.log('Creating contact...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.post('api/contact/store', params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
showContact: function(id){
let self = this;
axios.get('api/contact/' + id)
.then(function(response){
self.contact.id = response.data.id;
self.contact.name = response.data.name;
self.contact.email = response.data.email;
self.contact.phone = response.data.phone;
})
self.edit = true;
},
updateContact: function(id){
console.log('Updating contact '+id+'...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.patch('api/contact/'+id, params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
deleteContact: function(id){
axios.delete('api/contact/'+id)
.then(function(response){
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
}
}
}
</script>
I am getting a TypeError message saying that self.fetchContactList is not a function.
I know that its saying that the value is not actually a function. There is no typo in the function name. Did I call the function on the wrong object? Should I be using a different property name?
I used self.fetchContactList(); on adding and updating contacts, why will it not work with deleting the contact?
Do I need to add request headers? I didn't have to for the other requests.
If I simply remove self.fetchContactList() it will not function at all.
Despite the error, when I refresh the page, it deletes the contact, but I want the contact deleted upon clicking the delete button.
You don't have let self = this; line in deleteContact function, obviously you would get an error.
alternatively, you can use ES6 arrow functions to avoid assigning this to separate variable like this:
deleteContact: function(id) {
axios.delete('api/contact/'+id)
.then((response) => {
this.fetchContactList();
})
.catch((error) => {
console.log(error);
});
}

AngularJS to php to json working inconsistently

I used AngularJS to make an app for grading students. It works perfectly 90% of the time, but every now and then, it doesn't record the data. The grade given or other change made will be reflected in the DOM, but disappears when the page is refreshed.
I use an angular service to send data to a PHP file which sends it to a JSON file.
The service is set up like this:
app.factory('studentList', function($http) {
var studentService = {};
studentService.getInfo = function() {
var promise = $http.get('../data/studentList.json').then(function(response) {
return response.data;
});
return promise;
};
studentService.sendData = function(data) {
$http.post('../data/studentData.php', data)
.success(function (data, status, headers, config) {
console.log(status);
})
.error(function (data, status, headers, config) {
console.log(status);
});
};
return studentService;
});
When I give a grade or change student info, I call the sendData() function defined in the service. This sends it to the PHP file which looks like this:
<?php
$data = file_get_contents("php://input");
$file = "studentList.json";
file_put_contents($file, $data);
?>
I've used this PHP code before, and it seems to work fine in everything else I've done. Any insights?
Thank you.

How to call custom action in controller(laravel) using AngularJS

I am using laravel 5.
I have a custom action in my controller. By custom I mean it is not used by the resource object in angular. The following is the code of my controller.
class ServicesController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function extras()
{
// code here
}
}
This is my service code in the angular script.
(function() {
'use strict';
angular
.module('bam')
.factory('myservice', myservice);
function myservice($resource) {
// ngResource call to the API for the users
var Serviceb = $resource('services', {}, {
update: {
method: 'PUT'
},
extras: {
method: 'GET',
action: 'extras'
}
});
function getExtras(){
return Serviceb.query().$promise.then(function(results) {
return results;
}, function(error) {
console.log(error);
});
}
}
})();
Now, the query() here will send the request to the index method in the laravel controller. How will I access the extras() action in the getExtras() method?
It looks like you're almost there try out the example below I tried to use what you have in your question, and added a few other custom endpoints as examples. You'll want a base URL set up similarly to the example so you can feed it an id out of your payload so $resource can set up your base CRUD. Otherwise to make custom routes using the same resource endpoint you can add some extra actions like you have in your question, but apply your customization on the base endpoints URL.
.factory('ServicesResource', ['$resource',
function ($resource) {
// Parameters used in URL if found in payload
var paramDefaults = {
id: '#id',
param: '#param'
}
// Additional RESTful endpoints above base CRUD already in $resource
var actions = {
custom1: {
method: 'GET',
url: '/api/services/custom',
},
custom2: {
method: 'GET',
url: '/api/services/custom/:param',
},
extras: {
method: 'GET',
url: '/api/services/extras'
}
update: {
method: 'PUT'
}
}
// Default URL for base CRUD endpoints like get, save, etc
return $resource('/api/services/:id', paramDefaults, actions);
}])
Now you can dependency inject the factory and use it like this:
var payload = {param:'someParam'};
ServicesResource.custom(payload).$promise.then(function(response){
// handle success
}, function(reason) {
// handle error
});
Or for Extras:
ServicesResource.extras().$promise.then(function(response){
// Handle success
}, function(reason) {
// Handle error
});
In Laravel you're route might be something like this:
Route::get('services/{param}/custom', 'ServicesController#custom');
Or for extras like this:
Route::get('services/extras', 'ServicesController#extras');
I got what I wanted using $http.
function getExtras(){
return $http.get('/services/extras').success(function (results) {
return results;
});
}
But, that would be nice if anyone suggest me how to do it with Serviceb.query().$promise.then.

Angularjs How to get Parsed Data of Json Format return by the $http response in Service

First of all i want to clear, That am not accessing the data using web service.
My database(php) and angularjs UI are on the same server it self.
In Service of AngularJs, am sending http Get Request to interface.php(Database) it return json format. I dont how to actually parse the data and send it to Controller ?
Here Clear Cut Code :)
var app=angular.module("app.chart.ctrls",['ngSanitize']);
Controller
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data= registerService.getYears();
**how to parse the data is it correct format or not ? in Controller**
}
**Service**
app.factory('registerService', function ($http,$q,$log) {
return {
getYears:function () {
var deferred = $q.defer();
$http({
method : "GET",
url : "interface.php",
}).success(function(data){
**** How to Return the data from here to Controller ***
})
},
}
});
interface.php
1 - First define a object in your controller that later you can use as a storage for your http response like this :
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data = {};
// fire your servise function like this :
registerService.getYears($scope);
}
2- In your Servise :
app.factory('registerService', function ($http) {
return {
getYears:function (scope) {// scopes comes from your controller
$http({method : "GET",url : "interface.php"})
.success(function(data){
scope.data = data;!!!!!!
})
}
}
});
It's done so far and it'll work ;
BUT if your want to use some kind of promise , you can do like this :
in your controller :
.
.
.
$scope.data = {};
// fire your servise function like this :
var promise = registerService.getYears();
promise.then(function(msg){
$scope.data = msg.data[0];
});
.
.
.
in your Service :
app.factory('registerService', function ($http) {
return {
getYears:function () {
var promise = $http({method : "GET",url : "interface.php"});
}
return promise ;
});
from https://docs.angularjs.org/tutorial/step_11
the source:
[
{
"age": 13,
"id": "motorola-defy-with-motoblur",
"name": "Motorola DEFY\u2122 with MOTOBLUR\u2122",
"snippet": "Are you ready for everything life throws your way?"
...
},
...
]
your service looks like:
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
and your controller:
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone', function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
so, you call the service from within the controller and get the results back.

AngularJS service for php files

i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!
You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});

Categories