Getting a value from 3rd party website API - javascript

So I'm desperately trying to pull a value from a 3rd party website API. The information is formatted in the following way:
Website's API response
I'd like to pull out a value for "price". So far I've tried many different codes but all have failed. I've also spent a lot of time searching for a solution but without succes. At the moment my code for obtaining the value looks like this, but it's obviously not complete and incorrect as I'm new to NodeJs:
var Request = require("request");
Request.get("url", (error, response, body) => {
if(error) {
return console.dir(error);
}
console.dir(JSON.parse(body));
});
And yes the url is actually inserted in my code + I know that this should only display the full JSON structure, but it fails to do even that :/
Any kind of advice would be welcome :)
EDIT: So I've fixed that issue with not getting data :) However I still need to filter my data in order to pull out the "price" value. As of now my data displays this: "data: { items_on_sale: [ [Object] ], items_not_on_sale: [] } }"

status: 'fail' : The api is not replying with the data.Does the url require any query params/body to be passed with the url?
Try hitting the api using postman/SoapUI and check the response there.
also try printing the response in the log,what values do you get?
console.log('statusCode:', response && response.statusCode);

There was a problem with 2FA code. It wasn't generating properly. It is now fixed.

Related

How do I send json object that javascript can understand as array rather than string using R and plumber?

I'm trying to get JSON raw response from R Plumber and consume it in Angular, but JavaScript Framework thinks it's a string rather than a JSON format.
"[{\"id\":1,\"type\":\"Diagnostic\"},{\"id\":2,\"type\":\"Impact\"}]"
I saw here and here, but these didn't really help me.
How do I make it so that it's a proper JSON format that JavaScript frameworks can recognize.
#* #apiTitle Diagnostic Report API
#* Send the list of report types
#* #get /reportTypes
#* #serializer unboxedJSON
function(){
reportTypes <- read_csv(file = "ReportTypes.csv")
# list(
# message_echo = paste("The text is:", "text")
# )
}
And in the Angular, this is the error that I receive. Given that this is not Angular SO, I just wanted to show the issue I'm running into:
Cannot find a differ supporting object '[{"id":1,"type":"Diagnostic"},{"id":2,"type":"Impact"}]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
Not the best thing to do to answer your own question, but I found many questions like this but without a particular solution that worked for me. I felt I should write this as an answer for anyone who'd run into similar situation. Hopefully, it'll save someone hours of painful debugging.
As many of the posts including the ones that I mentioned above correctly assert that plumber automatically serializes the r object. This means, it should be ready for any application requesting the data to consume. But clearly, there were something that I was missing. I had already tried solutions based on these.
Turns out, my express.js server was also parsing the text to json.
router.get('/', function (req, res) {
request.get({ url: 'http://localhost:5762/reportTypes' },
function (error, response, body) {
if (!error && response.statusCode == 200) {
res.json(body); <-- this is where it's serializing again
}
});
});
Credit to all SO community and responders including #MrFlick who discussed about JSON parsing, it gave me a thought perhaps there's somewhere something is serializing the data. So, after digging, it turns out that my express is re-serializing the already serialized data. Simply changing res.json to res.send solved the problem.
Hopefully, this will give some ideas to people who either work on r or javascript and have similar problems, to re-check the codes which is requesting the data again and make sure it's not getting serialized and escaping important characters.

JSON spreadsheet returns null, or am I an idiot

So, have been trying to get a javascript to read a spreadsheet, but needed it private rather than public, so spent quite a bit of time trying to figure out how to do that. It is actually quite easy, or seems like it is, except that I still can't read the spreadsheet. Will cover private spreadsheets through the cloud console in the end.
So, I have a rather simple spreadsheet which contains about 6 columns, (including customer emails and similar, hence why private). And I have been playing about trying to get it to work for the last couple of days.
First, the string!
So to enable this I first need a string that will return a json object (is that what I am expecting back?)
https address: https://spreadsheets.google.com/feeds/list/
Sheet ID :
Additional : /od6/private/full
Command : ?alt=json-in-script&callback=importGSS
or full string : https://spreadsheets.google.com/feeds/list//od6/private/full?alt=json-in-script&callback=importGSS
This seems to work quite fine, if I remove the json part it shows me the data sheet, if I ad it, I get an empty file instead.
So now to the code.
The function that SHOULD be returning the object is the following (spLink) contains the link above.
function loadData(spLink){
$.getJSON(spLink).always(function(data) {
console.log("Object created!");
console.log(data);
}).fail(function(message) {
console.error('Something went pretty wrong!');
console.error(message);
}).done(function(){
console.log('Done!');
});
}
The only thing I can really tell about it is that data continues returning null, and I can't really figure out where else the data may end up.
Have tried both with and without callback.
The list feed only works if there are no empty cells in a row with data, among other pitfalls.
Use the cell feed instead, which requires more code because you wont get the data organized by rows.

Script error: "Unable to get value of the property 'split': Object is null or undefined

I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.

Form data not passing to PHP file

The Program I'm writing and the functionality I'm trying to achieve
Okay. So what I'm writing at the moment is a very simple forum, in Javascript using AJAX. Part of my task is to add a new post, using an API that my lecturer wrote for us in PHP. Just to note, the API and the SQL database are completely local.
The function I am using to add this post is:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
'method':'post',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).send(Object.toQueryString({
// Had to convert it to a query string because it wouldn't work as a normal object.
// These are the required values to send, to store a "post" in the database.
'name':'This is a name',
'comment':'This is a comment!'
}));
}
I am aware this will add the same data every single time. I'm just trying to get the damn thing working!
The problem
What is happening is, when this function is called, I am getting an SQL syntax error. I was confused, because that would imply that my lecturer's code is wrong. After speaking with my lecturer, he explained that this happens when the post data isn't sent correctly to the PHP code. So I went about using Google Chrome's developer tools to see what was going on, and this is what I discovered:
Now to me, this means that the data is successfully being loaded into the request, and is being passed to the PHP files fine. Obviously I'm wrong. I've been racking my brains trying to make this work.
I know that the API works fine, because everyone else in my class isn't having any problem with it, and the code I am using is practically a rip off of the code in the notes, so I'm about 90% sure that's correct to.
One thing to note is that the code in the onSuccess key runs, so I know it's not a problem on the AJAX side.
Another thing is that this code worked in University on those computers, and it's since I've got it home that it's decided not to work.
Stack Trace
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000]: General error: 1 near ")": syntax error' in G:\Ajax
Coursework\guestbook\php\database.php:134Stack trace:#0 G:\Ajax
Coursework\guestbook\php\database.php(134): PDO->prepare('INSERT INTO
pos...')#1 G:\Ajax Coursework\guestbook\php\class.GuestBook.php(44):
DatabaseHandler->insert(Array)#2 G:\Ajax
Coursework\guestbook\control.php(8): GuestBook->insert(Array)#3
G:\Ajax Coursework\guestbook\control.php(56): insertPost()#4 {main}
thrown in G:\Ajax Coursework\guestbook\php\database.php on line 134
Object.toQueryString is used in convert an object to a query string. So if the server is requiring both $_POST['name'] and $_POST['comment'] to be set, it wont be.
Frankly because you are posting it, I dont think $_GET['name'] or $_GET['comment'] would be set either.
Request.send expects an opject. You are sending it a string. So it should be
Request.send({prop: 'value'}), not Request.send(value).
Do yourself a favor and make a PHP with the following php code, and see what it returns. It may clear this up for you right away. I have a feeling nothing is being sent except for $_GET['action']
<?php
echo '<pre>';
print_r($_GET);
print_r($_POST);
echo '</pre>';
?>
Just in-case anyone stumbles upon this thread looking for an answer:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).post('name=This is a name&comment=This is a comment!');
}
Here I'm using the .post method to POST data.

connecting javascript to a Web API

I am new to the web development world and I would like to be able to connect an HTML page to a web api through . and I was really not successful in this.
I followed this tutorial to be able to make this connection : http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
All I need is to send some inputs from an HTML page to a web api that takes these parameters and returns an object
I am using this code
$.getJSON("api/GeneratorController/setparameters/"+firstparameter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter,
function (data) {
alert(data); //never comes here
}).fail(function (jqXHR, textStatus, err) {
alert("All checks are correct, image was not generated. jqXHR = " + jqXHR.valueOf() + " textStatus=" + textStatus + " Error" + err);
});
it always goes into the fail portion , I attached the alert message that comes out of it
Any Reason why it is doing this ?
#smartmeta (I changed the typo , thanks) I followed your advice and here is the output of the alert (as expected , values that I have inserted are displayed):
Your url needs to start with your domain, not 'api/generatorcontroller/...'. If you are developing locally, something like http://localhost:[port]/api/generatorController/....
Also, webApi maps to url verbs, (get, post, put, delete..), not functions like setparameters, unless you have a [name=setparameters] above your get() function.
Also, I am pretty sure you don't have a route setup to handle the url with all those parameters. What you want to look at, as it seems your using jQuery, is jQuery.get documentation. The second example near the bottom shows where to place parameters. WebAPI will check for them in the body if they are not in the query string. so it would end up looking like:
$.getJSON("http://"+window.location.host+"/api/GeneratorController/setparameters", {parameter1: parameter1, parameter2:parameter2 ...});
Well, the first thing to check is to make sure that your server-side function is returning the values you expect. You can do this with Chrome's developer tools or with the Firebug Firefox extension, and I think IE10 has something equivalent, too. Go to the "net" tab, find the request corresponding to your API call, and take a look at what the server responded with.
Please add the line
alert("api/GeneratorController/setparameters/"+firstparemeter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter)
Then call your script and take the output of the alert into a browser. Then check if your application Handels that route.
By the way I think you have a typo. I guess it should be firstparameter.
I assume you would like to do
"api/GeneratorController?foo=Bar
But when you are new to this, I would suggest that you first try the example like it is. And After that you can start changing setails.
So I found what was the problem with my code
Two things :
1- I shouldn't use the word "Controller" when I call my API ,it should be api/Generator/...
2- the function name needs to start with "get" and not "set" since it "gets" the return value from the api
Thanks everyone!

Categories