0

I have a project in PHP using CodeIgniter in an HMVC approach.

Now, I run into a problem where I'm really confused what to do next. Here's my situation:

I have a view which looks like this:

//logs_v_month.php

<div id="logs" class="tab-pane active">

</div>

<script type="text/javascript">
$(function(){       
    $.ajax({
      url: "<?php echo load_global_assets('system/js/log.js')?>",
      dataType: "script",
      success: function(e){}
    });
});

</script>

Then I have a controller:

//view.php
function display_logs_month(){
    $data['logs_v'] = $this->load->view('logs_v_month');                        

echo json_encode($data);
}

Then I have another view which is the main view.

//logs.php
<div class="tab-content" id="logs_content">
    <!--logs loaded via ajax call-->
</div>
<script type="text/javascript">
function view_month(group_id, start_end){
$.ajax({
    type : "POST",
    dataType: "json",
    url : "<?=base_url()?>logs/view/display_logs_month",                        
    data : {"group_id" : group_id},
    success : function (data){  
        $("div#logs").remove();                     
        $("#logs_content").append(data.logs_v);//logs_v             
    },
    error : function(data){
    console.log(data);
    }
    });
}

The logs.php view has an ajax call to load the logs_v_month.php view through the view.php controller.

My question is, how do I access JavaScript functions (which are also loaded via ajax) from the logs_v_month.php from the logs.php view?

I've tried searching for the answer on the web and most answers people give is using the eval() function but many discourages from using that.

Is there a way I can restructure or rearrange my JavaScript so it will be easy for me to access them in this kind of situation? I'm also taking into account Namespacing if this can help the problem.

I just started learning CI and HMVC so I'm fairly new to this.

Thanks!

1 Answer 1

2

You need to put the returned scripts into the DOM for the page.

when you get the script data back in the success method of your ajax call, you can create a script element with the code inside it and append it to the DOM, something like:

success:function(data){
    var scriptElement = document.createElement('script');
    scriptElement.setAttribute('type', 'text/javascript');
    scriptElement.textContent = data;
    var head = document.getElementsByTagName('head').item(0);
    head.appendChild(scriptElement);
}

Now the functions will be accessible to all scripts.

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

1 Comment

Sorry for the late reply, I actually did this and it worked! Accepted as answer. Thanks!

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.