Handle php results from ajax

1

I have a php file that collects data and sends it through ajax to another php that validates that the data entered are the same as those stored in $ _SESSION
If they are the same, make an UPDATE in my database. I want to see if there is a way to return to the ajax information on whether the data is valid and on whether the UPDATE was made in the database the function of js of the php is this:

<code>
function Check()
            {
                var newname = document.getElementById('newUserName').value;
                var newpass = document.getElementById('newPass').value;
                var ActualData = {
                    Nusuario: newname,
                    Npassword: newpass
                    };
                $.ajax({
                        type: 'POST',
                        url: 'check_data.php',
                        data:ActualData,
                        success: function(data)
                        {
                            //Manejar la respuesta del otro php
                        }
                    });
            }

and the php where I send the data is this:

<?php
@session_start();
    include("BD/conexion.php");
    $Nus = $_POST['Nusuario'];
    $Npass = $_POST['Npassword'];
    $act_us = $_SESSION['usuario'];
    $act_pass = $SESSION['pass'];
    if ($us == $act_us && $ps == $act_pass)
    {
        mysqli_query($mysqli, "UPDATE usuarios SET username='$Nus', pass='$Npass' WHERE usuarios.username='$us'");
    }
    else
    {

    }
?>
</code>
    
asked by Cead135 20.11.2017 в 16:48
source

1 answer

3

Returning messages to the Front-End after executing the Back-End requests is simple, just put echo in the messages you want to return.

In your PHP you can do the following:

<?php
@session_start();
  include("BD/conexion.php");
  $Nus = $_POST['Nusuario'];
  $Npass = $_POST['Npassword'];
  $act_us = $_SESSION['usuario'];
  $act_pass = $SESSION['pass'];
  if ($us == $act_us && $ps == $act_pass)
  {
    $resultado = mysqli_query($mysqli, "UPDATE usuarios SET username='$Nus', pass='$Npass' WHERE usuarios.username='$us'");

    if($resultado){
      echo "Los datos fueron actualizados correctamente";
    }else{
      echo "Ocurrió un error al actualizar los datos";
    }
  }
  else
  {
    echo "Las credenciales no coinciden";
  }
?>

And in the JS you receive it in the following way:

function Check()
{
  var newname = document.getElementById('newUserName').value;
  var newpass = document.getElementById('newPass').value;
  var ActualData = {
    Nusuario: newname,
    Npassword: newpass
  };
  $.ajax({
      type: 'POST',
      url: 'check_data.php',
      data:ActualData,
      success: function(data)
      {
        alert(data);
      }
  });
}
    
answered by 20.11.2017 / 16:57
source