html - Implementing AJAX into a PHP page with multiple selections

209

very new coder here.

I have a page with four select inputs each with two possible options, and when all of the selections have a value and a submit button is clicked a certain song (1 of 16 based on the selections made) will echo out into an audioplayer.

In its current state I have been able to connect to my database which echos out the links and titles for the audio tracks.

My issue is that I want all of the selections to visually retain their option values once the submit button is clicked so that users can see what options they have selected for the current song that is playing.

I've found lots of examples online of implementing AJAX into a page with one selection that activates via an onchange event such as this one from W3 Schools http://www.w3schools.com/php/php_ajax_database.asp, but nothing with multiple selections and a submit button.

Someone from this community helped me out the other day so that the code for the W3 schools example could accommodate a submit button onclick event instead of the onchange on the select input, but with my lack of much fluency with PHP/Javascript I don't really have an idea of how to include multiple selections.

I was hoping someone could take a look at how far I got in my page with multiple selections but no AJAX implemented and explain to me in very simple terms how I could go about including AJAX so that the select options are visible once the submit button has been clicked. If one could even show me a version of my page with AJAX placed with comments to explain the process would be absolutely golden.

Here is my page...

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<link rel="shortcut icon" href="favicon.ico"/>
<title>MoodTunes -- Tunes for your mood</title>
<script src="prefixfree.min.js"></script>
</head>

<body>
<?php

$myDatabase = mysql_connect("localhost","root","root");
if (!myDatabase) die ('Oh dear.' . mysql_error());

if(isset($_GET['submit'])){
mysql_select_db("tunes",$myDatabase);
$volume = $_GET['volume'];
$tempo = $_GET['tempo'];
$complexity = $_GET['complexity'];
$key = $_GET['key'];
$query = "SELECT * FROM music WHERE volumeOption='".$volume."' AND tempoOption='".$tempo."' AND complexityOption='".$complexity."' AND keySignatureOption='".$key."'";
$mydata = mysql_query($query, $myDatabase) or die(mysql_error());
while($row = mysql_fetch_array($mydata)){

echo "<div id='submitContent'>";
echo "<h3><span>Now Playing:</span> " . $row['title'] . "</h3>";
echo "<figure id='audioplayer' style='display:inline-block;'>";
echo "<audio id='audiotrack' controls loop>";
echo "<source src='" . $row['link'] . "'type='audio/mpeg'>";
echo "</audio>";
echo "</figure>";

}
mysql_close($myDatabase);
}

?>

</div>

<header>
    <div>
        <h1>
            <img src="assets/images/logo.png" alt="">
        </h1>
        <h2>Tunes for <span>your</span> mood</h2>
    </div>
</header>

<main>
    <h4>Choose your tune criteria</h4>
    <form>

        <label for="volume"></label>
            <select name="volume" id="volume">
            <option>Select One</option>
            <option value="0" id="loud">heavy</option>
            <option value="1" id="quiet">soft</option>
            </select>
        </label>

        <label for="tempo"></label>
        <select name="tempo" id="tempo">
        <option>Select One</option>
        <option value="0" id="fast">fast</option>
        <option value="1" id="slow">slow</option>
        </select>
        </label>

        <label for="complexity"></label>
        <select name="complexity" id="complexity">
        <option>Select One</option>
        <option value="0" id="complex">complex</option>
        <option value="1" id="simple">simple</option>
        </select>
        </label>

        <label for="key"></label>
        <select name="key" id="key">
        <option>Select One</option>
        <option value="0" id="minor">minor key</option>
        <option value="1" id="major">major key</option>
        </select>
        </label>   
<div id="submitDiv">

<input type="submit" name="submit" id="submit" value="Get My Tune!">
</div>

</form>

</main>

</body>
</html>

Any help would be greatly appreciated. Like I said, I'm still very new to much coding so please answer simply if you can help me out. Thanks.

206

Answer

Solution:

I suggest splitting into 2 files: an HTML file and a PHP file. Keep the PHP separate and call it with an XHR object (Ajax).

music.html

<!-- skipped top stuff -->

<body>

<!-- replace your PHP code with straight HTML -->
<div id='submitContent'>
  <h3><span>Now Playing:</span> <span id="musictitle"></span></h3>
  <figure id='audioplayer' style='display:inline-block;'>
    <audio id='audiotrack' controls loop>
      <source id="musiclink" src='' type='audio/mpeg'>
    </audio>
  </figure>
</div>

<!-- skipped middle stuff -->

<form id="musicform"> <!-- give your form an id -->
  <!-- skipped form stuff -->
</form>

<!-- add script tag to bottom of body -->
<script>

// function to handle music selection
function get_selection () {

    // instantiate music url
    var url = 'music.php'

    // get form values or defaults
    var musicform = document.getElementById('musicform')
    url += ('Select One' == musicform.volume.value)?     '?volume=1':     '?volume='     + musicform.volume.value
    url += ('Select One' == musicform.tempo.value)?      '&tempo=1':      '&tempo='      + musicform.tempo.value
    url += ('Select One' == musicform.complexity.value)? '&complexity=1': '&complexity=' + musicform.complexity.value
    url += ('Select One' == musicform.key.value)?        '&key=1':        '&key='        + musicform.key.value

    // set up XHR object
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    // handle response
    xhr.onload = function () {
        //console.log(this.responseText)
        var music = JSON.parse(this.responseText)
        document.getElementById('musictitle').innerHTML = music.title
        var audio = document.getElementById('audiotrack')
        document.getElementById('musiclink').src = music.link
        audio.load()
        audio.play()
    }
    xhr.send()
}

// hook up music selection function to form submit
document.getElementById('musicform').addEventListener('submit', function(evt){
    evt.preventDefault()
    get_selection()
})

// execute music selection function at least once
get_selection()

</script>

</body>
</html>

music.php

<?php

$myDatabase = mysqli_connect("localhost","root", "root", "tunes");

$stmt = mysqli_prepare($myDatabase
  , "SELECT title, link FROM music WHERE volumeOption = ? AND tempoOption = ? AND complexityOption = ? AND keySignatureOption = ?"
) or die(mysqli_error($myDatabase));
mysqli_stmt_bind_param($stmt, 'ssss', $_GET['volume'], $_GET['tempo'], $_GET['complexity'], $_GET['key']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $title, $link);

mysqli_stmt_fetch($stmt); // assuming only one result
echo '{"title": "' . $title . '", "link": "' . $link . '"}';

mysqli_close($myDatabase);

?>

And I'm using PHP MySQLi prepared statements for database access for security and the fact plain old PHP MySQL functions are deprecated.

367

Answer

Solution:

Disclaimer The object will only be available while the{-code-2}. If you wish to retain the information regardless of the browser being closed, please change to the{-code-3} object instead.


Here's your working jsFiddle example

One of the easiest and quickest ways to retain form input information without even bothering with serverside language is using the functions.

We can capture all of the change events on the form elements and push their values into the . We can then retrieve and apply them to each of the respective inputs on the page reload with very minimal code.

//First, we need to make sure our users support the Storage object.

if(typeof(Storage) !== "undefined") {
    /**
    |     






961
votes

Answer

--- | All of your elements can be selected by the :input selector in jQuery | We will bind to the change function and push to the whenever they are altered. |






648
votes

Answer

--- */ $(':input').change(function(){ .setItem($(this).prop('name'), $(this).val()); }); }

Basically, if the storage is available, we create an event handler that binds to the change event of all of our form elements. Now when they change, we'll have a bunch of keys we can retrieve from the element.

Now, we need to apply those values to our elements on page load.

//make sure we still have Storage available.
if (typeof (Storage) !== "undefined") {
   /**
    |     






435
votes

Answer

--- | We capture each of the input elements below and then check if | we previously had values saved for them. | If not, the default is left selected. |






941
votes

Answer

--- */ $('form *').filter(':input').each(function () { if(sessionStorage.getItem($(this).prop('name'))){ $(this).val(sessionStorage.getItem($(this).prop('name'))); } }); }

Now in the above code we're simply looping over all of our form elements and applying the values that were stored in the sessionStorage to those elements.

Additionally

Let's get you away from the{-code-7} library as it's deprecated, and will be completely removed in future versions of PHP. Let's also focus on sanitizing user input, so you don't have SQL injection vulnerabilities which could have catastrophic side effects.

{-code-8}

Users can still bypass the{-code-9} conditional, so let's add some more sanity checking.

{-code-10}

Now we should check if all those are set at the same time.

{-code-11}

Inside of this conditional, we can then apply our database logic using mysqli's object oriented approach. We'll also use prepared statements to avoid the SQL injection.

{-code-12}
64

Answer

--- | All of your elements can be selected by the :input selector in jQuery | We will bind to the change function and push to the sessionStorage whenever they are altered. |
857

Answer

--- */ $(':input').change(function(){ sessionStorage.setItem($(this).prop('name'), $(this).val()); }); }|||//make sure we still have Storage available. if (typeof (Storage) !== "undefined") { /** |
725

Answer

--- | We capture each of the input elements below and then check if | we previously had values saved for them. | If not, the default is left selected. |
674

Answer

--- */ $('form *').filter(':input').each(function () { if(sessionStorage.getItem($(this).prop('name'))){ $(this).val(sessionStorage.getItem($(this).prop('name'))); } }); }|||mysql_|||$myDatabase = new mysqli('localhost', 'username', 'password', 'database');|||if(isset($_GET['submit'])){|||$volume = isset($_GET['volume']) ? $_GET['volume']: null; $tempo = isset($_GET['tempo']) ? $_GET['tempo'] : null; $complexity = isset($_GET['complexity']) ? $_GET['complexity'] : null; $key = isset($_GET['key']) ? $_GET['key'] : null;|||if(isset($volume, $tempo, $complexity, $key)){ }|||$stmt = $mysqli->prepare('SELECT * FROM music WHERE volumeOption=? AND tempoOption=? AND complexityOption=? AND keySignatureOption=?'); $stmt->bind_param('ssss', $volume, $tempo, $complexity, $key); if($stmt->execute()){ while($row = $stmt->fetch()){ ?> <div id="submitContent"> <h3><span>Now Playing:</span> <?php echo $row['title']; ?> </h3> <figure id="audioplayer" style='display:inline-block;'> <audio id="audiotrack" controls loop> <source src="<?php echo $row['link']?>" type="audio/mpeg"/> </audio> </figure> <?php } }

People are also looking for solutions to the problem: Unable to add user to MySQL database using PHP, error code #1064

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.