Pulling JSON data from API server in Angular 1 - javascript

Struggling to get http:get to pull a request from a API server in an Ionic app, can anyone help with the code. Here is what I have:
<form ng-submit="getOrders()">
<label class="item item-input item-stacked-label">
<span class="input-label">Search Order #</span>
<input type="text" name="order number" placeholder="enter order number" ng-model="query">
</label>
<input class="button button-block button-positive" type="submit" name="submit" value="Submit">
</form>
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+ $scope.query).success(function(data) {
$scope.orders = [ data.data ];
$scope.query = query;
console.log(query);
})
}
Here are a few http get code blocks I have tried without success
//$http.get('http://example.com/api/booking/get/orders/').success(function(data) {
//$http({ url: 'http://example.com/api/booking/orders/', method: "GET", params: {query} }).success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/+ $scope.query').success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/121137').success(function(data) {
//$http.get('js/121137.json').success(function(data) {
Also, here is an example of some working POST code to an API which may provide some extra clues in performing a successful GET query from an API server:
https://plnkr.co/edit/w0cyfzGij8SgcsnbXqsj?p=catalogue

use promise as follows
.then(function(success){
//handle success
})
.catch(function(error){
//handle error
})

this is currect code.
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+$scope.query).success(function(data) {
$scope.orders = data.data;
console.log(data);
console.log($scope.query);
})
}

Related

AngularJS Empty Respose Using Spring Boot And Mongodb

I have a AngularJS app where I take in user input and store it in a painting objects and then send it to my spring boot back-end that will store it to the Mongodb server and return an id, however when I try go POST anything to the server i get an empty response back, even though the object gets stored in the server.
AngularJS code:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.1/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<br>
<br>
<br>
URL : <input type="text" ng-model="painting.url"><br>
Artist : <input type="text" ng-model="painting.artist"><br>
ArtistInfo : <input type="text" ng-model="painting.artistInfo"><br>
Title : <input type="text" ng-model="painting.title"><br>
Dated : <input type="text" ng-model="painting.dated"><br>
Medium : <input type="text" ng-model="painting.medium"><br>
Dimensions : <input type="text" ng-model="painting.dimensions"><br>
Credit : <input type="text" ng-model="painting.credit"><br>
<button ng-click="submit()">Post</button>
<pre>{{painting | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope','$http', function($scope,$http) {
$scope.name = "";
$scope.painting = {
url: '',
artist: '',
artistInfo: '',
title: '',
dated: '',
medium: '',
dimensions: '',
credit: ''
};
$scope.submit = function(){
console.log(JSON.stringify($scope.painting));
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'http://localhost:8080/paintings',
data: $scope.painting
}).then(function (response) {
console.log(response);
}, function (response) {
console.log("Error");
console.log((JSON.stringify(response)));
});
//$http.post('http://localhost:8080/paintings', $scope.painting).catch(console.error);
};
}]);
</script>
</body>
</html>
SpringBoot Java POST Method:
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public String save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
return painting.getID();
}
PostMan Response:
Not sure why I'm getting an empty response when I check the console in a browser, even though the server is sending back a response.
I think you need to access the data property of the response,
.then(function (response) {
console.log(response.data);
}
What I ended up doing with the help of #Sajeetharan is edit my backend post request to
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public ResponseEntity<String> save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
JSONObject json = new JSONObject();
json.put("id",painting.getID());
return ResponseEntity.ok(json.toString());
}

Converting from get request from JQuery to Vue.js

I am new to js and would like to convert my JQuery-based js to Vue. I want to send a get request and output back the data. What is the best way of doing this?
Here is the html:
<div>
<div>
<input type="text" id="var1" placeholder="Search...">
</div>
<div>
<button id="submit">Submit</button>
</div>
</div>
<div>
<p>Results</p>
<p id="results"></p>
</div>
Below is my js:
$(document).read(function() {
$('#var1').keypress(function(e) {
if (e.keyCode == 13)
('#submit').click();
});
});
$(document).ready(function() {
$("#submit").click(function() {
var var1 = document.getElementById("var1").value
// sends get request to URL
$.getJSON("URL" + var1, function(search, status) {
console.log(search);
// cont.
$("#results").text(search.results);
});
});
});
EDIT: Here is what I have so far with axios:
function performGetRequest() {
var var1 = document.getElementById('var1').value;
axios.get('URL', {
params: {
id: var1
}
})
.then(function (response) {
console.log(search);
})
}
I am not sure if the above code is correct or how to factor in keypress and click-- is there a simple way to do that?
Well, I am not sure what you want to do with this ajax call, but hopefully this may help you. Vue is data driven, so I always try to focus on that aspect. So this is an example of how you can access and input and send the data using axios.
<div>
<div>
<input v-model='input' type="text" placeholder="Search...">
</div>
<div>
<button #click="searchInput()">Submit</button>
</div>
</div>
<div>
<p>Results</p>
<p >{{ result }}</p>
</div>
you must have those models in your data
// Your data
data() {
return {
input: '',
result: '',
}
}
and your method will look something like this.
searchInput() {
axios({
method: 'GET',
url: url + this.input,
}).then(response => {
this.result = response.data;
}).catch(error => {
//handle error
})
}
So this is a very basic example. you can do the same process in different ways, you could pass the input to the method or loop over the results, but the idea is taking advantage of Vue.js data driven system and think data first.
Hopefully this will help you, remember to escape your input and add necessary validations. Good luck

how to post data to server using angularJS, web api

i am new to angularJS and trying to figure out, how to post data to my server, problem is that my post to server is successful and it create new record but all is empty(null).
Thanks for any advice
JS:
$scope.addChannel = function () {
var channels = [];
//var newChannel = {
// Name: $scope.Name
//};
//clearing error message
$scope.errorMessage = "";
$http.post("api/Channel/channels", newChannel)
.success(function (newChannel) {
//on success
$scope.channels.push({ "Name": $scope.Name });
console.log("data added");
// newChannel.push(response.data);
newChannel = {};
}, function () {
//on failure
$scope.errorMessage = "Failed to save data";
})
}
HTML:
<div ng-controller="ChannelController">
<div class="col-md-4 col-lg-4 col-sm-4">
<form novalidate name="newUser"ng-submit="addChannel()">
<div class="form-group">
<label for="name">Channel</label>
<input class="form-control" type="text" id="Name" name="Name" ng-model="newChannel.Name" />
</div>
<div class="form-group">
<input type="submit" value="Add" class="btn btn-success" />
</div>
</form>
<a ng-href="/Dashboard#/channels">Return to dashboard</a>
</div>
<div class="has-error" ng-show="errorMessage">
{{errorMessage}}
</div>
Channel Controller
[HttpPost("channels")]
public async System.Threading.Tasks.Task Create(Channel channel)
{
await _channelRepository.CreateChannel(channel);
}
Repository
public async System.Threading.Tasks.Task CreateChannel(Channel channel)
{
_context.Channel.Add(channel);
await _context.SaveChangesAsync();
}
Check if you name properties correctly in object that you send to server, property names are case sensitive. Looks like you have in js
var customer = {name: 'foo', lastName: 'bar'};
and on server you try to deserialize your JSON to this entity
class Customer {
public Name {get;set;} //note prop names are capitalized
public LastName {get;set;}
}

Edit MEANJS list in the list page

I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource

using angular.js ui and bootstrap typeahead for asynchronous call to retrieve auto suggestions for search

I am using angular 1.3.0 and bootstrap 3.2.0. I am trying to get data from asynchronously from my mysql database but I got some issue with bootstrap typeahead.
MY code index.html:
<input type="text" ng-model='locality' name="locality" typeahead="name for locality in getLocality($viewValue) | filter:$viewValue" typeahead-loading="loadingLocations" class="form-control size1 input-medium search-query"
placeholder="Enter Organization name/service">
</input>
main.js file for typeahead
$scope.getLocality = function(val) {
console.log(val);
var url = $rootScope.baseURL + '/api/location?locality=' + val;
console.log(url);
return $http.get(url, {
params: {
name: val,
sensor: false
}
}).then(function(response) {
var addresses = [];
angular.forEach(response.data.resulults, function(item) {
addresses.push(item.formatted_name);
});
return addresses;
});
};
When I was debugging this value will fine but i am not getting any auto suggestions please any one help me out of this problem.
It's working fine Thank u #tiblu
index.html file
<input type="text" ng-model='locality' name="locality"
typeahead="name for name in getLocality($viewValue)"
typeahead-loading="loadingLocations"
class="form-control size1 input-medium search-query"
placeholder="Enter Organization name/service">
</input>
.js file
$scope.getLocality=function(val){
console.log(val);
var url=$rootScope.baseURL + '/api/location?locality='+val;
console.log(url);
return $http.get(url,{
params: {
name: val,
sensor: false
}
}).then(function(response){
console.log(response);
console.log(response.data);
var addresses=[];
angular.forEach(response.data.data,function(item){
addresses.push(item.name);
//return item.formatted_name;
console.log(response.data);
});
return addresses;
/*return response.data.results.map(function(item){
return item.formatted_address;*/
});
};

Categories

Resources