jQuery to dynamically toggle between layouts

I was hoping someone could point me in the right direction here. I have a simple media page with three layouts '1', '2' and '3' in a MySql database. When I load the page, I check to see what layout is set in the DB and use the code below to display the correct block of code - this works perfectly. Now, using jQuery, I'd like to be able to have 3 graphic buttons to dynamically toggle between the 3 layouts. What I'd like to achieve is this:

  1. By default, layout 1 is set and icon one is set in the rollover "On" state.
  2. Clicking icon two will dynamically set the $album['layout'] to "2" and update the page, will update the DB from 1 to 2, and change icon one to the rollover 'Off' state and change icon two to rollover 'On' state.
  3. Next time the user visits the page, layout 2 will be set and icon two will be in the rollover 'On' state.

I am relatively new to PHP and I'm just starting to get my head around jQuery - but I understand all the basic concepts - I just can't think how to do this, and I can't seem to find anything online to point me in the right direction to achieve this. Any insight would be much appreciated.


Code used in php to display the correct block of code

<?php

    if ($album['layout'] == 1) {

        //Display Album Layout 1

    } else if ($album['layout'] == 2) {

        //Display Album Layout 2

    } else if ($album['layout'] == 3) {

        //Display Album Layout 3
    }

?>

Answers


It seems like Ajax is the solution for your problem.

Using jQuery, you can easily update the page. You can even switch out the entire style sheet, see this question for more information on that

Using Ajax you can send a call to your server to update the value stored in the database without having to refresh the page. See this question for more information on getting JavaScript to talk with PHP.


Example:

The page that gets displayed let's call it index.php:

<?php require_once("ajax.php"); //include your functions ?>

<html>
  <head>
    <title>Toggle</title>
    <!-- include jQuery -->
    <script 
      src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
      type="text/javascript"></script>
    <!-- include your javascript -->
    <script src="js/functions.js" type="text/javascript"></script>
  </head>
  <body>

    <!-- This div will hold the current album layout -->
    <div id="albumLayoutDiv">
      <?php
        // Gets the album specified in $album['layout'] so it will
        // display on page load. This is defined in ajax.php
        echo GetAlbumLayout($album['layout']);
      ?>  
    </div>

    <input id="layout1" type="button" value="layout 1" /> 
    <input id="layout2" type="button" value="layout 2" /> 
    <input id="layout3" type="button" value="layout 3" /> 

  </body>
</html>

As you can see, GetAlbumLayout isn't defined in here, I have moved it to an external file called ajax.php:

<?php

function GetAlbumLayout($layout) {
  if ($layout == 1) {

    // UPDATE THE DATABASE TO LAYOUT 1
    return $htmlForLayout1; // Display Album Layout 1

  } else if ($layout == 2) {

    // UPDATE THE DATABASE TO LAYOUT 2
    return $htmlForLayout2; // Display Album Layout 2

  } else if ($layout == 3) {

    // UPDATE THE DATABASE TO LAYOUT 3
    return $htmlForLayout3; // Display Album Layout 3

  }
}

// Here is where we look at the values that were passed though
// Ajax. Remember the we used POST, and set the values in 'data'?
// You can see all of that here. You get the values by using 
// $_POST['key'] = value. In this case I am using "action" to 
// determine what PHP function we want to call.

// If 'action' is set from the Ajax call
if(isset($_POST['action']) && !empty($_POST['action'])) {

  $action = $_POST['action'];

  switch($action) {
    // We set action to 'changeLayout' in the Ajax call
    case 'changeLayout': 

      // likewise, we set "layoutNum" to be the number that the
      // user clicked on. We access this value in the same was as
      // the action
      GetAlbumLayout($_POST['layoutNum']);
      break;

    /* 
    case 'anotherAction' : 
      someOtherFunction();
      break; 
    */

    // ...etc... Add more here if you want to perform different
    // ajax calls down the road
  }
}

?>

And now finally for the Ajax call and the Javascript that brings it together functions.js:

// This function fetches the layout number that we want from
// php and updates the "albumLayout" div on the page when
// successful.
function changeLayout(layoutNumber) {

  // Start the Ajax call
  $.ajax({ 
    // set the url to your ajax.php file. This is what this
    // Ajax call will POST to.
    url: '/php/ajax.php', 
    type: 'post',
    // the data can be thought of as the paramaters that you can
    // use on the PHP side of things. Think of it as a dictionary
    // or a map of values. You can pass in anything here that you
    // need in PHP to call a function
    data: {
      action: 'changeLayout', // what we want to do
      layoutNum: layoutNumber    // the layout that was requested
    },
    // After we get the results back from PHP, it is stored as a 
    // string inside of output. Ajax is async - this won't happen 
    // until the results are received from PHP. In this case, I am
    // updating the albumLayout div with the output gathered from
    // the PHP function `GetAlbumLayout(layoutNumber)`
    success: function(output) {
      $('#albumLayout').html(output);
    }
  });
}

/* document ready waits till the DOM is fully loaded to do anything */
$(document).ready(function() {

  // When the user clicks button 1
  $('#layout1').click(function() {
    changeLayout(1);
  });

  // When the user clicks button 2
  $('#layout2').click(function() {
    changeLayout(2);
  });

  // When the user clicks button 3
  $('#layout3').click(function() {
    changeLayout(3);
  });

});

I haven't tested any of the code provided, but it should get you going in the right direction. Basically you initially load the page with the values in the database. The user will click a button on the page to change the layout. You make an Ajax call to the server to UPDATE your database's default value, and return the new HTML to be displayed on the page. Once successful, you update the HTML on your page to the new HTML gathered from PHP.

Best of luck! Let me know if I misunderstood your question.


Sounds like a typical front-end job. Made you a small Fiddle, as the question is a bit too broad for a straight-forward answer.

http://jsfiddle.net/mNbLa/1/


Need Your Help

Triggering asynchronous event in gui thread

java events javafx concurrency javafx-8

TL;DR I'm looking for a way to have one thread raise an event in another

Python Code not Working in Certain Versions

python python-2.7 python-3.x calculator

So for my school, I have to make this script that calculates the tip and tax of a meal. I'm ahead of everyone in my class, so no others have had this issue.