How to POST data to php template in angular - javascript

New to angular, new to php, new to programming at all.
I'm using ui-router, and here's how it looks like:
.state('admin', {
url:'/admin',
templateUrl: 'admin/admin.php',
controller: 'AdminController'
})
.state('admin.auto', {
url: '/auto',
templateUrl: 'admin/states/auto.php',
controller: 'AdminAutoController'
})
.state('admin.auto.update', {
url: '/update',
templateUrl: 'admin/states/autoupdate.php',
controller: 'AdminAutoUpdateController'
})
Routing works fine, on my admin.auto view, I've got list of autos with "edit" and "delete" buttons. I get the list from MySQL database.
<div ng-repeat="auto in autos">
<p>{{auto.mark}}</p>
<button class="btn btn-primary" ng-click="updateAuto(auto.mark)">Edit</button>
<button class="btn btn-danger">Delete</button>
</div>
So now I need to post auto.id to auto update nested view, so i can select proper table row. At this point I'm struggling to post any data to update view, just to find out if it works, so here it is:
.controller('AdminAutoController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
$http.get('php/DBZ.php').success(function(data) {
$scope.autos = data;
});
$http({
url: "admin/states/autoupdate.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({id:"some id"})
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}])
And, finally, my PHP:
<?php
$test = $_POST['id'];
echo $test;
?>
So, as a result, i get:
Notice: Undefined index: id on line 4
Sorry for my English, and thanks for any help!

Related

Angularjs $scope.data not showing in html

I get the response from POST, it prints the data in the console but it doesn't show the data in the html page.
I have my controller, its just that the {{user}} doesnt show in html page
I can see the what it returns in the console,
angular.module('app.AllUsersCtrl', [])
.controller('AllUsersCtrl', function ($scope, $http, $cookies, $window, $state) {
$scope.getAccount = function (n) {
$http({
method: 'POST',
url: '/FYPapp/getAccount',
data: $.param({
username: n
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
}).success(function (data, status, headers, config) {
console.log(JSON.stringify(data));
$scope.user = JSON.stringify(data);
});
};
});
**Data Returns **
scripts.js:95 {"id":118,"firstname":"Lauren","lastname":"Smithss","description":"the Makup Chair the.....","enabled":true,"user":{"userid":21,"username":"theMak","email":"theMak22#mail.com","password":"995bf49114defd4f35d10e477135b89112ecdc2f25af6ab7969112842919ba4dc193b194f9485671","enabled":true},"followers":[],"username":"theMak"}
HTML: This is the html page
<link rel="stylesheet" type="text/css" href="static/app/css/css.scss">
<div class="mainDiv">
<h1> Profile Details</h1>
{{user}}
</div>
In your HTML you need to define our controller with ng-controller and also the ng-app which will be your module name.
Then you will need to make the data call.
After that you can directly assign the data to scope like this:
$scope.user = data;
As it appears you're using a controller alias, ie
.state('profile', {
url: "/profile",
templateUrl: '/views/profile.html',
controller: 'AllUsersCtrl',
controllerAs: 'allusers' // this one here
})
You should be assigning methods and properties to the controller instance, eg
.controller('AllUsersCtrl', ['$http', function($http) {
var ctrl = this;
this.getAccount = function(n) {
$http(...).then(function(response) {
ctrl.user = response.data;
});
};
}])
and in your template...
<img ng-click="allusers.getAccount(something)"...
and
<h1>Profile Details</h1>
<!-- for debugging -->
<pre>{{allusers.user | json}}</pre>
<!-- or for prod -->
<p>{{allusers.user.firstname}} {{allusers.user.lastname}}</p>
You are missing ng-controller in your html templates.
<h1> Profile Details</h1>
{{user}}

How can I pull in more WordPress posts from my angular app, using the WordPress REST api

I am trying to build a page of WordPress posts, showing 4 initially and then lazy load these in onclick of a "Load More" button. This list will be filterable via angular.
I am using the json rest api plugin for WordPress, and my angular app is currently:
var myapp = angular.module( 'myapp', [] );
// Set the configuration
myapp.run( ['$rootScope', function($rootScope) {
// Variables defined by wp_localize_script
$rootScope.api = aeJS.api;
}]);
// Add a controller
myapp.controller( 'mycontroller', ['$scope', '$http', function( $scope, $http ) {
// Load posts from the WordPress API
$http({
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]' : 4
},
}).
success( function( data, status, headers, config ) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {});
$scope.loadmore = function(){
$scope.posts = $scope.posts.concat(data);
}
}]);
I am just a bit clueless with how to get the next 4 posts each time the load more button is clicked. I have setup a loadmore function which I am calling on click of the button:
<button ng-click="loadmore()">Load more articles</button>
Any advice would be appreciated, thanks.
Basically you need to use paging which has already implemented in wordpress API.
You need to increment your posts_per_page on each ajax call.
Controller
myapp.controller('mycontroller', ['$scope', '$http', function($scope, $http) {
var count = 0;
$scope.posts = []; //setted as blank
$scope.getData = function() {
// Load posts from the WordPress API
$http({
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]': 4,
'filter[page]': ++count
},
}).
success(function(data, status, headers, config) {
$scope.posts = $scope.posts.concat(data);
}).
error(function(data, status, headers, config) {});
};
$scope.loadmore = function() {
$scope.getData();
};
}]);
Done - with the help from a friend, this solution is working nicely:
var myapp = angular.module( 'myapp', [] );
// Set the configuration
myapp.run( ['$rootScope', function($rootScope) {
// Variables defined by wp_localize_script
$rootScope.api = aeJS.api;
}]);
myapp.controller('mycontroller', ['$scope', '$http', function($scope, $http) {
$scope.init = function() {
$http({ // Load posts from the WordPress API
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]' : 4
},
}).
success( function( data, status, headers, config ) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {});
};
var page = 2;
$scope.getData = function() {
$http({ // Load posts from the WordPress API
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]': 4,
'page': page
},
}).
success(function(data, status, headers, config) {
$scope.posts = $scope.posts.concat(data);
page++;
}).
error(function(data, status, headers, config) {});
};
$scope.loadmore = function() {
$scope.getData();
};
}]);

not getting data from $http from service to scope

we are trying to get data from service agrService with $http its working but when i reccive data to controller i am not able to access it outside that function
$scope.resource return data inside function but not outside please help.
var app = angular.module('app', ['ui.router','ngTasty']);
app.config(['$urlRouterProvider', '$stateProvider',function($urlRouterProvider, $stateProvider, $routeProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html',
controller: function($scope, $http, $location, agrService) {
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
}, function(error) {
// do something else
});
I NEED TO ACCCESS DATA HERE CAN ANY BODY HELP
console.log($scope.resource);
}
});
}]);
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
var ret = $q.defer();
$http({
method: 'GET',
dataType: "json",
url: dataUrl
})
.success(function(data, status, headers, config) {
ret.resolve(data);
}).error(function(data, status, headers, config) {
ret.reject("Niente, Nada, Caput");
});
return ret.promise;
};
});
My suggestion would be to rethink the logic a bit. You want to do something with the data after you receive it, so why not make a function that you call once the data is received?
You'll never be able to access the resource data in that console log, simply because $http is an async call, and no matter if you return a promise or not, it's simply not ready at that point.
However, if you use it in a template or elsewhere that uses angular's double binding, it will work just fine.
To fix your issue, you can define a function with what happens after that service call and simply call it from the success callback:
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
myAfterFunction(); // <--- here
}, function(error) {
// do something else
});
and the function can be:
function myAfterFunction() {
console.log($scope.resource);
}
And btw. your service is an example of deferred antipattern, you can simply do this:
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
return $http({
method: 'GET',
dataType: "json",
url: dataUrl
})
};
});

Can't split up JSON

I am stuck with this annoying problem that I can't seem to figure out.
I want to take a JSON file and only show that information I find relevant. But somehow I can only show the whole thing, and not choose, for example, {{post.title}}.
Here is the JSON I want to use: http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json
This is my controller:
.controller('View5Ctrl', function ($scope, $http, $timeout)
$http({
method: 'GET',
//url: '/test/allMovies/test'
url: 'http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json',
dataType: 'json'
}).
success(function (data, status, headers, config) {
$scope.posts = data;
}).
error(function (data, status, headers, config) {
$scope.error = data;
});
});
And this is my HTML file
<div ng-repeat="post in posts" >
<div id="div">
<p>
{{post.title}}
</p>
<p></p>
</p>
</div>
By this, I only get a bunch of empty paragraphs. But if I remove the .title, I get the whole thing out.
SOLUTION:
Thanks for the answers! I will post the solution here for future viewers.
<div id="div">
<p>
{{posts.Title}}
</p>
</div>

How to pass URL params in angular $http

I'm converting a server side CRUD app to Angular.js and have a small problem.
I'm getting my data with $http and display all the data via ng-repeat. I want to make users able to click and a specific item and redirect them to the resource.
So how can I pass a URL param to the $http get call dynamically?
Here's how I built the link to the resource (car.id = 3)
<a ng-href="/#/cars/{{car.id}}">Edit</a>
The link should go to http://local.dev/#/cars/3
So how do I bind the dynamic url in my controller?
Here's a stripped down version of my controller
App.controller('CarIndexCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
$scope.car = {};
$http({
method: 'GET',
url: $location.$$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
})
.error(function (data, status, headers, config) {
// error
});
}]);
So I'm interested to bind the URL the angular way. The above solution works, but feels very much like a hack. I'm not that familiar with Angular, so I like to stick to the defaults for now. I might consider restangular or ng-resource at a later time though...
the above solution works, but feels very much like a hack.
I don't think its hack or something messy.
I would generate URL list in controller (from my view its better for code maintenance) without appending in HTML. Something like:
$scope.urlList = [];
$http({
method: 'GET',
url: $location.$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
$scope.urlList.push("/#/cars/" + data.id);
})
.error(function (data, status, headers, config) {
// error
});
After in HTML:
<li ng-repeat="url in urlList" repeat-done="layoutDone()" ng-cloak>
<a ng-href="{{url}}">Edit</a>
</li>
BTW, I suggest you to use some loader because URL links we generate from promise (aka async) therefore with delay.
Demo Fiddle
In your app.js do something like this
var app = angular.module('YourAPP');
app.config(function ($routeProvider) {
$routeProvider
.when('/cars/:CarID', {
templateUrl: 'app/views/cars.html',
controller: 'CarIndexCtrl'
});
});
And in your controller
App.controller('CarIndexCtrl', ['$scope', '$http', '$location', '$routeParams', function ($scope, $http, $location, $routeParams) {
$scope.car = {};
$scope.carid = $routeParams.CarID;
$http({
method: 'GET',
url: $location.$$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
})
.error(function (data, status, headers, config) {
// error
});
}]);
And use the carid in wherever in your controller. Hope it helps.

Categories