0

i want to use append a table on click of add button. this table will display all values from the $category array . i tried to use php code inside of jquery and the sample code is as below. how can i improve my code to display array from php variable?

 $(".add_field_button").on("click", function(e) {
     var wrapper = $(".input_fields_wrap");
     $(wrapper).append('<hr>\n\
                 <table class="append-group table">\n\
                   <tr>\n\
                     <td colspan='4'>\n\
                       <div class="form-group">\n\
                          <label class="">\n\
                             Select Category<span id="load"></span>\n\
                          </label>\n\
                             <?php foreach($categories as $category){?>\n\
                                <div class="radio-inline">\n\
                                    <label style="font-weight:normal;">
                                      <input class="category" id = "<?php echo $category['id'];?>" type="radio" onclick="get_sub_category('<?php echo $category['id'];?>',0)" name="category_id" <?php if ($action == 'edit' && $detail[0]['category_id'] == $category['id']) {  echo "checked='checked'";} ?> value="<?php echo $category['id'];?>"><?php echo ucwords(strtolower($category['name']));?>
                                    </label>\n\                                    
                                </div>\n\
                             <?php }?>\n\
                       </div>\n\
                         <input type="hidden" id="selected_item" value="<?php if(isset($detail[0]['category_item_id'])) echo $detail[0]['category_item_id'];?>">\n\
                      </td>\n\
                    </tr>\n\
                 </table>\n\
                ');
             });
3
  • you should use ajax.. Commented Mar 4, 2015 at 5:32
  • @AwladLiton - I don't agree - in this case. Why should he? Commented Mar 4, 2015 at 6:09
  • i think in any scenario it is never be a good practice. Commented Mar 4, 2015 at 6:14

2 Answers 2

2

Saperate every part and make the things moduler, so that it will be easy to extend. In PHP Do like this:

$categories_data = "";
foreach($categories as $category) { 
     $categories_data .= '<div class="radio-inline">';
     $categories_data .= '<label style="font-weight:normal;">';
     $categories_data .= '<input class="category" id = "'.$category['id'].'" type="radio" onclick="get_sub_category("'.$category['id'].'",0)" name="category_id" ';

     if ($action == 'edit' && $detail[0]['category_id'] == $category['id']) {  
         $categories_data .= ' checked="checked" '; 
     }

     $categories_data .= 'value="'.$category['id'].'">';
     $categories_data .= ucwords(strtolower($category['name']));
     $categories_data .= '</label></div>';
}


$cat_item_id = "";
if( isset($detail[0]['category_item_id']) ) {
    $cat_item_id = $detail[0]['category_item_id'];
}

In your JAVASCRIPT saperate the template, variables etc. and then append after replace the things properly:

var _categories = '<?php echo $categories_data; ?>';
var _cat_item_id = '<?php echo $cat_item_id ?>';

// Your template 
var _template = '<hr>\n\
             <table class="append-group table">\n\
               <tr>\n\
                 <td colspan='4'>\n\
                   <div class="form-group">\n\
                      <label class="">\n\
                         Select Category<span id="load"></span>\n\
                      </label>\n\
                      {{categories}}\n\
                   </div>\n\
                     <input type="hidden" id="selected_item" value="{{cat_item_id}}">\n\
                  </td>\n\
                </tr>\n\
             </table>';


// Marge with original values and append
var _table = _template.replace(/{{categories}}/, _categories)
                      .replace(/{{cat_item_id}}/, _cat_item_id);

$(wrapper).append( _table );

To access categories and item_id globally you can use window._categories = '<?php echo $categories_data; ?>'; and window._cat_item_id = '<?php echo $cat_item_id ?>'; so that if you have external js file (custom.js) then its easy to access these values with window._categories and window._cat_item_id

Sign up to request clarification or add additional context in comments.

Comments

1

You can preload your js objects in the header of your php file like this:

<script type="text/javascript">
    var GLOBALS = {
        categories: <?php echo json_encode($categories); ?>,
        detail: '<?php echo isset($detail[0]['category_item_id']) ? $detail[0]['category_item_id'] : ""; ?>',
        action: '<?php echo $action; ?>'
    }
</script>

<script src="myscript.js">

Next create a script that triggers on the button press. You can grab your category data from the global variables set in the php file.

$(".add_field_button").on("click", function(e) {

     var $span = $('<span>', {id: "load"});
     var $label = $('<label>', {text: "Select Category"}).append($span);
     var $divs = [];

     for (var i in GLOBALS.categories) {
        var action = GLOBALS.action || "";
        var detail = GLOBALS.detail || "";      
        var id = GLOBALS.categories[i].id || "";
        var name = GLOBALS.categories[i].name || "";

        var $i = $('<input>', {
            class: category, 
            id: id,  
            type: "radio",
            onclick: "get_sub_category(" + id + ", 0)",
            name: "category_id",
            value: id,
            text: name.toLowerCase()
        });        

        if (action == "edit" && detail == id) {
            $i.prop("checked", true);
        }   

        var $l = $('<label>', {style: "font-weight: normal"}).append($i);
        var $d = $('<div>', { class: "radio-inline"}).append($l);
        $divs.append($d);
     }

     var $div = $('<div>', {class: "form-group"}).append($label, $divs);
     var $input = $('<input>', {type: "hidden", id: "selected_value", value: GLOBALS.detail});
     var $td = $('<td>', {colspan: 4}).append($div, $input);
     var $tr = $('<tr>').append($td);
     var $table = $("<table>", {class: "append-group table"}).append($tr);
     var $wrapper = $(".input_fields_wrap").append($('<hr>'), $table);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.