AngularJS access $http return json array - angularjs

i have older post which i deleted i solved it there.
I have other issue:
I have this data array came from PHP with $http(i use console.log):
I can't access that data with ng-repeat:
ibids.controller("auctions",function($http){
var req = {
method: 'POST',
url: 'includes/bids.php',
headers: {
'Content-Type': 'json'
},
data: 'q=getAuctions'
}
$http(req).then(function(req){
console.log(req);
var auctionslist = req.data;
}, function(){
});
});
html:
<body ng-controller="auctions as auction">
<input type="text" value="test" ng-model="man">
{{man}}
<hr>
<div class="search" >
<input type="text">
<div class="res" ng-repeat="x in auction.auctionslist">
{{x}}
</div>
</div>
</body>
What is wrong here ? i recive json data from php and perfect assign to data array in $http .when i use console.log(req) this is what you see in the pictures and its recive the json array perfect.
i don't know how to use ng-repeat on that data .

You have to use $scope and add a property on it for this data and use it in template
ibids.controller("auctions",function($http, $scope){
var req = {
method: 'POST',
url: 'includes/bids.php',
headers: {
'Content-Type': 'json'
},
data: 'q=getAuctions'
}
$http(req).then(function(req){
console.log(req);
$scope.auctions = req.data;
}, function(){
});
});
and in html
<body ng-controller="auctions">
<input type="text" value="test" ng-model="man">
{{man}}
<hr>
<div class="search" >
<input type="text">
<div class="res" ng-repeat="auction in auctions">
{{auction}}
</div>
</div>

Related

model does not change angularjs

I have client list in a table.
When I click on editClient, the name of the client will be displayed in an input text. This work perfectly.
<body ng-app="myClientApp" ng-controller="myClientController">
<a class="btn btn-success" ng-click="chargerClients()">
Charger Clients
</a>
<div ng-if="clients">
<table>
<tr ng-repeat="cl in clients >
<td>{{cl.idClient}} </td>
<td>{{cl.nomClient}} </td>
<td> <a class="btn btn-success" ng-click="editClient(cl.idClient,cl.nomClient)"></td>
</table>
<div>
<input type="text" ng-model="id">
<input type="text" ng-model="nom">
<button ng-click="modifyClient()"> validate</button>
</div>
</div>
</body>
The problem is when I click on modifyClient, it keeps the same values and nothing happens. How can I fix this problem?
<script>
var app=angular.module("myClientApp", []);
app.controller("myClientController", function($scope,$http,$window) {
$scope.chargerClients=function(){
$http.get("/clients")
.success(function(data){
$scope.clients=data;
});
};
//load id and name
$scope.editClient=function(idClient, nomClient){
$scope.id=idClient;
$scope.nom=nomClient;}
//modifyClient
$scope.modifyClient=function(){
var params="";
var params = ({
idClient:$scope.id,
nomClient: $scope.nom});
$http({
method: 'PUT',
url: "clients",
data: params,
headers: {'Content-type': 'application/json'}
})
.success(function(data) {
$window.alert($scope.id+$scope.nom);
$scope.chargerClients();
$window.location.href = '/index.html'
})
};
}
</script>
Try using POST method in your modifyClient
Thank you i solve it; i have to add link in ng-model:
`<ng-model="client.id">`
and in the script also:
$scope.client={}
$scope.editClient=function(idClient, nomClient){
$scope.client.id=idClient;
}
$scope.modifyClient=function(){
var params="";
var params = ({
idClient:$scope.client.id
});

AngularJS http POST using form not working

// http.post gives 404 error no matter what so I am trying with GET
// $scope.user.name etc does bring correct values from form
// I think we can't view FormData on console but passing the 'data
// after appending $scope values, runs the get request without any //data
// so I tried to make a plain dummy object 'obj' with static
// values to check get request
// this too runs URL with no data
// response that i recieve is //{"success":"no","data":"","error_code":"DSWS3","error_descriptio//n":"Server Error"}
//and yes, testing the API with same parameters on Postman does //give correct result
var data = new FormData();
data.append('name', $scope.user.name);
data.append('city', $scope.user.city);
data.append('address', $scope.user.address);
var obj = {
name: "fefe",
city: "1",
address: "fofo"
};
var data = JSON.stringify(obj);
console.log(data);
//alert(JSON.stringify(data));
$http.get('http://lowc----.com/storeManager/createParentStore?token=6fc72be8-4153-432e23a9e', data, {
withCredentials: false,
transformRequest: angular.identity,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
console.log(response)
});
I am stuck at making this HTTP POST work.. I am getting the data from form and I want to append it at the end of the URL like this baseURL+token+&name=store%20name&city=this&address=that
It gives two errors also how can I make an object of the data I received from form to pass to the http data.
1. POST (url i provided) 404 not found
2. Possibly unhandled rejection: {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /storeManager/createParentStore</pre>\n</body>\n</html>\n","status":404,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://lowcost-env.2u3kmcbg4k.us-west-2.elasticbeanstalk.com/storeManager/createParentStore?token=6fc72be8-4153-432e-9191-64a9e3b23a9e","data":{"name":"$scope.user.name","city":"$scope.user.city","address":"$scope.user.address"},"headers":{"Content-Type":"application/x-www-form-urlencoded","Accept":"application/json, text/plain, */*"}},"statusText":"Not Found"}
Here is my HTML
<form class="form-horizontal" name="userForm" ng-submit="submitForm()">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Add new </strong></h3>
</div>
<div class="panel-body form-group-separated">
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">Name</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-pencil"></span></span>
<input type="text" class="form-control" name="name" ng-model="user.name" />
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">City</label>
<div class="col-md-6 col-xs-12">
<select class="form-control select" name="city" ng-model="user.city">
<option>Islamabad</option>
<option>Rawalpindi</option>
<option>Karachi</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">Address</label>
<div class="col-md-6 col-xs-12">
<textarea class="form-control" rows="5" name="address" ng-model="user.address"></textarea>
</div>
</div>
</form>
You should not pass the $scope variables in quotes, remove the quotes and pass it as below,
var data = new FormData();
data.append('name', $scope.user.name);
data.append('city', $scope.user.city);
data.append('address', $scope.user.address);
$http.post('http://low----.com/storeManager/createParentStore?token=6fc72be3-432e-9191-64a9e3b23a9e', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
}).success(function(response) {
console.log(response)
});
Try this:
$http({ url:'http://low----.com/storeManager/createParentStore?token=6fc72be3-432e-9191-64a9e3b23a9e',
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
data: JSON.stringify($scope.user),
responseType: 'arraybuffer'
}).success(function(data, status, headers, config) {
console.log("success");
}).error(function(data, status, headers, config) {
console.log("error");
return null;
});

How to dynamically call data from an API when option is selected

Suppose there are two hotels in my options in select tags and I want my h1 to change when I select one of the options. How do I achieve this
I am using POST method to authorize and call data in my reservationCtrl and display the hotel_name in my select tags.
<div class="container">
<div class = "row" ng-controller="reservationCtrl">
<div class="form-group">
<label for="sel1">Select a Hotel:</label>
<select class="form-control" id="sel1">
<option ng-repeat="x in hotels.data">{{x.hotel_name}}</option>
</select>
</div>
</div>
And I am using GET method to call data from another API to display the hotel_name.
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data">{{x.hotel_name}}</h1>
</div>
</div>
</div>
Here is my showController and I want my hotel id to change like from 72 to 35 when I click one of the options so that it will call data from a different API and display a different name in the headers.
(function(){
angular
.module("reservationModule")
.controller("showCtrl", function($http, $scope, $log){
$http({
method: 'GET',
url: '&hotel_id=72'})
.then(function (response) {
$scope.hotel = response.data;
}, function (reason){
$scope.error = reason.data;
$log.info(reason);
});
});
})();
Here is the reservationController
(function(){
angular
.module("reservationModule")
.controller("reservationCtrl", function($http, $scope, $log){
$http({
url: '',
method: "POST",
data: 'postData',
headers:{ 'Authorization': 'value'}
})
.then(function(response) {
$scope.hotels = response.data;
}
);
});
})();
Yes you can add ng-change and achieve your functionality as below
JS code
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope) {
$scope.hotels = [{
name: 'Taj',
id: 1
}, {
name: 'Royal',
id: 2
}];
$scope.hotelInfo = {};
$scope.fetchData = function() {
// here call service which will fetch data and assign to hotel data
$scope.hotelInfo = {
address: 'London'
};
}
});
app.controller('ctrl2', function($scope) {
$scope.data = ''
});
HTML code
<div ng-app='myApp'>
<div ng-controller='ctrl1'>
<select ng-options='item as item.name for item in hotels' ng-model='hotel' ng-change='fetchData()'>
</select>
{{hotel}} - {{hotelInfo}}
</div>
</div>
Here is the link Jsfiddle demo
You need to call event on the select box which will call simple function which return the data like following
<select ng-options="size as size.name for size in sizes"
ng-model="item" ng-change="update()"></select>
write javascript code on the update function
Your can use ng-change on select of particular hotel.
In congroller :
$scope.showHotel = function(hotelName){
$scope.selectedHotel = hotelName;
}
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data" ng-change="showHotel(x.hotel_name)">{{x.hotel_name}}</h1>
</div>
</div>
In view you you can edit like this if you have to display only one hotel name instead of ng-repeat:
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1>{{selectedHotel}}</h1>
</div>
</div>

Show images from array in Angularjs

Images path are stored in database and I am fetching them from http request.
Data is in array format.
Sample data:
{"success":true,"img":["portfolio_img\/40306762187.jpg","portfolio_img\36272080187078.jpg","portfolio_img\/36211374209814.jpg","portfolio_img\/36272058183542.jpg"]}
I am want to show those images in html page.
Here is the http request code.
var formApp = angular.module('formApp', []);
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_pics.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
//forEach($scope.data,function(value,index){
// alert(value.img);
//})
}
});
})
HTML code is here.
<div ng-controller ="getprofile">
<div class="row"><div id="grid">
<fieldset ng-repeat="choice in choices"> (Need to modify)
<div class="col-xs-3 thumbnail">
<img src="" ng-src="{{imageUrl}}" ng-model="choice.course">(Need to modify)
</div>
</fieldset>
</div></div>
</div>
I am still working on code. So, there should be some error and typos.
Try this,
var formApp = angular.module('formApp', []);
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_pics.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
angular.forEach(data,function(value,index){ // Angular foreach
$scope.images = data.img; // data in images scope variable.
})
}
});
})
In HTML
<div ng-controller ="getprofile">
<div class="row"><div id="grid">
<!-- loop images scope variable -->
<fieldset>
<div class="col-xs-3 thumbnail" ng-repeat="imageUrl in images">
<img src="" ng-src="{{imageUrl}}" ng-model="choice.course">
</div>
</fieldset>
</div></div>
</div>

How to post ng-repeat Object data? i tried this way but not working

How to post ng-repeat Object data? i tried this way but not working.
<body ng-controller="mainCtrl as MC">
<div>
<div ng-repeat="(item,value) in MC.items">
{{item}} <input type="text" ng-model="value"/>
</div>
</div>
<button ng-click="MC.submitMe()">Save</button>
Controller:
mc.items = {prompt: 'prompt 1', value: 'value 1'};
mc.submitMe = function(){
var url = 'http://serverUrl';
//sample post code:
//$http.post(url, self.items);
//debug:
alert('post data to ' + url + '\n' + JSON.stringify(mc.items));
};
From the AngularJs Docs:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
in your case you are missing the callback functions:
$http.post(url, mc.items).then(function successCallback(response) {
alert('post data to ' + url + '\n' + JSON.stringify(mc.items));
}, function errorCallback(response) {
alert('post failed');
});
<body ng-controller="mainCtrl as MC">
<div>
<div ng-repeat="(item,value) in MC.items">
{{item}} <input type="text" ng-model="MC.items[item]"/>
</div>
</div>
<button ng-click="MC.submitMe()">Save</button>
Change your ng-model as above

Resources