0

Let's say that I have btn1 and btn2 which load some data into a div when clicking on them through Ajax like this:

$(document).on('click', '#btn1', function(e){
    var url = "<?= $this->Url->build(['controller' => 'MyController', 'action' => 'my_action', '?' => ['param1' => 'abc']], ['escape' => false]); ?>";

    $('#my_container').load(url);
});

$(document).on('click', '#btn2', function(e){
    var url = "<?= $this->Url->build(['controller' => 'MyController', 'action' => 'my_action', '?' => ['param2' => 'def']], ['escape' => false]); ?>";

    $('#my_container').load(url);
});

As tou can see above, each button call the same controller action but passes different query strings (param1 and param2) with different values.

I would like to be able to append the query strings to the current url, instead of just loading the link attahed to each button meaning:

If I clicked on btn1, the url that I load will be:

http://example.com/mycontroller/my_action/?param1=abc

But if I then click on btn2, my url should become:

http://example.com/mycontroller/my_action/?param1=abc&param2=def

Instead of:

http://example.com/mycontroller/my_action/?param2=def

So I want to append query strings to the existing url.

Keep in mind that those are Ajax calls. So the currently loaded url is not visible in the browser.

Is there a CakePHP 3 way of doing this? I realize that this works already with pagination. Anybody knows how to make this work also with custom query strings?

Thanks in advance

user765368
  • 19,590
  • 27
  • 96
  • 167

1 Answers1

0

Are you looking for something like this?

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

This will get you the current querystring items. now you just have to manipulate it and use it.

Found at https://css-tricks.com/snippets/javascript/get-url-variables/

Dieter Kräutl
  • 657
  • 4
  • 8