Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
JSON to HTML CSS output

I have a registration form, on data.error PHP outputs as JSON the errors
exit('{"error": "Passwords do not match!"}');

After a successful register, the user will be redirected to exit('{"location": "home.php"}');

I want the json output, instead of plain text to be put into html+css for styling,
so i can style div for the errors

            document
                    .querySelector(".register form")
                    .addEventListener("submit", async (e) => {
                        e.preventDefault();
                        const form = e.target;
                        const body = new FormData(form);
                        const res = await fetch(form.action, {
                            method: "POST",
                            body,
                        });
                        const data = await res.json();
                        if (data.error) { // If there is an error
                            document.querySelector("#msg").innerHTML = data.error; 

                        }
                        else if (data.location) { // If we want to redirect the user somewhere
                            window.location.href = "./" + data.location;
                        }
                    });
        

If i add a class, <div id="msg" class="error"></div> doesn't output anything,
while only inline style style="background-color:red;"> will work

.error {
    background: #F2DEDE;
    color: #A94442;
    border-radius: 4px;
    font-weight: bold;
    text-align: center;

}

enter image description here

I been researching this for 12 hours, i've seen few examples about JSON.stringify and others,
but i don't know how could i implement this into my code

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Well I still don't know if I understand your case correctly. You can add a class to element msg for when an error is returned.

if (data.error) { // If there is an error
document.querySelector("#msg").classList.add("error"); //This will be styled from your CSS. Add a background, etc
document.querySelector("#msg").innerHTML = data.error;
}

CSS:

.error {
  color: white;
  font-size: 14px;
  margin-top: 10px;
  background-color: red;
  }
about 4 years ago · Juan Pablo Isaza Denunciar

0

function login($username, $password) {
  // do a login

  // if any errors
  header('Content-Type: application/json');
  echo json_encode($response);
  exit;

  // or if you're using any framework/controller then return properly
  // using a json response containing the error i.e. "Invalid Login"
}

You want to do something like that server side. Then on the client side you want to get the response, check if there are errors and display the errors if they exist. Use a visible class or something for that so that you can change the visibility and display errors. So you create the div and css the way you want to and just use display: none on it, then if you do get errors you make it visible.

Don't use PHP to generate HTML/CSS, especially not in this way, unless you're using a proper view engine, otherwise you'll end up creating a mess. Send back a proper JSON response and do your UI stuff client side based on that response.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda