Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
PHP Redirect and Ajax

I have a registration form. The register.php is checking for errors such as short password
AJAX gives an alert with the echo error from PHP.

With PHP, after an if else statement
the user will be registered and redirected successfully to Location:index.php (good)

register.php

The problem is, if there is any error, the user will be redirected to register.php
and the echo alert shows there (on white page)


AJAX

var form = document.querySelector('.register form');
form.onsubmit = function(event) {
    event.preventDefault();
    var form_data = new FormData(form);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', form.action, true);
    xhr.onload = function() {
      document.querySelector('.msg').innerHTML = this.responseText;
    };
    if (xhr.status >= 200 && xhr.status <= 299) {
      var response = JSON.parse(xhr.responseText);
      if (response.location) {
        window.location.href = response.location;
      } else {
        xhr.send(form_data);
      }
    }

Example 2: the alerts will display properly at <div class="msg"></div> position
(But will also throw the index.php on the msg div(same page where the alerts go)

var form = document.querySelector('.register form');
form.onsubmit = function(event) {
  event.preventDefault();
  var form_data = new FormData(form);
  var xhr = new XMLHttpRequest();
  xhr.open('POST', form.action, true);
  xhr.onload = function() {
    document.querySelector('.msg').innerHTML = this.responseText;
  };
  xhr.send(form_data);
};

So, i want the user to be redirected to index.php & also the echo errors (register.php) to be handled by AJAX

Please understand that im new & learning, i spent a week in this.
If you choose to resolve this, please fix based off register.php and ajax code

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda