Pass URL to controllers via XMLHttpRequest

Hi!

I have a controller controllers/add.php that creates a page child with an URL, a title and some tags, from a form.

I need to pass those datas to this controller via XMLHttpRequest (i’m using barba.js for transitions between pages, I can’t do this with PHP only).

To do this, I’m using this custom route :

'pattern' => 'addbookmark/(:all)/(:all)/(:all)',
'action'  => function ($url, $title, $tags) {
  $data = [
    'url'   => $url,
    'title' => $title,
    'tags'  => $tags,
  ];
  return page('add')->render($data);
}

Called by :

let url   = encodeURIComponent(submitted_url.value);
let title = encodeURIComponent(submitted_title.value);
let tags  = encodeURIComponent(submitted_tags.value);

xhttp.open("GET", "/addbookmark/"+url+"/"+title+"/"+tags, true);

But the route send me a 404 because of the URL encoding.
It works if I remove the URL parameter.

Is there a way to pass URL via routes ?
Or is it a bad practice using routes to do this and there is another way to do it?

Thanks for your help!

— G

You route cannot work, should be

'pattern' => 'addbookmark/(:any)/(:any)/(:any)',

What is your controller actually doing? Wondering why you are not sending a POST request to the controller (or add a json representation controller) instead of going via a route

Same with :any, 404 due to URL encoding :slightly_frowning_face:

BUT, got it thanks to you!

As overcat in this post, my mistake was to POST directly to the controller like this :

xhttp.open("POST", "/site/controllers/add.php", true);

But the good way is to call the url obviously :

xhttp.open("POST", "/add", true);

My XHR request is solved :white_check_mark:

About the inability to use URL in routes, I don’t know, it’s a bug or a feature?

Thanks!

It could probably work if you urlencode/urldecode the url, but a POST request is IMO the better option for sending such data.

1 Like