简体   繁体   中英

How to call javascript function in the index of a controller in codeigniter?

I'm trying to call a javascript function inside my controller to display a warning message in page if a verification I do in the index function of this controller is false.

Here is my code:

<?php
public function index() {

    $this->load->model('uploads_m');
    $this->load->helper('form');
    $template_vars = Array();

    $this->load->vars($template_vars);

    $data = Array();
    $data['currentUploadId'] = $this->uploads_m->get_lastUploadId();
    $data['fileTypes'] = $this->uploads_m->getAllFileTypes();

    $data['existingFiles'] = Array();
    if (isset($data['currentUploadId'])) {
        $data['existingFiles'] = $this->uploads_m->get_UploadedFilesFromUploadId($data['currentUploadId']);
    }else {
        // TODO create warning message to tell that uploadid was not generated
    }
    $this->load->view('include/header');
    $this->load->view('upload_files', $data);
    $this->load->view('include/footer');
}
?>

I have a JS function stored in an extern js file that I wanted to call in this TODO. It should be called this way :

show_msg_xajax("warning", "System was unable to find an Upload ID");

Since the check condition is being done in the index() of the controller, I don't know how to call this js function. if it was being invoked by an event in the view, I'd create an ajax method to execute this function. but how can I call the javascript function it in the index() ?

I already checked this answer: Calling javascript function from controller codeigniter but it didn't help me.

The solution I found was to send the function directly to the footer of that page... so I added a new variable to a footer template I have (where I call my javascripts). in the index function in the controller I did:

if (isset($data['currentUploadId'])) {
        $data['existingFiles'] = $this->uploads_m->get_UploadedFilesFromUploadId($data['currentUploadId']);
} else {
        // TODO criar alerta de erro no sistema que não gerou UPLOADID
        $template_vars['foot_javascripts_inline'] = 'show_msg_xajax("error", "System was unable to find an Upload ID");';
}

and in my footer template I added:

if (isset($foot_javascripts_inline)) { ?>
    <script> <?php echo $foot_javascripts_inline ?> </script>
}

Thanks anyway for the help

您需要使用JS函数将文件添加为视图:

$this->load->view('path-to-js-message');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM