skip to Main Content

I want to fill a div from my controller that called with ajax for my onchange, but I can’t make it work, I think the problem is in the function in the controller that I called.

I try using the return view and else but nothing works, I try using the setBody but it can’t provide for my looping for the table.

Here is the div that I want to fill in :

<div id="tableCont"></div>

Here is my script in my myscript.js :

function call_user_menu ()
{
    $.ajax({            
     type: 'GET',
     url: 'http://localhost:8080/menumanagement/formMenuUser',
     dataType: 'html',
     success: function (html) {
        $("#tableCont").empty();
        $("#tableCont").html(html);
                            
        },
        error: function(){
          Swal.fire({
          title: 'Menu Data failed to load!',
          text: "",
          icon: 'warning',
          confirmButtonColor: '#d33',
          cancelButtonColor: '#d33',
          })        
        },
    });
    
}   

Here is my function in my Controller :

public function formMenuUser()
{
    //the default return view :
    return view('menu_form-menu-user.php');

    //what should I write here to call the view to fill the div?
    //can I use the setBody? but I can't use my foreach there

}

I really appreciate any help that can provide. Thanks

2

Answers


  1. You should pass the view like this.

    $html = view('menu_form-menu-user')->render();
    return $this->response->setBody($html);
    

    Read – Working with the Response

    Login or Signup to reply.
  2. You would need to supply the data to build your loop in that method, and the HTML that builds out the table in the view.

    Make sure you’re calling the Model at the top:

    use AppModelsFormMenuUserModel;
    

    IE: Try this method..

    public function formMenuUser()
    {
        $getMenuUserItems       = (new FormMenuUserModel)->findAll();
        $data = [
            'title'             => 'View Form',
            'menuItems'         =>  $getMenuUserItems
        ];
        // uncomment the line below to make sure it is returning the data you want
        // echo '<pre>';print_r($data);echo '</pre>';die;
        return view('menu_form-menu-user', $data);
    }
    

    And in your menu_form-menu-user view, add your forloop to display the menu table how you want..

    <table class="table table-sm table-bordered table-striped table-hover">
    <?php foreach ($menuItems as $row) : ?>
        <tr>
            <td><a href="<?= site_url($row['link']); ?>"><?= $row['title'] ?></a></td>
        </tr>
    <?php endforeach; ?>
    </table>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search