contributor01010
contributor01010

Reputation: 31

PHP JSON redirect

I have a registration form,i want to redirect the user after register success (200) response to "location" => "home.php" or display errors on 400 (bad request) via json

I only know few basics of php so how should this look like

--> register.php ?

Combined with the examples below?


// make sure nothing is echo'd or otherwise sent to the
// output buffer at this stage

$errors = []; // collect errors in here

// do whatever you need to do with the $_POST / $_FILES data...

// capturing errors example...

if ($_POST['cpassword'] != $_POST['password']) {
    $errors[] = "Passwords do not match!";
}

// use content negotiation to determine response type
if ($_SERVER['HTTP_ACCEPT'] === "application/json") {
    if (count($errors)) {
        header("Content-type: application/problem+json");
        http_response_code(400);
        exit(json_encode([
            "message" => "Invalid form data or something",
            "errors" => $errors
        ]));
    }

    header("Content-type: application/json");
    exit(json_encode(["location" => "home.php"]));
}

// just a normal request, respond with redirects or HTML
// ...

foreach ($errors as $error) : ?>
    <div class="error"><?= $error ?></div>
<?php endforeach;

The client can navigate to home on success or display error information otherwise

document.querySelector(".register form").addEventListener("submit", async (e) => {
  e.preventDefault()

  const form = e.target

  const body = new FormData(form)

  // fetch is much easier to use than XHR
  const res = await fetch(form.action, {
    method: "POST",
    headers: {
      accept: "application/json", // let PHP know what type of response we want
    },
    body
  })

  const data = await res.json()

  if (res.ok) {
    location.href = data.location
  } else if (res.status === 400) {
    document.querySelector('.msg').textContent = data.message
    // also do something with data.errors maybe
  }
})

Please understand that im new and i have trouble resolving this,
a complete php answer would help & mark as resolved

Upvotes: 2

Views: 190

Answers (1)

Barmar
Barmar

Reputation: 780889

You have no ok element in the JSON when it contains the redirect location. So change

    exit(json_encode(["location" => "home.php"]));

to

    exit(json_encode(["ok" => true, "location" => "home.php"]));

Upvotes: 2

Related Questions