Outputting JSON Data in Angular Expressions - javascript

My PHP script returns this JSON data:
{
"userData": {
"userName": "knows_nothing",
"userFullName": "Jon Snow",
"userMoney": "124.01"
}
}
How can I access the variables (userName etc) in my webpage?
eg:
JS
var app = angular.module('dashboard', []);
app.controller('userDataCtrl', function($scope, $http) {
data = "{query:'userData'}"
$.post("api/mysql.php", {query:'userData'})
.then(function (response) {$scope.userData = response.userData;});
});
HTML
<div ng-app="dashboard">
<div ng-controller="userDataCtrl">
<h1> Username: {{ userData.userName }} </h1>
<p> Balance: {{ userData.balance }} </p>
</div>
</div>
This has been driving me insane for hours :(
This is what it outputs when I `console.log(response.userData)
Object { userName: "knows_nothing", userFullName: "Jon Snow", userMoney: "124.01" }

According to $http documentation you should read the response from response.data. So, in your case:
...
.then(function (response) {$scope.userData = response.data.userData;});
should do the trick.

Maybe you have to declare the $scope.userData variable outside of the then-function

check if your response is array, if array then you need to do something like this,
$scope.userData = response[0].userData.
If still not getting solution please share or response format.Entire response structure.

Related

Vue.js - Displaying JSON results not working correctly

Before I start this question I am 100% new to vue.js so I may be missing something simple. I've looked through the documentation endlessly and still haven't got a soloution to my problem.
I'm just building a very simple example as practice, where I fill a form and it saves to my DB, but also loads the records I've saved automatically.
This is where it gets strange, when I plug into https://jsonplaceholder.typicode.com/users the JSON data displays correctly in my app.
When I pug into my own backend code, valid JSON is returned but it doesn't display correctly.
This is where I call my Data:
created: function(){
this.$http.get('https://jsonplaceholder.typicode.com/users') // JSON service that is working
this.$http.get('http://localhost:8888/vue_testing/users/get/') // My JSON Service that isn't
.then(function(response){
console.log(response.data);
this.users = response.data;
});
}
Note I am getting back valid JSON from both services.
My valid JSON: http://take.ms/lIa3u
But displays like this: http://take.ms/6dOEL
jsonplaceholder Valid JSON: http://take.ms/VCwKZ
And displays like this:http://take.ms/Ne3fw
This is my complete component code:
<template>
<div class="users">
<h1>Users</h1>
<form v-on:submit="add_user">
<input type="text" v-model="new_user.name" placeholder="Enter name" /><br />
<input type="text" v-model="new_user.email" placeholder="Enter email" />
<input type="submit" value="submit">
</form>
<ul>
<li v-for="user in users">
{{user.name}}: {{user.email}}
</li>
</ul>
</div>
</template>
<script>
export default{
name: 'users',
//Props can accept values from outside the component
data(){
return{
new_user: {},
users: []
}
},
methods:{
add_user: function(e){
//console.log('Add');
this.$http.post('http://localhost:8888/vue_testing/users/set/', this.new_user)
.then(response => {
console.log(response);
}, error => {
console.log(error);
});
e.preventDefault();
}
},
created: function(){
//this.$http.get('https://jsonplaceholder.typicode.com/users')
this.$http.get('http://localhost:8888/vue_testing/users/get/')
.then(function(response){
console.log(response.data);
this.users = response.data;
});
}
}
</script>
<style scoped>
</style>
Again I'm totally new to vue.js, any help in solving this is appricieated. Thanks.
While jsonplaceholder is sending you an array of objects:
[
{
"id": 1,
"name": "Leanne Grehem",
...
}
]
You are sending from your backend an object which holds first the columns, and second a two dimensional array for the data:
{
"COLUMNS": ["ID", "NAME", ...],
"DATA": [
[1, "Leanne Grehem, ...],
[2, "John Doe, ...],
]
}
I would advise you to change your backend so your response looks like that of the jsonplaceholder. Otherwise you would have to make objects out of arrays. Like below:
created: function(){
//this.$http.get('https://jsonplaceholder.typicode.com/users')
this.$http.get('http://localhost:8888/vue_testing/users/get/')
.then(function(response){
console.log(response.data);
let users = [];
const responseData = response.data['DATA']; // Get DATA key from your response
for (user of responseData) { // iterate
users.push( { id: user[0], name: user[1] } ); // create object out of array
}
this.users = users;
});
}
Edit: typo

How to display nested JSON objects using ng-repeat with Ionic framework?

I am developing a simple hybrid mobile app using the Ionic framework. When you search for a last name, a GET request is sent to retrieve all matching last names, and then displays their corresponding ID's. I am having an issue displaying the returned data from the JSON object.
Below is the html page:
<ion-view view-title="Account" ng-controller="AccountCtrl">
<ion-content>
<div class="list">
<div class="item item-input-inset">
<label class="item-input-wrapper">
<input type="text" placeholder="Search" ng-model="name">
</label>
<button class="button button-small" ng-click="searchUser(name)">
Go
</button>
</div>
</div>
<div>
<ul ng-repeat="user in $results">
<li>{{user.id}}</li>
</ul>
</div>
</ion-content>
Next is the js file that successfully returns a populated JSON object with everything I need.
angular.module('starter.controllers', [])
.controller('AccountCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.searchUser = function (name) {
$http.get('https://notrelevantforthis/searchLastName?=' + name).then(function (response) {
console.log(response.data)
//Assign JSON obj to results to repeat through and display data
$scope.results = response.data;
//To show the actual JSON object is returned
//var jsonStr = JSON.stringify($scope.results);
//document.body.innerHTML = jsonStr;
}, function (error) {
console.log(error)
});
};
}]);
Now the important part is the structure of the JSON object itself. I think this is where I am getting confused. The structure is like the following:
{
"response": {
"totalFound": 275,
"start": 0,
"acc": [
{
"id": [
"1"
],
"first_name": [
"Joe"
],
"last_name": [
"Smith"
]
},
{
"id": [
"2"
],
"first_name": [
"John"
],
"last_name": [
"Doe"
]
}]}
}
My problem is iterating through the JSON object using ng-repeat I think. For some reason none of the data is being displayed, but the object is definitely there when looking at the console. Any help or direction in what I am doing wrong would be much appreciated, as I am new to this and have been trying to find the correct way to do this.
EDIT:
Tried using collection-repeat as well offered by the ionic framework but was getting stack limit errors.
When you're assigning response.data to $scope.results, you're literally assigning the HTTP's response body to it, which is the whole JSON object that you have in your question. You would need to actually point to response.data.response.acc if you wanted to ng-repeat through those accounts.
In your template, it should just be ng-repeat="user in results", without the $ in front of results.
Your JSON object lists the id for each account as an array, I'd recommend just giving the literal value without the array, otherwise in your ng-repeat you'll have to use {{user.id[0]}} to actual print the value without printing the array itself.
I've created an example for you here: http://plnkr.co/edit/GYeF4FzVHl8Og5QTFcDx?p=preview

Sending "CC" and "BCC" in substitution data when calling Node SparkPost API

I have templates created in SparkPost dashboard. But the problem I face is that I am not able to send "CC" or "BCC" by making the api calls. The code snippet below will help you understand what I am trying to do.
var SPARKPOST_KEY = "KEY"
var sparkpost = require('sparkpost');
var sparkclient = new sparkpost(SPARKPOST_KEY);
var req_opts = {
transmissionBody : {
content: {
template_id: 'order-confirmation',
from: 'support#domain.in',
subject: 'Order confirmation',
headers: {
"CC": "<anon2#gmail.com>"
}
},
substitution_data: {
"CC": "anon2#gmail.com",
"customer": "Aravind",
"order": 123532
},
recipients: [
{address: {email:'anon1#domain1.in'}},
{address: {email: 'anon2#gmail.com'}}
],
"return_path": "support#domain.in",
}
};
sparkclient.transmissions.send(req_opts, function(err, res){
if(err){
console.log("ERROR");
console.log(err)
}else {
console.log(res.body);
console.log("Mail has been successfully sent");
}
});
As mentioned in the reply on your github issue, you must use either inline content or a template. So as the documentation says, use just template_id in your content.
What needs to happen for this to work is that the headers in the template include a CC header, as described here. Currently there is no way to set the headers of a template in the UI -- it must be done using the API.
To do this execute a PUT against the templates endpoint, in your case https://api.sparkpost.com/api/v1/templates/order-confirmation, with a JSON payload containing the following:
{
"content": {
<other content parts>
"headers": {
"CC": "{{CC}}"
}
}
}
Note that you will also need to use the header_to parameter for your CC recipient to prevent their address showing up in the To: header. In your example this means replacing:
{address: {email: 'anon2#gmail.com'}}
with this:
{address: {email: 'anon2#gmail.com', header_to: 'anon1#domain1.in'}}
You also do not need the return_path parameter.
Hope this helps!

ng-repeat won't repeat array of data

I am pulling in a JSON file using Angular's $http, but I can't get the formatting right to use ng-repeat for an array of data.
For brevity's sake, here is a sample piece of what I'm working with...
{
name:"Pete",
phone: {
brand: "Nexus",
OS: "Android",
contacts: [
"Alexis",
"Billy",
"Chuck",
"Danny"
]
}
}
Then my ng code is
function($scope, $http) {
$http.get('/my/url')
.success(
function(data){
$scope.contacts = data.phone.contacts;
and my HTML is
<div ng-repeat="names in contacts">
{{names}}
</div>
Only it isn't returning anything. I feel like I am missing a set of [] somewhere?
In JSON:
conAtacts: [
"Alexis",
"Billy",
"Chuck",
"Danny"
]
On view:
<div ng-repeat="names in contacts">
{{names}}
</div>
conAtacts != contacts
Also, you have missed one bracket in JSON.
Should be:
{
name:"Pete",
phone: {
brand: "Nexus",
OS: "Android",
contacts: [
"Alexis",
"Billy",
"Chuck",
"Danny"
]
}
}
Can it be reasons of issue?
Your problem could simply be because you didn't respect the widely recommended practice of the 'point' when you use values that can evolve in AngularJS.
Create an object in the scope :
$scope.dataScope = {}
then in your method
function($scope, $http) {
$http.get('/my/url')
.success(
function(data){
$scope.dataScope.contacts = data.phone.contacts;
and in your html
<div ng-repeat="name in dataScope.contacts">
{{name}}
</div>
Thanks everyone for the as always quick responses. This was a case of sleep deprivation and overthinking things on my part and I left out the ng-controller for the div that the ng-repeat was in.
<div **ng-controller="myCtrl"** ng-repeat="names in contacts">
{{names}}
</div>

AngularJS assign variables to view's scope

I have a somewhat deep JSON object I am trying to using in an HTML template.
{
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
}
I am including a template with the following HTML code.
<div class="modal-body" ng-include="service.instructionsTemplate"> </div>
In the template there is the following.
<h1>Some example content</h1>
{{service.metadata.password}}
My question is instead of referencing the field password via service.metadata, is there a way I can reference it with just the variable password.
I was trying to dig through some of the Angular docs around scoping and templates but came up empty. I saw you can use ng-init.
I was able to use ng-init="metadata = service.metadata" and was able to reference the field password in the template via metadata.password.
However I would just like to reference it by password.
Any ideas?
You already did ng-init="metadata = service.metadata", why not going a step further and do ng-init="password = service.metadata.password"?
Another way would be to bind $scope.password = service.metadata.password inside the controller thayou're using on that page
Edit: OP asked a more general solution
If you don't know the property names, then your best move would be to bind the metadata object, like you already did, and then iterate through its properties using ng-repeat
in your controller:
$scope.metadata = service.metadata
in your template (view):
<h1>Some example content</h1>
<ul>
<li ng-repeat="element in metadata">{{element}}</li>
</ul>
You can easily set the password to something inside the controller:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.data = {
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
};
$scope.password = $scope.data.service.metadata.password;
});
Here is a demo: http://plnkr.co/edit/KrKeLIP2ANd0rl5NLywF?p=preview

Categories

Resources