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

Asked

Viewed 18,344 times

2

Hello!

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

On the login.php page, I check if the e-mail and password data are correct and if they are, I redirect the user to the main.html page, otherwise redirect to the index.php page.

Page verificalogin.php :

<?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 page.html I have the 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 href of the tags (a) for $end1 and $end2.

$user, $end1 and $end2 are on the login.php checkpage and are PHP variables.

I tried to make:

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’s not working!!

Anyone who can help me, thank you! Vlw!

1 answer

7

That one link explains when using GET or POST, in JQUERY GET & POST are aliases or nicknames for the AJAX method, when Voce uses the $.GET This is an abbreviation for:

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

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

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

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

$_SESSION['id'] = $usuarioId;  

and then when it entered the main page you could make a request to the bank to list all its information and then through php print out all the 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 DON’T RECOMMEND WRITING QUERYS DIRECTLY IN A "VIEW" it would be better if you had an API or a class that took care of it, but that way it will also work.

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

<?php echo json_encode($usuario) ?>

this way you would return a JSON with user data which is the lightest format known to me of data transfer/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);
      });
}

  • Hi Reynnan, thanks for the reply! After making the changes you indicated, apache gave permission error 403. This was the first time this happened. Putting the link directly in the tag (a) goes in a good way. I changed the 'httpd.com' and 'httpd-vhosts.conf' files to require all granted, but it still has the same error.

  • can you post your code here? or you have some repository with it?

  • I edited the question and posted the two files, verificacad.php and main.php.

Browser other questions tagged

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