Doubt: $ .ajax () or $ .get or $ .post ()?

1

Hello

In my project, the user makes a registration by entering user, email, link 1 (http) and link 2 (http). I save this data in a database.

In the verificalogin.php page, I check if the email and password are correct and if they are, I redirect the user to the main.html page, otherwise I redirect to the index.php page.

Verificalogin.php page:

<?php
require 'conexao.php';
?>

<!DOCTYPE html lang="en">
<html>
<head>
    <meta charset="utf-8">
	<title>VerificaLogin</title>
	<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
	<script type="text/javascript">
		function loginsucesso(){
			setTimeout("location.href='principal.html'", 3000);
		}

		function loginerro(){
			setTimeout("location.href='index.php'", 3000);
		}
	</script>
</head>
<body>


<?php
session_start();
$email=$_POST['email'];
$senha=$_POST['senha'];

$querry = "SELECT * FROM bancodados WHERE email='$email' AND senha='$senha'";
$sql = mysqli_query($con,$querry) or die(mysqli_error());
$row = mysqli_num_rows($sql);
$dados = mysqli_fetch_assoc($sql);
$user = $dados['user'];
$_SESSION['id'] = $user; 
$end1 = $dados["link1"];
$end2 = $dados["link2"];
$var="<br/>";
 
if ($row > 0){
	$_SESSION ['email'] = $_POST ['email'];
    $_SESSION ['senha'] = $_POST ['senha'];
    echo "<center><h3>Login realizado com sucesso!</center></h3>";
    echo "<script>loginsucesso()</script>";
} else {
	echo "<center><h3>Usuário ou senha incorretos</center></h3>";
	echo "<script>loginerro()</script>";
}

?>

On the main.html page I have the following codes:

<?php
require 'conexao.php';
session_start();
if (!isset($_SESSION["email"]) || !isset($_SESSION["senha"])){
	header("Location: index.php");
	exit;
} 
$usuario = array();
    $query1 = "SELECT * FROM bancodados WHERE user = $_SESSION['id']";
    $resultado = mysqli_query($con,$query1);
    while(mysqli_fetch_assoc($resultado) = $row1){
    array_push($usuario,$row1);
    } 
?>

<!DOCTYPE html>
<html lang="en">
<head> 
	<meta charset="utf-8">
	<title>Exemplo numero 1</title>
	<link rel="stylesheet" type="text/css" href="css/estilo.css">
	<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
	<script type="text/javascript" src="js/javascript.js"></script>
</head>

<body>
<div id="site">

<div id="areapessoal">
    	<section>
		<figure id="fotoperfil">
			<img src="imagens/usuario.jpg" alt="Foto de Perfil">
		</figure>
	    <br>
	    <p><h3 id="user"><?= $usuario['id']; ?></h3></p>
	    <input id="sair" type="button" onclick="location.href='logout.php';" value="Sair" />
	    </section>
    </div>

<div id="links">
        <section class="icons">
        <a id="lend1" href="<?=$usuario['href1']?>"><?= $usuario['end1'] ?><img src="imagens/link1.jpg" alt="Link 1"/></a> 
		</section>
	    <section class="icons">
	    <a id="lend2" href="<?=$usuario['href1']?>"><?=$usuario['end2']?><img src="imagens/link2.jpg" alt="Link 2"/></a>
	    </section>  
	    
</body>
</html>

I need to replace the contents of the tag (h3) with my $ user variable, and tag href (a) for $ end1 and $ end2.

$ user, $ end1 and $ end2 are on the verificalogin.php page and are PHP variables.

I tried to do:

function loginsucesso(){
     $.get("principal.html", function(){
        $("#user").html("<?=$user?>");
        $("#end1").attr("href","<?=$end1?>");
        $("#end2").attr("href","<?=$end2?>");
      });
			setTimeout("location.href='principal.html'", 3000);
		 }

But it is not working !!

Who can help me, I thank you! Vlw!

    
asked by anonymous 01.05.2017 / 16:57

1 answer

5

That # explains when to use GET or POST in JQUERY GET & POST are aliases or nicknames for the AJAX method, when you use $ .GET this is an abbreviation for:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

And the same goes for $ .POST which is an abbreviation for:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

This error is happening because you are making a request for the main.html $ .GET returns the requested data of the page. There are several ways you can do this, one that may be a possible solution is, the moment it checks the login to verificalogin.php , save the user id in a session variable from php or even the entire user with all the information you need .

$_SESSION['id'] = $usuarioId;  

Then when he entered the main page you could make a request to the bank to list all his information and then through php print all information,

<!-- 
     $usuario = array();
     $query = "SELECT * FROM user WHERE id = $_SESSION['id']";
     $resultado = mysqli_query($conexao,$query);
     while(mysqli_fetch_assoc($resultado) = $row){
          array_push($usuario,$row);
     }
     
 -->
<p><h3 id="user"> <?= $usuario['id']; ?> </h3></p>
 <div id="painel">
        <section class="icons">
          <a id="end1" href="<?=$usuario['href1']?>"><?= $usuario['link1'] ?><img alt="end link 1"/></a> 
		    </section>
        <section class="icons">
          <a id="end2" href="<?=$usuario['href1']?>"><?=$usuario['link2']?><img alt="end link 2"/></a> 
		    </section>

I DO NOT RECOMMEND TO WRITE QUERYS DIRECTLY INTO A VIEW It would be best if you had an API or a class that takes care of this, but that will work as well.

And if you still prefer to make a request through AJAX to get the user's data then create a PHP page that will return that data, say it will be a page with the query written above, you could give a

<?php echo json_encode($usuario) ?>

in this way you would return a JSON with the user data which is the lightest format known to me for transfer / data exchange, and you could get this data through JQUERY in this way:

function loginsucesso(){
     $.getJSON("pegaInformacoesDoUsuario.php", function(dados){
        /* verifique como vem o formato do JSON e troque pela forma correta */
        console.log(dados)
        $("#user").text(dados.user);
        $("#end1").attr("href",dados.end1);
        $("#end2").attr("href",dados.end2);
      });
}
    
02.05.2017 / 02:36