Get an answer with AJAX jQuery, it's not going to succes!

0

I make this query from jQuery AJAX, because I'm doing a PHP, AJAX, JQUERY test, The issue is that I try to make a request to the server to send data from the user fields and password but when sending the data, I'm always going to error instead of success, in $ .ajax (), I do not know what happens here?

//Codigo jQuery 3.3.1

$('#send').click(function(){

	$.ajax({
		method:'post',
		url:'login.php',
		datatype: 'html',
		data: user : {$('#user').val()},
		success : function(response){
			$('.alertArea p').text(response);
		},
		error : $('.alertArea p').text("Hubo un error al enviar los datos.!");
	});

});
/*Codigo CSS */

*{
	margin: 0;
	padding: 0;
}
input{
	padding: 10px;
}
h2{
	font-family: "trebuchet ms";
}
.alertArea{
	display: none;
}
.alertArea p{
	background: #333;
}
<!-- Codigo HTML -->



<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" href="stl.css">
	<title>Formulario de imagenes</title>
</head>
<body>

	<form method="post" align="center" id="form">

		<h2>Inicie sesión</h2>
		<hr>
		<br>

		<div class="alertArea">
			
			<p></p>

		</div>

		<input type="text" placeholder="Nombre de usuario" name="user" id="user">

		<input type="password" placeholder="Contraseña" name="pass">

		
		<button id="send">Enviar</button>
	</form>

	<script src="jquery/jquery-3.3.1.min.js"></script>
	<script src="js.js"></script>
	
</body>
</html>
<?php 

include('conexion.php');

$usuario = $_POST['user'];
$contrasena = $_POST['pass'];


echo "Los datos son : 'Usuario : $usuario' , 'Contrasena : $contrasena'";?>

I add that the button being inside the form reloads the page, but when I put it out of the form I do not recharge the page, and even though I removed the action="", I really do not want to recharge the page as well, I guess that's the problem.

    
asked by Abdiel 28.11.2018 в 02:41
source

2 answers

1

There are several problems in your code. I will try to give you a hand.

I list by parts what I have seen globally and then I provide a code as a solution:

Javascript

  • It is convenient to enclose all the code within $(function() { (it is the substitute of the well-known document.ready
  • So that you do not reload the page, you can pass the event in parameter and use preventDefault
  • We will use done and fail , because success is obsolete from jQuery 3.
  • It does not matter if you remove the action, what counts is the url parameter that you put in Ajax
  • Your parameter data of Ajax is wrong. Also, you are not passing the value of pass that you try to recover in PHP

I propose these corrections:

$(function() {

    $("#send").click(function(e){
        e.preventDefault();
        var data= {user : $('#user').val(), pass : $('#pass').val()};
        var request = $.ajax({
            url: 'login.php',
            method: 'post',
            data: data,
            dataType: "html"
        });

        request.done(function(response) {
            console.log(response);
            $('.alertArea p').text(response);
        });

        request.fail(function(jqXHR, textStatus) {
            alert("Hubo un error: " + textStatus);
        });

    });
});

HTML

I guess you'll need to pass the password, then add an id to that input, so that it can be recovered in the variable data that you saw above.

    <input type="password" placeholder="Contraseña" name="pass" id="pass">

PHP

Verify that the data was passed in the POST. Although many people use isset , my favorite for this is empty , combined with a ternary operator that allows me to save the data permanently in a variable.

This also allows you to apply the basic principle of you do not believe anything until you are sure you are going to need it .

<?php 
    /*Había un error aquí, olvidé poner el signo ?*/
    $usuario    = ( empty($_POST['user']) ) ? NULL : $_POST['user'];
    $contrasena = ( empty($_POST['pass']) ) ? NULL : $_POST['pass'];

    if ($usuario && $contrasena){
        /*Sólo aquí estamos seguros de necesitar la conexión*/
        include('conexion.php');
        $msg="Los datos son : 'Usuario : $usuario' , 'Contrasena : $contrasena'";
    }else{
        $msg="No se postearon datos de usuario y contraseña";
    }
    echo $msg;
?>
    
answered by 28.11.2018 в 04:36
0

To avoid reloading the page you can use submit of jquery and manage how you want the form to be processed. preventDefault() will prevent the default action of the form from being performed.

    $( "#form" ).submit(function( event ) {
      alert( "Submit de #form se ha lanzado" );
      //Aqui la logica para manejar la forma.
      event.preventDefault();
    });

For the matter of which the ajax does not enter to success I believe that it is not so easy to diagnose without more information, always you can see the error that the function returns with the callback of error

$.ajax({
    method:'post',
    url:'login.php',
    dataType: 'html',
    data: {user : $('#user').val()},
    success : function(response){
        $('.alertArea p').text(response);
    },
    error: function(response){
        $('.alertArea p').text("Hubo un error al enviar los datos.!");
        //imprime a consola el response con detalles del error
        console.log(response);
    }
});

Although at first glance I see a few details in the ajax datatype should be dataType and there should only be one object in the data field. And I do not know the configuration to show the errors in PHP because your code will generate a NOTICE since there is no value of $_POST['pass']

    
answered by 28.11.2018 в 04:15