Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return view after ajax post to controller in ci4

I try to achieve to return a view after an ajax call with jquery.

HTML

<a class="btn" data-value="10">

jQuery

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(document).on("click", ".btn", function(){
        $.ajax({
            url: 'http://localhost:8080/test/testmenu/',
            type: 'POST',
            data: { id : $(this).data('value')},
            success: function(response){
                // What to do?
            }
        })
    })

CI4 Route

$routes->post('test/testmenu/','Menu::openMenu');

CI4 Controller

public function openMenu(){
    $menu = model(\MenuModel::class);
    $menu_id = $this->request->getPost("id");

    $data['menu'] = $menu->getMenuById($menu_id);
    $data['title'] = "Test";

    // How to correctly return?
    return view('menu/testmenu/',$data);
}

I dont want to replace a DOM div with $("div").html(response) in ajax success – i want to redirect to an new page showing the return view.

Is this possible or a wrong approach?

thanks in advance

>Solution :

The whole point of using AJAX is to avoid the need to post back, refresh, redirect or otherwise navigate away from the current page. So if your goal is to redirect, then simply don’t use AJAX – make a request in one of the other ways instead.

The way you’re trying to do it now is possible (AJAX and then redirect) it’s just that it’s nonsensical – not least because it ends up causing two HTTP requests instead of one, which is less efficient.

In this case it looks like you could simply make a little form and put this ID in a hidden field within it, and then the form could submit and post back the ID to your PHP, which would then show the view as you are expecting. Something like this is the general idea:

<form action="http://localhost:8080/test/testmenu/" method="POST">
 <input type="submit" name="submit" class="btn" value="Submit"/>
 <input type="hidden" name="id" value="123"/>
</form>

The hidden field there replaces having the ID as a data-attribute of the clickable element, as you have now. And a "submit" input (or a <button> if you prefer) is required in order to submit a form – an <a> cannot do that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading