Skip to content

Loss of search parameters #155

@alain-guidon

Description

@alain-guidon

Hi Chistian,

It seems I've found a bug with search parameters in the context of a form using the GET method.

Example context:

<form x-target="x-target-message-deliveries" method="get" accept-charset="utf-8" action="/internal/message-deliveries/prepared?messageId=9">
  <div class="field is-grouped c-valigned ">
    <label class="label" for="limit">Items per page</label>
    <div class="control ">
      <div class="select">
        <select name="limit" onchange="this.form.requestSubmit();" id="limit">
          <option value="20">20</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
      </div>
    </div>
  </div>
</form>

The URL in the form's action attribute already has a parameter.

When the form is processed by Alpine AJAX, the current parameters are lost.

For example, the resulting URL is "/internal/message-deliveries/prepared?limit=50".
It should be "/internal/message-deliveries/prepared?messageId=9&limit=50"

To fix this, I patched the source code as follows.

In module.esm.js:

async function send(control, action = "", method = "GET", body = null, enctype = "application/x-www-form-urlencoded") {
//...
 if (body) {
    body = parseFormData(body);
    if (method === "GET") {
// Before
      // action.search = formDataToParams(body).toString();
// After
      let bodyParams = formDataToParams(body);
      action.search = mergeSearchParams(action.searchParams, bodyParams).toString();
      body = null;
    } else if (enctype !== "multipart/form-data") {
      body = formDataToParams(body);
    }
  }
//...
}

//...

// Added function
function mergeSearchParams(searchParams, bodyParams) {
  for (let p of bodyParams) {
    if (searchParams.has(p[0])) {
      searchParams.set(p[0], p[1]);
    } else {
      searchParams.append(p[0], p[1]);
    }
  }
  return searchParams;
}

You will likely produce better code. 😃

Many thanks for your great lib. 👍

Alain

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions