Lazy json data fetching with JS and PHP - javascript

I've been looking for a way to lazy load JSON data from an API (since I'm making about 5+ API calls a page)
and I found this: https://github.com/rpnzl/jquery-lazyjson/tree/v1.0
Seem like a nice class but since I'm using PHP all over my website and the call made by this class is with JavaScript, I have no idea how to combine it with my PHP code to make my website loads "by parts".
My goal is to load fast what's possible, then load dynamically each API call one by one to make website runs smoother.
I would like to hear any ideas for handling multiple API calls and fetching the data dynamically.
This is how I'm fetcing my data right now. all PHP and about 7 seconds of loading:
//Get the match!
$matches = $data->getMatchHistory($playerId,$characterId); //Returns an array of each match found
if ($matches == 0)
{
//Todo when user not in game
echo '<div class="alert alert-danger"><h2>We\'re sorry..<br/>There are no matches for this player with '.$playerId.'</div>';
} else {
for($i=0;$i<sizeof($matches)-1;$i++)
{
$match[$i] = new Match();
$match[$i]->matchId = $matches[$i]['matchId'];
$match[$i]->charName = $data->getCharacterName($matches[$i]['character']);
$match[$i]->stats = $data->getMatchStats($match[$i]->matchId); // Makes another API call and returns the match statistics. One Match = 2 API calls
}
?>
<h2><?=$playerName?> Match History</h2>
<?php
for ($i=0;$i<sizeof($matches)-1;$i++)
{
?>
<!--ALOT OF HTML,CSS, AND data fetching this way:-->
<?=matches[$i]->someData;?>
<?php
}
?>

You might as well use PHP to decode and get JSON from API calls.
$JSON = file_get_contents("API-URL.json");
If we know that the file_get_contents returns a page to a variable (in this case, a JSON string), we can then decode the received JSON using PHP.
$Array = json_decode($JSON, 1);
Let's say you've got a json string of {"playerid": 1298134, "gender": "male"}, you could access these via $Array["playerid"] and $Array["gender"], and they would return the variable.
The same goes if you have a array inside the JSON, eg {"playerid": 1298134, "gender": "male", "personal": {"fname": "Kieran", "lname": "Cross"}} could be accessed as $Array["playerid"] and $Array["personal"]["fname"]
If you wish to decode the API at the top of your page, quickly, you can easily do
$Array = json_decode(file_get_contents("API-Page.json"), 1);
You can read more on this here, on the PHP documentation.

Related

How to retrieve content in PHP from external JavaScript

I have an external JavaScript file, I would like to display array content in my PHP page. How can I display the content by loop. I tried to display the content using following code. But Failed.
<?php
ini_set('allow_url_fopen', 'On');
$feed = file_get_contents("https://example.com/media-list.js");
$array = json_decode($json);
var_dump($array);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
?>
media-list.js content
var contents = {
"0W7EHsR8":{
"attachmentCode":"0W7EHsR8",
"title":"title1",
},
"vciym7Zb4":{
"attachmentCode":"vciym7Zb4",
"title":"title2",
},
"XlKBM6":{
"attachmentCode":"XlKBM6",
"title":"Title3",
}
};
I would like to display content like
Title is "title1" .
Title is "title2".
You are trying to use json_decode() on a Javascript Array. JSON and Javascript are two different things.
You need to convert your contents array to JSON, save it in a different file (contents.json for example) and load that file with file_get_contents.
If you need to do this only once you can do something like
var contents = {
"0W7EHsR8":{
"attachmentCode":"0W7EHsR8",
"title":"title1",
},
"vciym7Zb4":{
"attachmentCode":"vciym7Zb4",
"title":"title2",
},
"XlKBM6":{
"attachmentCode":"XlKBM6",
"title":"Title3",
}
};
console.log(JSON.stringify(contents));
and copy the result from the console (click CTRL+Shift+I to open it).
JSON.stringify() takes a Javascript array and turns it into a JSON string.
for this small array the JSON equivalent is
{"0W7EHsR8":{"attachmentCode":"0W7EHsR8","title":"title1"},"vciym7Zb4":{"attachmentCode":"vciym7Zb4","title":"title2"},"XlKBM6":{"attachmentCode":"XlKBM6","title":"Title3"}}
If you intend on making this dynamic (say, loading all attachemnts from a database) you can create a php file that loads that data into an array and returns it into proper JSON using json_encode(). Loading that file with file_get_contents and using json_decode like you are doing now should do the trick.

How to get MySQL query result returned using $.ajax

i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.

I can't get a value from a PHP array...?

I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?

Using YouTube API to get all comments from a video with the JSON feed

I'm using the YouTube API to get comments for a video with a parameterized query like the following:
http://gdata.youtube.com/feeds/api/videos/theVideoID/comments?v=2&alt=json
The problem with this is that the maximum number of results you can get per query is 50. I want to get every comment. I'm currently using the start-index and max-results parameters to solve this. I had a bit of trouble doing iterations of 50 at a time because sometimes the iteration would have a start-index above the number of comments and I couldn't figure that out, so I just tried to work out one at a time. It may be better to do 50 at a time, so let me know if that is the better solution. For now:
I'm using PHP to get the amount of comments:
<?php
$video_ID = 'gT2HYxOdxUk';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$commentCount = $JSON_Data->{'entry'}->{'gd$comments'}->{'gd$feedLink'}->{'countHint'};
?>
And then I'm calling a JavaScript/jQuery function to load all comments into an array. For testing, it prints them into a div. For starters, here's how I'm calling the function:
<body onLoad="loadComments('<?php echo $commentCount; ?>', '<?php echo $video_ID; ?>')">
Next, the actual function:
function loadComments(count, videoID) {
for(i = 1; i <= count; i++) {
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos/" + videoID + "/comments?v=2&alt=json&max-results=1" + "&start-index=" + i,
dataType: "jsonp",
success: function(data){
$.each(data.feed.entry, function(key, val) {
comments.push(val.content.$t);
$('#commentOutput').append(val.content.$t + '<br>'); //Just for testing purposes.
});
}
});
}
}
The problem is that it is really iffy. When I use the count variable as the terminating part of the for loop like this, it always gets like, for example, 45 out of 211 comments. If I manually enter 211, it will go to around 195. If I put in a low number, like 1-15, it pretty much always gets them all. 20+, it's never right.
I need to figure out how to get this to consistently get all the comments of a given video by taking advantage of the max-results and start-index parameters. Thanks!
I just came across this question and I notice that its been quite some time when this was asked. But since nobody answered it yet, I think I should do that.
What you should ideally do is, use Youtube's PHP API (using Zend_GData) and use the following code in PHP:
<?php
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
$yt->setMajorProtocolVersion(2);
$video = parse_url("http://www.youtube.com/watch?v=K-ob8sr9ZX0");
parse_str(urldecode($video['query']), $query);
$videoId = $query['v'];
$commentFeed = $yt->retrieveAllEntriesForFeed($yt->getVideoCommentFeed($videoId));
foreach ($commentFeed as $commentEntry) {
echo "Full text: " . $commentEntry->content->text . "<br />";
}
The key element here is the retrieveAllEntriesForFeed() method.
Instead of echo-ing all the comments, you can construct a JSON and send it back to the waiting Javascript.
It does not use the max-results or start-index, but does the job well without them.
Use the 'orderby' parameter of the api and set it to 'published' to retrieve almost all the comments.
https://gdata.youtube.com/feeds/api/videos/<videoID>/comments?max-results=50&alt=json&orderby=published
You can still use the start-index parameter to loop through the comments but it is not a good idea.
From the documentation:
API responses use tags to identify pagination links for the previous and/or next page of entries in a feed. To avoid pagination problems, we recommend that you use these links to enable users to link to different pages of API results.
If a feed contains a previous page of results, the API response will contain a tag with a rel attribute value of previous.
If a feed contains a next page of results, the API response will contain a tag with a rel attribute value of next.
https://developers.google.com/youtube/2.0/reference#Paging_through_Results
This way you won't get any nested feeds. To get the next set of results simply use the link given on the previous page of results! Hope this helps. It worked for me!

jQuery $.ajax to pass multidimensional array to PHP

I am using jQuery and PHP to write JSON data to my server. I'm processing a decent amount of repeating numeric data (~.75kb), so I want to pass the data to PHP in the form of a multidimensional array.
At the moment I cannot manage to get the data to PHP in a form that it can recognize. I've tried various combinations of sending/receiving as arrays and objects with no success.
The best case scenario would be one in which I pass a the array to the PHP and the PHP converts it to a readable form. I'd rather not use associative arrays or any serializing on the part of the Javascript.
Code... This is giving me a 500 internal server error, which no longer occurs if I omit the passed data variable. (I'm not yet using $data in the php file yet because I know it's not working.)
function generateData() {
// code here
return [ one[ sub_one[], sub_two[] ], two[], three[], four[] /* Etc... */ ]
}
function saveData() {
$.ajax({
url: "scripts/save.php",
data: {
"area":"testing",
"location":"testing",
"name":"testing",
"data":generateData()
}
});
}
<?php
$area = $_GET['area'];
$location = $_GET['location'];
$name = $_GET['name'];
$data = $_GET['data']);
# Performing operations with variables...
echo 1;
?>
Thanks for any help you can offer.
Found a solution:
"data": {
data: generateCellData()
}
The above code passes data as an object to PHP, whereby I can access the original array as $data("data"). I'm still somewhat baffled by why this works when I'm already passing the data and other parameters as an object.

Categories