2

I've got really ambitious problem today as I want to achieve something ridiculously stupid but satisfying. Basically, I do have a database with data for gym exercises

CREATE TABLE IF NOT EXISTS `gp_progs` (
  `prog_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `exer` varchar(250) NOT NULL,
  `pic` varchar(15) NOT NULL,
  PRIMARY KEY (`prog_id`),
  UNIQUE KEY `prog_id` (`prog_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

--
-- Dumping data for table `gp_progs`
--

INSERT INTO `gp_progs` (`prog_id`, `name`, `exer`, `pic`) VALUES
(1, 'ABS', 'TO DO ABS YOU NEED TO DO THIS AND THAT', 'abs.jpg'),
(3, 'Arms2', 'this is what we want', 'abs.jpg'),
(7, 'Biceps', 'curls', 'abs.jpg');

I have treated it after digging the code for many hours with this code in PHP

$jsondb = "data/prog.json";
$q = "SELECT * FROM gp_progs";
$r = @mysqli_query ($dbc, $q);
/*$json = array();
while ($row = mysqli_fetch_assoc($r)){
    $json[] = $row;
    }

$jsondata =  json_encode($json, JSON_PRETTY_PRINT);
if(file_put_contents($jsondb, $jsondata)) {
            echo 'Data successfully saved';
        }

It gave me a json file from which I realy want to build AJAX functional app like this one. JS:

$(function() {                                    // When the DOM is ready

  var times;                                      // Declare global variable
  $.ajax({
    beforeSend: function(xhr) {                   // Before requesting data
      if (xhr.overrideMimeType) {                 // If supported
        xhr.overrideMimeType("application/json"); // set MIME to prevent errors
      }
    }
  });

  // FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
  function loadTimetable() {                    // Declare function
    $.getJSON('data/events.json')              // Try to collect JSON data
    .done( function(data){                      // If successful
      times = data;                             // Store it in a variable
    }).fail( function() {                       // If a problem: show message
      $('#event').html('Sorry! We could not load the timetable at the moment');
    });
  }

  loadTimetable();                              // Call the function


  // CLICK ON THE EVENT TO LOAD A TIMETABLE 
  $('#content').on('click', '#event a', function(e) {  // User clicks on event

    e.preventDefault();                                // Prevent loading page
    var loc = this.id.toUpperCase();                   // Get value of id attr

    var newContent = '';                               // Build up timetable by
    for (var i = 0; i < times[loc].length; i++) {      // looping through events
      newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
      newContent += '<a href="data/descriptions.html#';
      newContent += times[loc][i].title.replace(/ /g, '-') + '">';
      newContent += times[loc][i].title + '</a></li>';
    }

    $('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page

    $('#event a.current').removeClass('current');       // Update selected item
    $(this).addClass('current');

    $('#details').text('');                             // Clear third column
  });

  // CLICK ON A SESSION TO LOAD THE DESCRIPTION
  $('#content').on('click', '#sessions li a', function(e) { // Click on session
    e.preventDefault();                                     // Prevent loading
    var fragment = this.href;                               // Title is in href

    fragment = fragment.replace('#', ' #');                 // Add space after#
    $('#details').load(fragment);                           // To load info

    $('#sessions a.current').removeClass('current');        // Update selected
    $(this).addClass('current');
  });


  // CLICK ON PRIMARY NAVIGATION
  $('nav a').on('click', function(e) {                       // Click on nav
    e.preventDefault();                                      // Prevent loading
    var url = this.href;                                     // Get URL to load

    $('nav a.current').removeClass('current');               // Update nav
    $(this).addClass('current');

    $('#container').remove();                                // Remove old part
    $('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
  });

});

HTML:

<section id="content">
      <div id="container">
        <h2>Upcoming Events in Yorkshire</h2>

        <div class="third">
          <div id="event">
            <a id="sh" href="sh.html"><img src="img/sheffield.fw.png" alt="Sheffield, South Yorkshire" />Sheffield</a>
            <a id="hu" href="hu.html"><img src="img/hull.fw.png" alt="Hull, East Yorkshire" />Hull</a>
            <a id="ls" href="ls.html"><img src="img/leeds.fw.png" alt="Leeds, West Yorkshire" />Leeds</a>
            <a id="yk" href="yk.html"><img src="img/york.fw.png" alt="York, West Yorkshire" />York</a>
          </div>
        </div>
        <div class="third">
          <div id="sessions">
            <p>Select an event from the left</p>
          </div>
        </div>
        <div class="third">
          <div id="details"></div>
        </div>

      </div><!-- #container -->
    </section><!-- #content -->


    <script src="js/jquery-1.11.0.min.js"></script>
    <script src="js/events.js"></script>

So the result I want to see is to click on the group of exercises e.g. Arms, which will open next exercises e.g. Biceps and then onclick I want to see programme with pictures. But I cannot find out how to change JS so it will give me what I want. Spent on it already 13 hrs and still cannot find anything online.

If something is not clear please let me know as I am still learning how to use overflow.

Thanks in advance!

This is for PHP website with an use of JS, MySQL, Google API and HTML of course.

Edit: If it was not too clear, I want to get MySQL data to JSON (which I have done already)

[
{
"prog_id": "1",
"catg": "chest",
"name": "Chest",
"exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)",
"pic": "abs.jpg"
}
]

And now I want to use it in AJAX in way of: on page I want to see Groups - 'catg' which on click will open list next to group on the same page with Muscle to train 'name' which afterwards open last list next to previous also on the same page showing Descirption 'exer' and Picture/s 'pic'. Just like in the picture below: List to create with exercises

2
  • WARNING: Using the error-suppressing YOLO operator (@) obscures problems with your code and makes debugging issues like this a whole lot more complicated. That's a tool of last resort and should only be used in exceptional circumstances. You should display an error message for the user, log a problem, initiate some kind of retry, or all of these things in conjunction. Commented Mar 28, 2019 at 22:40
  • Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and ideally should not be used in new code. Commented Mar 28, 2019 at 22:40

2 Answers 2

2

I think your problem is that you don't know how to get data from MySQL to JSON in PHP, then get that JSON into Javascript in a form that lets you manipulate it easily.

Here's how I do it. The key here is the use of str_replace.

PHP, using my own SQL() function to retrieve the result set via fetch_all(MYSQLI_ASSOC):

$subcategorydata =
  SQL("select * from subcategoryoptions order by category, subcategoryoption");
$subcategories = 
  str_replace('\\"','\\\\"',
  str_replace("'","\'",
  json_encode($subcategorydata)));

Javascript (direct rather than via ajax in my case):

var subcategories = '<?php echo $subcategories; ?>';
var jsonSubcategories = JSON.parse(subcategories);
for (var row in jsonSubcategories) { ....

EDIT: Additional code to load 2 layers, toggling the display of the lower level on/off according to user clicks. This version assumes you've pulled all the data out of MySQL in one go (I've just hard-coded it) - you would probably want to use ajax to load stuff dynamically in practice - and my code is definitely not optimal, but it should do the job.

Main div into which the data is loaded is followed by the javascript to load it. Note the hide(), show(), toggle() and set() functions and the onclick.

<div id=main></div>

<script>
function set(div, value) {
    document.getElementById(div).innerHTML = value;
}

function hide(div) {
    var x = document.getElementById(div);
    x.style.display = "none";
}

function show(div) {
    var x = document.getElementById(div);
    x.style.display = "block";
}

function toggle(div) {
    var x = document.getElementById(div);
    if (x.style.display === "none") { show(div); } else { hide(div); }
}

var json='[{"heading":"This is the first heading","detail":"This is the first detail"},{"heading":"This is the second heading","detail":"This is the second detail"}]';
var jsonData = JSON.parse(json);

var html = '';
for (var row in jsonData)
  {
  html += '<div id=hdr' + row + ' onclick=toggle(\'dtl' + row + '\')>';
  html += '<b>' + jsonData[row].heading + '</b></div>';
  html += '<div id=dtl' + row + '>' + jsonData[row].detail + '</div>';
  }
set('main','Click on the headings to toggle the detail<br>' + html);
for (var row in jsonData)
  {
  hide('dtl' + row);
  }
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer. The problem is that I already do have JSON file which creates my data as this ``` [ { "prog_id": "1", "catg": "chest", "name": "Chest", "exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)", "pic": "abs.jpg" } ] ``` But then I don't know how to recreate the JavaScript so it shows it in groups that can work like a list of 3 on website (Group name (click)>Muscle part (click)>Description. I think I got lost at this point badly.
Sorry, but that was really not clear from the question - not sure why you referred to the mysql aspect at all if that is not part of your problem. Are you, therefore, really after creating selective divs and links from your json? I can add a bit of example javascript that does that, if it's any use?
Sorry if it was not clear, but I am sure I said I have got a PHP code to convert mySQL data to JSON, it is just the problem I don't know what to do after. The example I was given (events.js) is using JSON, HTML and XML, but I am sure I cannot do that same way from MySQL as it would be too complicated. If I am wrong then please tell me how, so I will do that this way and just change the values in JS script. I am not going to lie, this is my project for final year and I meant to work in a group but was left out at last minute so I want to focus on functionality rather than appearance Thanks
My problem is that I don't understand JQuery, but do you want to load all the divs and have the user click on a top level entry to toggle the lower levels on/off? Or do you want to link to a new html page?
Okay, I might show what I want to do I am not good at explanation of that stuff yet, Video here It is definitely in divs and then CSS work on it, which I could work out probably but I do not have a clue how to export the data appropriately
|
1

you have the name of the image already in the records and you should also know, were on the server the images can be found.

You can combine this knowledge and forge a URI from path and filename

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.