1

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.

Community
  • 1
  • 1
John Peeterson
  • 71
  • 1
  • 12

2 Answers2

2

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

Community
  • 1
  • 1
ConnectedSystems
  • 892
  • 10
  • 19
  • Takuya, first of all thanks for suggestions! I am only concerned about the content of the dialog. The dialog itself should contain the customized message `Number ".$line["id"]." does not have any name.` or `The name of number ".$line["id"]." is ".$line["name"]` which you instead allocated to the text of the link. May you suggest how to solve that? – John Peeterson Jul 07 '14 at 20:45
  • I made a comment earlier this morning, but it seems to have disappeared. In any case, please see updated answer (which I've since edited to make things a little clearer). – ConnectedSystems Jul 08 '14 at 07:45
  • Thanks, @Takuya, I have been testing it for a while and it is perfect! – John Peeterson Jul 12 '14 at 09:22
  • Nevertheless, may I ask you how do you solve passing variables from the page loaded into the dialog to the dialog script (under option 2 above)? – John Peeterson Jul 12 '14 at 17:15
0

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>
ConnectedSystems
  • 892
  • 10
  • 19
  • I assume you are replying to my query above regarding passing variables from the page loaded into the dialog to the dialog script. What you propose is to load external page to the dialog. There is no interaction between content of the loaded page and the dialog. Imagine situation in which I would like to show a text field in the dialog (which will be provided by dialog_text_generator.php). The user would fill in some text in the field. Then we need to have the text from that text field to use in the script within the $('#dialog').dialog section. – John Peeterson Jul 13 '14 at 17:19
  • @JohnPeeterson You can do that. As you say, dialog_text_generator.php provides the text field (with an input name or div class), you just have to include the necessary JScript to handle the text field on the main page. E.g. $("#text-field-class").val() to get your text field value – ConnectedSystems Jul 13 '14 at 23:50