AJAX request returning the entire HTML page

Asked

Viewed 1,006 times

1

I’m using an ajax function that returns something to min, but the same function besides returning me the expected result, it returns all the HTML code of the page.

In my login form I use the ajax function to authenticate, and I receive the HTML code of the page as return, but if I use the form post the expected result is returned without the HTML code of the page.

Follows the code:

login.php

<?php 
    require_once '../../vendor/autoload.php';
    require_once '../route/routes.php';
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 2 | Log in</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.7 -->
  <link rel="stylesheet" href="../../assets/bower_components/bootstrap/dist/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="../../assets/bower_components/font-awesome/css/font-awesome.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="../../assets/bower_components/Ionicons/css/ionicons.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="../../assets/css/AdminLTE.min.css">
  <script src="../../assets/js/requisicao-ajax-view.js"></script>

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->

  <!-- Google Font -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <div class="login-logo">

  </div>
  <!-- /.login-logo -->
  <div class="login-box-body">
    <p class="login-box-msg">Faça login para acessar o sistema</p>

      <div class="form-group has-feedback">
        <input type="text" class="form-control" placeholder="Login" id="login" name="login">
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input type="password" class="form-control" placeholder="Senha" id="senha" name="senha">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="row">
        <div class="col-xs-8">
          <div class="checkbox icheck">

          </div>
        </div>
        <!-- /.col -->
        <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat" onclick="requisicaoAjaxAutenticaUsuario();">Entrar</button>
        </div>
        <!-- /.col -->
      </div>

    <a href="#">Esqueci minha senha</a><br>
    <a href="register.html" class="text-center">Registrar-se</a>

  </div>
  <!-- /.login-box-body -->
</div>
<!-- /.login-box -->

<!-- jQuery 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- Bootstrap 3.3.7 -->
<script src="../../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="../../plugins/iCheck/icheck.min.js"></script>
<script>
  $(function () {
    $('input').iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
      increaseArea: '20%' // optional
    });
  });
</script>
</body>
</html>

funcao-ajax-autentica.js

     function requisicaoAjaxAutenticaUsuario(){
            //RECUPERA OS DADOS DO FORM DE LOGIN
            var login = document.getElementById("login").value;
            var senha = document.getElementById("senha").value;

            if(login.length > 0 && senha.length > 0){
                $.ajax({
                    type:'post',
                    data:{login: login, senha: senha},
                    contenttype: "application/json; charset=utf-8",
                    url: 'login.php/usuario/autentica',
                    success: function (data) {
                        alert(data);
                    },
                    error: function (erro) {
                        console.log(erro);
                    }
                });
            }
        } 

Routes.php

$app = new Slim\App;

$app->post('/usuario/autentica', function($request){
    $login = $request->getParsedBody()['login'];
    $senha = $request->getParsedBody()['senha'];

    require'../model/usuario.php';
    $autentica = new App\Model\Usuario;
    echo $autentica->autenticaUsuario($login, $senha);

});
$app->run();

usuario.class.php

<?php
namespace App\Model;

/**
 * Classe com os metodos dos usuarios
 *
 * @author Abner Marques
 */
class Usuario {

    public function autenticaUsuario($login, $senha){
        echo $login;
    }
}

The code that is returned is this:

i give a alert, and at the beginning of the code the letter A is the value I enter in the login field, it is returning normally, but what is wrong is the return of the page’s HTML code.

eu dou um alert, e no começo do código a letra A é o valor que eu insiro no campo de login, esta retoornando normalmente, mas o que está de errado é o retorno do código HTML da página.

  • I am using the slim framework route systems

  • Routes.php $app = new Slim App; $app->get('/', Function(){ }); $app->post('/username/authenticate', Function($request){ $login = $->getParsedBody()['login']; $password = $->getParsedBody()['password']; require'./model/user.php'; $autentica = new App Model Usuario; echo $autentica->autenticaUsuario($login, $password); }); $app->run(); users.class.php <? php class Usuario { public Function autenticaUsuario($login, $password){ echo $login; } }

  • follows the code.

  • I just edited, sorry I’m new to the forum

  • Your routes are set in the file routes.php, but you do the requisition for login.php. That’s right?

  • Yes this correct, the routes are working properly. I do the request for the desired route, the route file is included in the php file of the user authentication form

  • What a mess. What, then, is the file code login.php? Already ahead for you to make the [tour] by the site and read urgently the guide of [Ask]. Try to provide in the question every detail concerning the problem, otherwise it will be impossible to infer anything.

  • I have already posted the login.php code, in the onclick event of the login form button, I use the login ajax function, in it I capture the form data and send to the route I prompt the user class and call the user authentication method, and in the way I return pro ajax user login.

  • Done. Problem solved. Look at the returned HTML in login.php. Everything inside this file will be returned to Javascript.

  • but this is the page that the user will log in, it must exist.

  • I believe that you do not understand much of the basic process and that is why there is this confusion. By logic, the file routes.php should not be included in login.php; This doesn’t make much sense. Slim, in theory, should receive all requests through the file routes.php and he wants to define what should be returned to the client, including HTML codes. A lot of things there seem to be solved correctly only by refactoring the project, which is impossible to do by the site. Then I recommend that you read more about Slim and try to understand better how the HTTP protocol works.

  • Perhaps this could be applied in your question https://answall.com/a/259599/8063

Show 7 more comments

2 answers

0

As you made an ajax request, anything you mount in your back-end (for example an echo in php) will go back to your ajax response variable. What you have to do is redirect the user if he has successfully logged in. I always return a "logged in" to javascript.

success: function (data) {
    if(data == 'logado'){
        window.location.replace(url);
    }
},

In the url I do the redirect has a code that checks if the user is actually logged in, redirecting him to the restricted area of the site or returning to the login page.

-3

I am using the slim framework routing system, the ajax requisicao sends this login.php/user/auth route, and einstancia the user class and calls the authentication method,

Routes.php

$app = new Slim\App;

$app->post('/usuario/autentica', function($request){
    $login = $request->getParsedBody()['login'];
    $senha = $request->getParsedBody()['senha'];

    require'../model/usuario.php';
    $autentica = new App\Model\Usuario;
    echo $autentica->autenticaUsuario($login, $senha);

});
$app->run();

usuario.class.php

<?php
namespace App\Model;

/**
 * Classe com os metodos dos usuarios
 *
 * @author Abner Marques
 */
class Usuario {

    public function autenticaUsuario($login, $senha){
        echo $login;
    }
}

it was supposed to return only the login of the user, but it is returning the login together with the code of the html page

  • Below the question is the [Edit] button. This area is unique for answers.

  • Enjoy and already put what is the returned HTML code too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.