简体   繁体   中英

Generate json with url built from form

I'm trying to create a form that is capable of generating multiple urls, depending on the input by the user. The created url has a json extension. A php file is used to get the contents of that url. This php file has to have the same contents as the inputted url has. This php file is used as input for a javascript/jquery file.

In this file I'm trying to convert the json code to an html table. This is done by an http_request. The table has to be outputted in a div on the html page. However my code doesn't work due to errors I can't find. I've already looked at simular questions at stackoverflow and google, but could find the fix that made my code working.

I'm applying this code to spotify lists. This is the code I already have:

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[i].artist_name;
        HTML += "</td><td id='song'>";
        HTML += x[i].track_name;
        HTML += "</td></tr>";
          }
        HTML += "</tbody></table>";

        document.getElementById("spotifylist").innerHTML = HTML; 

      }
    }
 }

$("#spotifyform").submit(function(){
    loadJSON();
    return false;
});

spotifylist.php

<?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;
?>

What currently goes wrong is that the php file is loaded when I press the submit button. This file contains the right json information. However this json isn't converted to a html table.

I would really appreciate it, if anybody could help me fix this problem

If you want the spotifylist div to load in the data when you press submit, you have to prevent the page from redirecting.

Make the form action:

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>

And if possible, your input values (if you have any within the form tags):

"<?php echo $_POST['value']?>"

If you can, place your HTML code within a PHP file which executes everything from spotifylist.php.

There are a couple of problems in my guess.

You send your Form to the spotifylist.php which grabs an file and sends something back to the html. Probably JSON but where did you handle that data? Maybe some Javascript which does something with that "string" that your php sends back?

And your loadJSON sends (whenever) a GET Request to the same php but without parameters or something. So your php run into an error because there obviously no POST variables set, so your variables inside your if condition will never set ergo your data which comes back again?!? with errors

You should first get clear which technique you want to use.

It seems to me as you would take a little of both.

    There are multiple ways to get information from an external server:

  • httprequest - not recommend, because of bad user experience.
  • file_get_contents - usually easy, but in this case it requires a lot of data handling. Php works server-side and javascript works client-side. It requires a lot more work to let these two work together.
  • $.ajax - in this case the best solution, because it doesn't require any php and $.ajax is able to directly parse the json data. Because the data is requested from an external site, you have to change the datatype to jsonp and perform a callback function.

  • It is very easy to transfer the data from the form to javascript:

    // Automatically call this function when the page loads.
    window.onload = function loadJSON()
    {
      // The HTML input of the form that is the input of this javascript document
      var country2 = document.getElementById("country");
      var chart2 = document.getElementById("chart");
      var interval2 = document.getElementById("interval");
    

    Build the url with the selected parameters on submit:

    // Call the function when the form is submitted
      $("#spotifyform").submit(function(e)
      {
        e.preventDefault(); // to prevent the page from reloading
    
        // Save the choice of the <select> country in a variable named country2
        var country = country2.options[country2.selectedIndex].value;
        var chart = chart2.options[chart2.selectedIndex].value;
        var interval = interval2.options[interval2.selectedIndex].value; 
        var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
    

    Then get the right data and parse it directly with the json native parser.

    // Get the data from the site and save this into the variable 'json'
        $.ajax
        ({
          'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
          'dataType': 'jsonp', // Cross site request via jsonp
          'error': function(xhr, status, error){ alert(error.message); },
          'success': jsonParser // call function
        }); // $.ajax  
    
      }); // $("#spotifyform").submit(function(e)
    } // window.onload = function loadJSON()
    

    Then do with the data whatever you want. You don't need to do an httprequest and you don't have to parse the data anymore.

    function jsonParser(json) 
    {
      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=json.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[i].artist_name;
        HTML += "</td><td id='song'>";
        HTML += x[i].track_name;
        HTML += "</td></tr>";
        }
      HTML += "</tbody></table>";
      document.getElementById("spotifylist").innerHTML = HTML; 
    } // function jsonParser(json)
    

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM