I'm having issues with getting this API to work.
I have used the same code with Google Finance API and that works perfectly. The issue is that I can only get a small amount of stocks out, and in the long run, I need to run 12000 stocks through (if possible).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var temp = [];
$(document).ready(function(){
stockInformation();
setInterval(stockInformation, 5000);
});
function stockInformation()
{
$.ajax({
url:"https://api.website.com/public/user/token/stock/SDRL/quote",
dataType:"jsonp",
jsonp:"callback",
jsonpCallback:"quote"
});
var i = 0; var j = 0;var status = "";
quote = function(data){
var output = "<table>"
$.each(data, function(key, value){
if (value.l_cur > temp[j])
status = "<td style=color:green>Up</td>";
else if (value.l_cur < temp[j])
status = "<td style=color:red>Down</td>";
else
status = "<td>Same</td>";
j++;
output += "<tr><td>" + value.t + "</td><td>" + value.l_cur + "</td>" + status + "</tr>";
temp[i] = value.l_cur;i++;
})
output += "</table>";
$("#result").html(output);
}
}
</script>
<div id="result"></div>
This is what the API returns (not with the code above):
{"timestamp":"1503691321","datetime":"2017-08-25 16:02:01 (UTC)","price":"6.17","price change":"0.12","price pct change":"1.98","open":"6.09","volumn":"1852887","low":"6.00","high":"6.22","currency":"USD"}
Many of googles api's limit the number of requests you can make in a given amount of time. Sometimes even as low as 50 per month depending on the api and the type of request. Its doesn't look like there is anything wrong with the way you are using the api in your code.
You could get around that though potentially by paginating. Start with like 30 at a time then when your user clicks a next button or scrolls to the end of the page then go get the next 30.
Related
I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}
I have build a function getuser() in which I recieve json data from php into javascript. I call this function when document gets ready. My problem is that I am also using jquery post for live updation of that record and for that reason I have to call that function getuser() again due to this it shows duplicate result. First when document gets ready socend on jquery post function.
HTML
<!--It has onclick event-->
<button type="submit" class="btn btn-primary modify" onclick="update_user()">UPDATE</button>
JQUERY
//This is function which gets json array from php
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
//This is jquery post. When I click button (in html section) it will get form values and sent to php page
//in return it will call getuser() function again which results of duplicate display of record
$(document).ready(function(){
$('.modify').click(function() {
var gender = '';
if($('.male').is(':checked')){
gender='Male';
}else{
gender='Female';
}
$.post("update.php",
{name: $('.name').val(),gender:gender,city:$('.city').val(),age:$('.age').val(),id:$('.id').val()},
function (data) {
//here is the function call again
getuser();
}
);
});
});
Kindy tell me that is there any way I avoid second call in post function and the record gets update without function call again.I need to avoid duplicate result. Thanks in advance!
First off, you need to read the docs on jquery document ready, and learn the difference between a function reference and actually calling a function. document.ready expects you to pass in a function definition to be called when the page is ready. It doesn't actively tell you if the page is ready, the first way you're calling it. The second way you're calling it is actually correct.
Second, replace $("#output").append with $("#output").html, which will update/replace the contents of that element every time, instead of just adding more and more.
Your if test will always return true because document.ready returns the JQuery object. So, you are always causing the call to getuser() to happen.
You can see the return value from document.ready() here:
console.log($(document).ready());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is an incorrect usage of document.ready(). You don't need to write a test for document.ready, just write a callback function for that event and let the browser do it correctly for you.
Read the docs on document.ready()
Solution:
This:
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
Should be this:
//when document gets ready it will show the record
$( document ).ready(getuser);
Or even:
$(getuser);
As for you getting the results a second time, just overwrite the old results instead of appending them.
This: $("#output").append(...
Should be: $("#output").html(...
All of you thanks for your suggestions. I have found the solution here by just adding $("#tbody").html(''); in getuser() before loop. Here is the code which works fine for me
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
$("#tbody").html('');//newly added
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
All of you thanks again!
this is a complete noob question, but I am brand new to javascript and web development, so please bear with me :)
I have objects in a Parse class that I want to list on a website. I want to iterate through these objects and list them (I am in an html file).
Here is my code:
<script>
Parse.initialize("XXXXXXX");
var Post = Parse.Object.extend("Post");
function getPosts() {
var query = new Parse.Query(Post);
query.find({
success: function(results){
var output = "";
for (var i in results) {
var title = results[i].get("activityTitle");
console.log("ok now");
output += "<div class=\"row container-post\">
<div class=\"col-md-4 col-sm-6\">
<div class=\"post-container\">
<div class=\"post-content no-padding\">
<img src=\"assets/image-portfolio-02.jpg\" alt=\"danish personal blog template\"></div>
<div class=\"post-content\">";
output += title;
output += "</div></div></div></div>";
}
$("#list-posts").html(output);
}, error: function(error) {
console.log("Query Error:"+error.message);
}
});
}
getPosts();
</script>
Once you have your results, literally start building your content. Say we have this on the HTML side:
<div class="results target"></div>
then we can do this on the JS side:
<script type="text/javascript">
Parse.initialize(...);
new Parse.Query(Post).find({
success: function(results) {
buildResultHTML(results);
}
});
function buildResultHTML(data) {
var container = document.querySelector("div.results.target");
data.forEach(function(entry) {
container.appendChild(buildHTMLRow(entry));
});
}
function buildHTMLRow(data) {
// there are a million ways to do this. Usually, you use a templating
// library to make live easier. Let's roll one:
var outer = document.createElement("div");
var img = document.createElement("img");
var url = data.imagelinkwhatever;
// safety first: is this a real http:// or https:// link? If not, DON'T USE IT
img.src = url.indexOf("http") === 0 ? url : "";
var p = document.createElement("p");
p.textContent = data.textwhatever;
// note: also NEVER use .innerHTML if your data can come from "not you".
// It's an instant XSS exploit waiting to happen. See below.
outer.appendChild(img);
outer.appendChild(p);
return outer;
}
</script>
But, as the code says: you typically want to use a templating library instead, so you don't have to worry about things like messy JS creation of DOM elements, user content security, etc.
And security is important: if that Parse result can give you something like this:
{
imgurlwhatever: "javascript:alert('lol')",
textwhatever: "<script>alert('lol');</script>"
}
then your page, if it uses blind img.src=... and p.innerHTML=..., will happily execute that JS. That sounds silly, but alert('lol') is a placeholder: if we can get that to run, we can also get things like "call another site's url using an XHR, with the content of document.cookies as url query parameters" and suddenly shit gets real(tm).
ok, I finally figured it out. Here is the code:
<script>
Parse.initialize("XXXXXXXXXXXXXX");
var Post = Parse.Object.extend("Post");
function getPosts() {
var query = new Parse.Query(Post);
query.find({
success: function(results){
var output = "";
for (var i in results) {
var title = results[i].get("activityTitle");
console.log("ok now");
var img = ""
var file = results[i].get("Bild");
var url = file.url();
img = "<img src='"+url+"'>";
output += "<div class=\"container\">";
output += "<div class=\"row\">";
output += "<div class=\"col-md-4\">";
output += "<div class=\"post-container\">";
output += "<div class=\"post-content no-padding\">";
output += img;
output += "</div>";
output += "<div class=\"post-content\">";
output += title;
output += "</div";
output += "</div>";
output += "</div>";
output += "</div>";
output += "</div>";
}
$("#list-posts").html(output);
}, error: function(error) {
console.log("Query Error:"+error.message);
}
});
}
getPosts();
</script>
And just above the javascript code, in the HTML, I just put:
<p id="list-posts">
</p>
This gets the objects from parse, and lists them out for me in the format I wanted. thanks for the suggestions though. For anyone else who may need help in the future with something like this, this video (and others by the author) really helped me: https://www.youtube.com/watch?v=_fxh825Bnpg&index=4&list=PLoN_ejT35AEhbFswEKW36LxzyXJs7xCWS
I am trying to make an image take a value in as a source, after the image tag (and a related radio button) has been created using JavaScript. I have discerned the following from testing and alert outputs:
If the image src is provided at the creation of the image tag using an exact filepath, it will show the image correctly (e.g. src='images/0.jpg'). However, this is not helpful since I need it to work for any given image, not a specific one.
If the image src is provided at the creation of the image tag using a variable containing a filepath, it fails to generate the image tag or the radio button at all (e.g. src='" + result + '").
NOTE: The last example is not present in the code below. The result was found by moving the '$.post' section to the line directly under the 'out +=' line within the for loop.
If the image src is left blank at the creation of the image tag, the image tag and radio button are created, though the image is blank as expected. If I then try to use 'getElementByID(imgID).src' to change the image source after this, it fails to do anything. ('imgID' here is an example, not what the code says).
On top of the above, using alerts and dumping info into divs indicate that the comicID is being correctly posted, and the filepath of the image src is definitely being found, and is being copied into the variable 'result' correctly, even one line before the creation of the tag or the attempt to edit it using 'getElementById'.
At this point I'm stumped, I don't know what could logically be stopping the src from reading in.
--
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
tempID = (arr[j].comicID);
$.post("getCover.php", {comicID:tempID}, function(result)
{
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
);
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print_r($row["pageLocation"]);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
To my knowledge, loadList.php is working perfectly, so I didn't list its code to keep things relevant.
I copied your code and tweaked it a little so I could run it without the web services and it works great. Here is the HTML page I created:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
// JSON parsing for 'loadComic'.
function loadComicJSON()
{
var arr = [{comicID: 1},{comicID: 2},{comicID: 3}];
var result = "monkey.jpeg";
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
var imgSrc;
tempID = (arr[j].comicID);
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
}
}
</script>
</head>
<body>
<div id="loadList"></div>
<button onclick="loadComicJSON()">Try it</button>
</body>
</html>
As you can see, I created an array of JSON objects that hold the comicID and am statically creating the image as 'monkey.jpeg'.
The code works so there is either an issue with the 'response' that you pass into your loadComicJSON method or the result from your POST method.
Add a couple of console.log statements and look at the two values I mentioned and you will likely see the issue.
Solved the issue myself. It turned out that the $.post needed to be $.get and that it needed to technically be outside of a loop (i.e. in its own function) to work properly. Works fine now after that and a couple minor tweaks.
I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.