Home > Net >  My async fetch function takes me to the endpoint I POST to. I want it to refresh the page it POSTS f
My async fetch function takes me to the endpoint I POST to. I want it to refresh the page it POSTS f

Time:11-19

My async fetch function is embedded on names.php and when I activate the function it takes me to the endpoint it POSTS to: change-name.php. I want to remain on the names.php page but refresh that page after the fetch function has run.

I am clicking the span below to open a text field where I add a name and click the button:

<span onclick="addGuestName(this)">

<button class="addPaxName btn btn-xs btn-warning">ADD</button>

This works perfectly fine. And updates the name but I am transported to the /change-name.php page after clicking the ADD button.

My desired response is to remain on the original page with a page refresh after the fetch function has completed. How do I get this result.

async function updateGuestName(paxid,name){
paxIDbody = '{"pxid": "'   paxid   '", "name": "'   name   '"}';
  console.log("PaxID:", paxIDbody);
  try {
    const settings = {
      method: "POST",
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      },
      body: paxIDbody,
    };
    const response = await fetch(
      "/change-name.php",
      settings
    );
    const data = await response.json();
    console.log("DATA: ",data);
  } catch (error) {
    console.log("ERROR: ",error);
  }
}

function addGuestName(obj) {
  const itemClicked = obj;
  const paxid = obj.id;
  const addPaxName = itemClicked.nextElementSibling;
  const addPaxNameButton = itemClicked.nextElementSibling;
  addPaxNameButton.style.display = 'inline-block';
  var addPaxNameField = document.createElement('input');
  addPaxNameField.setAttribute('type', 'text');
  addPaxNameField.setAttribute('name', 'visitorNameSurname[]');
  addPaxNameField.setAttribute('placeholder', 'Enter Name & Surname');
  itemClicked.parentNode.insertBefore(addPaxNameField, itemClicked.nextSibling);
  addPaxNameField.setAttribute("required", "required");
  addPaxNameButton.addEventListener('click', () => {
    const name = addPaxNameField.value;
    updateGuestName(paxid,name);
  })
}

My PHP endpoint returns JSON after the DB update:

header('Content-type:application/json;charset=utf-8');
    $myObj=new \stdClass();
    $myObj->status = $status;
    $myObj->message = $message;
    $myJSON = json_encode($myObj);
    echo $myJSON;

CodePudding user response:

Default button type is submit. Use onsubmit with event.preventDefault() inside onsubmit callback. If you don't need browser's form validation, you can use more straightforward type="button". For refreshing page look at location.reload().

CodePudding user response:

addPaxNameButton.addEventListener('click', (e) => {
    e.preventDefault();
    const name = addPaxNameField.value;
    updateGuestName(paxid,name);
  })
  • Related