Home > Software design >  Return view after ajax post to controller in ci4
Return view after ajax post to controller in ci4

Time:08-03

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

HTML

<a  data-value="10">

jQuery

$(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

CodePudding user response:

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"  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.

CodePudding user response:

Thank you - i changed it to your idea and submit the form with onclick. Two HTTP requests are indeed nonsensical.

<form action="<?php echo base_url(); ?>/test/testmenu/" method="POST">
    <a  onclick="this.parentNode.submit();">
    <input type="hidden" name="id" value="123"/>
</form>
  • Related