Ionic / AngularJS passing ID through a http.get - javascript

I'm having trouble passing the session_id through to my http.get function, any ideas what I'm doing wrong?
Heres my controller:
.controller('feedCtrl', function($scope,$rootScope,$ionicHistory,$state,$http) {
$scope.session_id= sessionStorage.getItem('session_id');
if($scope.session_id == null){
$state.go('login');
}
else {
$http.get('https://m.socialnetwk.com/home/app/feed_load.php?id='+ $scope.session_id +).then(function(rest) {
$scope.records = rest.data;
});
}
})

Errors I see in the code:
You should do to inject sessionStorage service.
Delete + at the end of URL.
Check Example : Link

I wouldnt exactly know what is the problem unless u explain how 'https://m.socialnetwk.com/home/app/' endpoint works and what error does it produce but my suspicion is that as you say you need to PASS the session_id and not GET it, you need to use $http.post instead of $http.get

I have tested your http request in Postman and it's working ok.
https://m.socialnetwk.com/home/app/feed_load.php?id=4235
and returns:
[
{
"firstname": "4235",
"lastname": "Round",
"profile_image": "jpg/55529055162cf0.jpg",
"lastname": "Round",
"iframe": "",
"media_format": "img",
"media_file_format": "jpg",
"media_post_id": "5851875bda5b3",
"media_author_id": "3",
"mediatxt": ""
},
{
"firstname": "4235",
"lastname": "Round",
"profile_image": "jpg/55529055162cf0.jpg",
"lastname": "Round",
"iframe": "",
"media_format": "img",
"media_file_format": "jpg",
"media_post_id": "583c459a745a4",
"media_author_id": "3",
"mediatxt": ""
},
{
"firstname": "4235",
"lastname": "Round",
"profile_image": "jpg/55529055162cf0.jpg",
"lastname": "Round",
"iframe": "",
"media_format": "img",
"media_file_format": "jpg",
"media_post_id": "583c4597778c1",
"media_author_id": "3",
"mediatxt": ""
},
{
}
]
so your error is:
$scope.session_id= sessionStorage.getItem('session_id');
if you print $scope.session you are going to get undefined. So your http request returns a empty array.
Let's fix it
Inject sessionStorage. Let's suppose you are using ngStore, so you need to inject $sessionStorage.
Example:
.controller('feedCtrl', function($scope,$rootScope,$ionicHistory,$state,$http, $sessionStorage )
Change your code:
$scope.session_id= sessionStorage.getItem('session_id');
$http.get('https://m.socialnetwk.com/home/app/feed_load.php?id='+ $scope.session_id +).then(function(rest) {
$scope.records = rest.data;
});
to:
$scope.session_id= $sessionStorage.getItem('session_id');
and delete + at the end of URL.
$http.get('https://m.socialnetwk.com/home/app/feed_load.php?id='+ $scope.session_id).then(function(rest) {
$scope.records = rest.data;
});
As Jackk tell you.
Sorry for my english.

Related

Javascript parse JSON error, but works fine in validator

When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);

not getting data from JSON file using angularjs 1.6

I am trying to get data from my JSON file using AngularJs 1.6
myApp.controller("homeCtrl", function($scope, $http) {
$scope.Data = [];
var getJsonData = function() {
$http.get('contactlist.json').then(function(response) {
$scope.Data = response.data;
console.log(response.data);
});
}
getJsonData();
});
But it's not going to response I am putting debug on then line but my page opened without stopping on debug response. So it's not going on then(function(reponse){
My JSON File:
var contactList = [
{
"firstName": "Joe",
"lastName": "Perry",
"contactNumber": "444-888-1223",
"contactEmail": "joe#cordis.us"
},
{
"firstName": "Kate",
"lastName": "Will",
"contactNumber": "244-838-1213",
"contactEmail": "kate#cordis.us"
}
];
Got it resolved. Issue was because of semicolon at the end of json file data.
Got this error when tried pasting in Plunker editor
My Bad.
Change your json file to(your json is not valid):
[{"firstName":"Joe","lastName":"Perry","contactNumber":"444-888-1223","contactEmail":"joe#cordis.us"},{"firstName":"Kate","lastName":"Will","contactNumber":"244-838-1213","contactEmail":"kate#cordis.us"}]
Remove var contactList = from you JSON file and place the JSON contents only
like:
[
{
"firstName": "Joe",
"lastName": "Perry",
"contactNumber": "444-888-1223",
"contactEmail": "joe#cordis.us"
},
{
"firstName": "Kate",
"lastName": "Will",
"contactNumber": "244-838-1213",
"contactEmail": "kate#cordis.us"
}
]
var contactList = <something> meant it's javascript code need to be execute, but you are reading the file and parsing it as a json data and not executing as js file, so make it like a json file so the contents is only json string and not some javascript code.

While retrieve a model by ID from a Backbone.js collection returning undefined

I'm trying to get a model from a collection by it's ID and display in view. After instantiating a model, I'm using the methods like get(), at() but it's returning undefined.
My collection:
[
{
"id": "1",
"firstname": "Abc",
"lastname": "Xyz"
},
{
"id": "2",
"firstname": "Klm",
"lastname": "Opq"
},
{
"id": "2",
"firstname": "rst",
"lastname": "Yvw"
}
]
Instantiation:
var persons = new PersonCollection();
console.log(persons.get(1)); // undefined
NOTE: I'm getting all the models in console (Not an issue). I want only to fetch a model by it's id name.
fetch is async so you need to place your code inside success callback
persons.fetch({
success: function() {
console.log('Now I have something: ', persons.get(1))
}
})
console.log('Nothing here: ', persons.get(1))
BTW to fetch single model by id you could use Model#fetch instead

Trouble parsing json with node.js

I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)

Json returns every character as a separate object?

I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);

Categories

Resources