John Peeterson
John Peeterson

Reputation: 81

Load dialog contents and pass variables

For several days, I cannot figure out how to design a solution for the following issue: I have a lot of items (around 1300) stored in database, each has its own "id", some "name" and a third property "enabled".

I would like to show on the same page to the user links to (all) the dialogs. Dialogs then shall show the "name" and allow the user to select OK/Cancel (i.e. enable/no action). (Changing of "enable" is made through a file some_file.php, which is already working properly and is not subject of this question.)

I have found similar questions like this or this but any of them so not need to pass variables between php and javascript like my dialogs.

I am not able to solve the problems stated below in comments:

javascript:

$(function(){
  $('#dialog').dialog({
    autoOpen: false,
    width: 600,
    modal: true,
    buttons: {
        'Cancel': function() {
            $(this).dialog('close');
        },
        'OK': function() {
                $.ajax({
                    url: 'some_file.php',
                    type: 'POST',
                    data: 'item_id=' + id,// here I need to pass variable, i.e. $line["id"] from the php loop
                });
                $(this).dialog('close');
        }
    }
});
$('.link_dialog').click(function(){
    $('#dialog').dialog('open');
    return false;
  });
});`

html + php:

<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// not sure here how to pass the "text" to some javascript function
    if ($line["name"]=="") {
      text = "Number ".$line["id"]." does not have any name.";
    } else {
      text = "The name of number ".$line["id"]." is ".$line["name"];
    }
}
?>
<a href='#' class='link_dialog'>Dialog 1</a>
<a href='#' class='link_dialog'>Dialog 2</a>
<a href='#' class='link_dialog'>Dialog 3</a>

<div id='dialog' title='Name' style='display: none;'>
    // not sure here how to extract the "text" from javascript function created above
</div>

jsfiddle demo (of course, not working)

If somebody sees the point, I would really appreciate your help. You can update my jsfiddle.

Upvotes: 1

Views: 2918

Answers (2)

ConnectedSystems
ConnectedSystems

Reputation: 932

What you are trying to do is called dynamic content loading. My last example does this by inserting the necessary data (as JSON) and generating the content directly on the page.

This next method may not be suitable for what you are trying to do, but may be useful later.

Instead of retrieving the data and generating the content on the page itself, we use an external page to provide content for us. This reduces server load by only providing the needed content, and can increase user interactivity (because the page doesn't have to load up all the information before it gets displayed to the user). See [here][1] for further information about AJAX.

Advantages: Separating the content generation from the page a user accesses. What if you need to show the same/similar content elsewhere on the website? This method allows you to reuse the code for multiple use cases.

You can even combine this with the previous method. Just use a separate PHP file to generate your dialog content and links en masse (rather than per click as shown below), which gets called and loaded in on $(document).ready()

Per click example:

Generate the content per click

A separate PHP file - dialog_text_generator.php:

<?
  //DON'T ACTUALLY DO THIS. ALWAYS SANITIZE DATA AND AVOID USING mysql_ prefixed
  //functions (use mysqli or PDO). 
  //This is just to illustrate getting data from the DB
  $item_id = $_REQUEST['item_id'];
  $query = "SELECT * FROM `stuff` WHERE item_id = $item_id";
  $query_results = mysql_query($query, $db_connection);

  $num_matches = count($query_results);
  $text = array();
  for($i = 0; $i < $num_matches; $i++) {
    $current_item = $query_results[$i];

    //Print out content
    //replace 'name' with whatever field your DB table uses to store the item name
    if($current_item['name'] == '') { 
      echo "<p>Number $item_id does not have any name.</p>";
    } else {
      echo "<p>The name of number ".$item_id." is ".$current_item['name']."</p>";
    }
  }
?>

Javascript in your main page:

<script>
$('.link_dialog').click(function() { 
      //On user clicking the link
      var link = this;

      //Get link ID
      var link_id = link.attr('id').split('-'); //Split string into array separated by the dash
      link_id = link_id[2]; //Second array element should be the ID number

      //autoOpen set to false so this doesn't open yet, we're just defining the buttons here
      $('#dialog').dialog({
        autoOpen: false, 
        buttons: {
          "Cancel": function() {
             $(this).dialog('close');
          },
          "OK": function() {
             $.ajax({
                      url: 'some_file.php',
                      type: 'POST',
                      data: 'item_id=' + link_id, //Use link id number extracted above
                    });
                    $(this).dialog('close');
          }
        }
      }); 

      //Load content from PHP file into dialog div and open the dialog
      //Obviously use the actual path to dialog_text_generator.php
      jQuery('#dialog').load('dialog_text_generator.php?item_id='+link_id).dialog('open');

      return false;
    });

</script>

Upvotes: 0

ConnectedSystems
ConnectedSystems

Reputation: 932

In PHP:

<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if ($line["name"]=="") {
      $text[$line["id"]] = "Number ".$line["id"]." does not have any name.";
    } else {
      $text[$line["id"]] = "The name of number ".$line["id"]." is ".$line["name"];
    }
}

/***
 * Give each link unique ID (I've used 'dialog-n')
 * Advantage to creating link dynamically: 
 * (what if the number of dialogs changes in the future?)
 * Also suggest that you wrap these in a div
 */
$num_links = count($text);
for($i = 1; $i <= $num_links; $i++) {
    echo "<a href='#' id='dialog-$i' class='link_dialog'>Dialog $i</a>";
}

HTML:

<div id='dialog' title='Name' style='display: none;'>
</div>

In Javascript:

    var DIALOG_TEXT = <?php echo json_encode($text); ?>; //Pass text via JSON

    $('.link_dialog').click(function() { 
      var link = this;

      //Get link ID
      var link_id = link.attr('id').split('-'); //Split string into array separated by the dash
      link_id = link_id[2]; //Second array element should be the ID number
      var msg_text = DIALOG_TEXT[link_id]; //Retrieve associated text

      //Insert text into dialog div
      $('#dialog').text(msg_text); //Use .html() if you need to insert html

      $('#dialog').dialog({
        buttons: {
          "Cancel": function() {
             $(this).dialog('close');
          },
          "OK": function() {
             $.ajax({
                      url: 'some_file.php',
                      type: 'POST',
                      data: 'item_id=' + link_id, //Use link id number extracted above
                    });
                    $(this).dialog('close');
          }
        }
      }); 
      return false;
    });

I have not tested the above, you will probably have to modify for your needs.

OPTION 2:

If you intend to have the dialog content generated dynamically (e.g. only when the user clicks the link), you can do the below

jQuery('#dialog').load('content_generator.php?item_id=**[your id]**').dialog('open'); 

where 'content_generator.php' takes the given id and outputs the appropriate text, which ".load()" inserts into the dialog.

Option 2 is based on the answer given by Sam here

Upvotes: 2

Related Questions