Op submit wil ik twee dingen doen:
- met file_get_contents de content van deze url ophalen
- deze content als input gebruiken voor een javascript functie die vervolgens de json data output in een html table.
Deze twee handelingen lopen niet synchroon. D.w.z. Op submit neemt het javascript niet de gegevens mee die in php bewerkt zijn.
Ik heb geprobeerd om dit probleem op te lossen met json_encode of $_ajax, maar kom hier niet uit. Zou iemand me hiermee kunnen helpen? De code staat hieronder.
html:
<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
<select id="country" name="country">
<option value="GB">UK</option>
<option value="US">USA</option>
</select>
<select id="interval" name="interval">
<option value="daily">Daglijst</option>
<option value="weekly">Weeklijst</option>
</select>
<select id="chart" name="chart">
<option value="most_streamed">Meest gestreamd</option>
<option value="most_viral">Meest gedeeld</option>
</select>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>
spotify.js:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.open("GET", "spotifylist.php", true);
http_request.send();
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.artist_name and jsonObj.track_name.
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=jsonObj.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x.artist_name;
HTML += "</td><td id='song'>";
HTML += x.track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
}
}
}
$("#spotifyform").submit(function(){
loadJSON();
return false;
});
spotifylist.php
[code]
<?php
if($_POST['formSubmit'] == "Submit")
{
$chart = $_POST['chart'];
$country = $_POST['country'];
$interval = $_POST['interval'];
}
$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>