Opening a .html with window.location - javascript

I'm writing a simple login page in Ajax + Jquery
I have an error when I click on the button. And I don't understand why.
Uncaught SyntaxError: Unexpected end of input
At this line
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
There is my code
<?php
session_start();
//si le user a un session de ouverte
/*if(isset($_SESSION['connecté'])){
header('Location : success.html');
die();
}*/
if (isset($_POST['login'])) {
$connection = new mysqli('localhost','root','','monumap');
$email = $connection->real_escape_string($_POST['emailPHP']);
$password = $connection->real_escape_string($_POST['passwordPHP']);
$data = $connection->query("SELECT id FROM users WHERE email = '$email' AND password = '$password'");
if($data->num_rows >= 0) {//tout et ok -> connexion
$_SESSION['connecté'] = '1';
//$_SESSION['email'] = $email;
header('Location:'.$_SESSION['redirectURL']);
exit('<font color = "green">Connexion reussi...</font>');
}else{
exit('<font color = "red">Le Mot de passe / Email est inconnue </font>');
}
//exit($email . " = " . $password);
}
?>
<html>
<head>
<title>Monumap Connexion</title>
</head>
<body>
<form method="post" action="login.php">
<input type="text" id="email" placeholder="Email..."><br>
<input type="password" id="password" placeholder="Mot de passe..."><br>
<input type="submit" value="Log In" id="login">
</form>
<p id = "reponse"></p>
<div class="Bouton">
<?php if($_SESSION['connecté']==1){
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
}
?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('vos inputs sont vides');
else {
$.ajax(
{
url: 'login.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password
},
success: function (reponse) {
$("#reponse").html(reponse);
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>

echo '<input type="button" value="connexion" onclick="window.location.assign('."'http://localhost/loginmap/members/success.html'".');")/>';
It's cause you wrote quote character.
You can use this way as well.
echo '<input type="button" value="connexion" onclick="func()"/>';
?>
<script>
function func(){
window.location.assign("http://localhost/loginmap/members/success.html");
}
</script>

Related

javascript function is supposed to display php SESSION data but isn't called

I'm trying to make a regular old registration form for a website; and I'm trying to display the name of the logged-in user(if any) at the top of the page. However, the function that is supposed to update that field doesn't seem o be called at all, and I can't make heads or tails of it, nor of the error messages my console displays:
"Uncaught SyntaxError: Unexpected token < -- pagina_registrazione.php:36"
"Uncaught ReferenceError: update_name is not defined
onload -- pagina_registrazione.php:10"
here is the code:
<?php
require './config_db.php';
?>
<!DOCTYPE HTML>
<html lang = "it" >
<head>
<meta charset="utf-8">
<meta name = "keywords" content = "catcher, profilo, registrazione, utente">
<meta name="author" content="Luca Ballarati">
<link rel="stylesheet" href="./../stile/sottopagine.css" type="text/css" media="screen">
<title>pagina di registrazione</title>
</head>
<body onload=update_name>
<section>
<p id="spia_connessione">NOMEUTENTEQUI</p>
<p>Se hai già un'account <strong>clicca qui</strong> per accedere.</p>
<p>Altrimenti <strong>registrati</strong> compilando i campi qui sotto</p>
</section>
<div id="login_form">
<form name="registra" action="./pagina_registrazione.php" method="post">
<div>
<label><p>Nome Utente</p></label>
<input type="text" placeholder="nome_utente" name="username" required autofocus>
</div>
<div>
<label><p>Password</p></label>
<input type="password" placeholder="password" name="password" required>
</div>
<div>
<label><p>Conferma Password</p></label>
<input type="password" placeholder="conferma_password" name="passwordconfirm" required>
</div>
<input name="pulsante_invio" type="submit" value="Invia">
<?php
if(isset($_POST['pulsante_invio'])) {
$nomeutente = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['passwordconfirm'];
if ($password==$cpassword) {
$query = "SELECT * FROM utenti WHERE NomeUtente='$nomeutente'";
$esegui_query = mysqli_query($con,$query);
if(mysqli_num_rows($esegui_query)>0) {
echo '<script type="text/javascript">
window.alert("Nome Utente già usato: registrarsi con un diverso Nome Utente");
</script>';
}
else {
$query = "INSERT INTO utenti (NomeUtente,Password,Record,Partite)
VALUES('$nomeutente','$password',0,0)";
$esegui_query = mysqli_query($con,$query);
if ($esegui_query) {
$nome = $_SESSION['username'];
//porta l'utente alla pagina di login
echo '<script type="text/javascript">
window.alert("Utente registrato correttamente");
</script>';
//echo '<script type="text/javascript">
//document.getElementById("spia_connessione").innerHTML = "'$nome'";
//</script>';
}
else {
echo '<script type="text/javascript">
window.alert("Errore durante la registrazione");
</script>';
}
}
}
else {
echo '<script type="text/javascript">
window.alert("Password e Password di conferma devono essere uguali");
</script>';
}
}
?>
</form>
</div>
<script type="text/javascript">
function update_name() {
window.alert("nome utente aggiornato");
var nm = <?php echo $_SESSION['username']; ?>;
document.getElementById("spia_connessione").innerHTML = nm;
}
</script>
</body>
Please write this code on the top of your php file.
<?php
ob_start();
session_start();
?>

Ajax script not calling

Inside my page it works, doesn't refresh the page and it sends to the database exactly how I want it, however, when it sends, or has an error depending on the error it should highlight the box but it doesn't. Whenever I press the button I get this error in the console:
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(){
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var gender = $("#mail-gender").val();
var message = $("#mail-message").val();
var submit = $("#mail-sendEmail").val();
$(".form-message").load("mail.php", {
name: name,
email: email,
gender: gender,
message: message,
submit: submit
})
});
});
</script>
</head>
<body>
<form method="POST" action="mail.php">
<input type="text" name="name" id="mail-name" placeholder="Full name" value=""><br>
<input type="text" name="email" id="mail-email" placeholder="Email" value=""><br>
<select name="gender" id="mail-gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
<textarea name="message" id="mail-message" placeholder="Message" rows="8" cols="80"></textarea><br>
<button type="submit" name="sendEmail" id="mail-sendEmail">Send email</button>
<p class="form-message"></p>
</form>
</body>
</html>
mail.php
<?php
include('inc/db.php');
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmptyName = false;
$errorEmptyEmail = false;
$errorEmptyMessage = false;
$errorEmail = false;
if(empty($name) || empty($email) || empty($message)){
$errorEmpty = true;
if(empty($name)){
echo "<span class='form-error'> Please enter a name! </span><br>";
$errorEmptyName = true;
}
if(empty($email)){
echo "<span class='form-error'> Please enter an email! </span><br>";
$errorEmptyEmail = true;
}
if(empty($message)){
echo "<span class='form-error'> Please enter a message! </span><br>";
$errorEmptyMessage = true;
}
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "<span class='form-error'> Please enter a valid email! </span><br>";
$errorEmail = true;
}else{
echo "<span class='form-success'> Successfully sent! </span><br>";
DB::query('INSERT INTO contact VALUES(\'\', :name, :email, :gender, :message)', array(':name'=>$name, ':email'=>$email, ':gender'=>$gender, ':message'=>$message));
}
}else{
die("Error");
}
?>
<script>
$("#name, #email, #message, #gender").removeClass("input-error");
var $errorEmpty = "<?php echo "$errorEmpty" ?>";
var errorEmptyName = "<?php echo $errorEmptyName ?>";
var errorEmptyEmail = "<?php echo $errorEmptyEmail ?>";
var errorEmptyMessage = "<?php echo $errorEmptyMessage ?>";
var errorEmail = "<?php echo $errorEmail ?>";
if(errorEmpty == true){
if(errorEmptyName == true){
$("#name").addClass("input-error");
}
if(errorEmptyEmail == true){
$("#email").addClass("input-error");
}
if(errorEmptyMessage == true){
$("#message").addClass("input-error");
}
}else if(errorEmail == true){
$("#email").addClass("input-error");
}
if(errorEmpty == false && errorEmail == false){
$("#name, #email, #message").val('');
}
</script>
It doesn't call the script inside the mail.php script.

How to use header with Ajax

I'm creating a login checker using jQuery and Ajax, i'm calling query.php which verifies the username and password. And if they don't match, an alert will be shown, and if they are correct it will redirect the user to the other page.
The error message works just fine.
The problem is that when i enter correct username and password, the page doesn't redirect.
In my case i'm been redirected twice, from login.php to query.php then to groupes.php or seance.php
query.php
<?php
require('queries/dbsetup.php');
$username = $_POST['username'];
$password = $_POST['password'];
$type = "";
if (empty($username) || empty($password)) { ?>
<script>
sweetAlert("Oops...", "Veuillez remplir tous les champs !", "error");
</script>
<?php
} else {
echo $type;
switch ($_POST['type']) {
case 'etudiant' : $type = 'etudiant';break;
case 'enseignant' :$type = 'enseignant';break;
}
// Check the username and password
$query = "SELECT username FROM ".$type." where username = '".$username."' AND password ='".$password."' ;";
$set = mysqli_query($conn,$query);
$run = mysqli_fetch_array($set);
$id = $run['username'];
// Save the type
$_SESSION['type'] = $type;
if (!empty($id)) {
$_SESSION['user_id'] = $username;
switch ($type) {
case 'etudiant':
header('location: ../groupes.php',true);exit;break;
case 'enseignant':
header('location: ../seance.php',true);exit;break;
}
} else { ?>
<script>
sweetAlert("Oops...", "Le nom d'utilisateur et le mot de passe ne sont pas identique !", "error");
</script>
<?php
}
}
?>
login.php
<form action="query.php" method="post" id="e1" class="">
<h4>Nouvelle seance</h4>
<input name="username" placeholder="Username" type="text" class="form-control">
<input name="password" placeholder="Password" type="password" class="form-control">
<input name="type" placeholder="Type" type="text" class="form-control">
<button id="login">Login</button>
<p id="result"></p>
</form>
login.js
$('#e1').submit(function(){
return false;
});
$('#login').click(function(){
$.post(
$('#e1').attr('action'),
$('#e1 :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
You can achieve the desired behavior by telling the client to load the new page via javascript.
You can change these lines
switch ($type) {
case 'etudiant':
header('location: ../groupes.php',true);exit;break;
case 'enseignant':
header('location: ../seance.php',true);exit;break;
}
To
switch ($type) {
case 'etudiant':
?>
<script>
window.location = "../groupes.php";
</script>
<?php
exit;
break;
case 'enseignant':
?>
<script>
window.location = "../seance.php";
</script>
<?php
exit;
break;
}

Problems with retrieving database info through AJAX/jQuery using dynamic fields

I am creating dynamic input textbox fields through jQuery. When a user clicks the link, two input fields are created. On the left input, the user can type in a code (or DB table id) and on the right input, they should see the name related to the id as the result.
To accomplish this, I attached a 'blur' event that will make an AJAX request to a PHP script which will query the database to retrieve the information. However my code is not working.
Here's what I've tried so far:
consulta.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var contenedor = $("#contenedor");
var AddButton = $("#agregarCampo");
var x = $("#contenedor div").length + 1;
var FieldCount = x-1;
$(AddButton).click(function (e)
{
if(x)
{
FieldCount++;
$(contenedor).append('<div class="added"><input type="text" name="codigo[]" id="campo'+FieldCount+'" placeholder="Ingrese codigo ID '+ FieldCount +'"/><input type="text" name="nombre" id="nombre'+FieldCount+'" value=""></div>');
x++;
}
return false;
});
});
</script>
</head>
<body>
<div id="cliente">
<table>
<tr>
<td>
Codigo
</td>
</tr>
<tr>
<td>
<div id="contenedor">
<div class="added">
<input type="text" name="codigo[]" id="codigo" placeholder="Ingrese codigo ID" required/>
<input type="text" name="nombre" id="nombre" value="">
</div>
</div>
<p>
<a id="agregarCampo" href="#">Agregar Campo</a>
</p>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="cliente.js"></script>
</body>
</html>
cliente.js
$(function(){
$('#cliente').on('blur','#codigo',function(){
var id = $(this).parents('div').attr('id');
var valor = this.value;
if(valor.length>=1){
var consulta = $.ajax({
type:'POST',
url:'cliente.php',
data:{codigo:valor},
dataType:'JSON'
});
consulta.done(function(data){
if(data.error!==undefined){
$('#estado').html('Ha ocurrido un error: '+data.error);
return false;
} else {
if(data.nombre!==undefined){$("#cliente #nombre").val(data.nombre);}
return true;
}
});
}
});
});
cliente.php
<?php
$codigo=$_POST['codigo'];
$conexion=mysqli_connect("localhost","root","","gabu");
if (mysqli_connect_errno($conexion)) {
echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}
$registros=mysqli_query($conexion, "select * from estudiantes where estudiante_id='$codigo'") or
die("Problemas en el select:".mysqli_error());
if ($reg=mysqli_fetch_array($registros))
{
$return = array('nombre' => $reg['nombre_estudiante']);
} else {
$return = array('nombre'=>'No existe el registro');
}
die(json_encode($return));
?>
This is how it should look like. Please help. Thanks.
You have a few problems. The ones that stand out the most are the HTML IDs and Classes. Theres no reason to create IDs dynamically as you can use classes for reference. Also, in PHP, you should use the right syntax for mysqli and return a proper JSON, with headers.
This is what I would do:
HTML/JS:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $contenedor = $("#contenedor");
var $AddButton = $("#agregarCampo");
$AddButton.click(function (e) {
e.preventDefault();
var FieldCount = $contenedor.children('div').length + 1;
$contenedor.append('<div class="added">\
<input type="text" class="codigo_input" placeholder="Ingrese codigo ID ' + FieldCount + '"/>\
<input type="text" class="nombre_input" >\
</div>');
});
});
</script>
</head>
<body>
<div id="cliente">
<table>
<tr>
<td>
Codigo
</td>
</tr>
<tr>
<td>
<div id="contenedor">
<div class="added">
<input type="text" class="codigo_input" placeholder="Ingrese codigo ID" required/>
<input type="text" class="nombre_input" value="">
</div>
</div>
<p>
<a id="agregarCampo" href="#">Agregar Campo</a>
</p>
</td>
</tr>
</table>
</div>
<script>
$(function () {
$('#cliente').on('blur', '.codigo_input', function () {
var $container = $(this).closest(".added");
var valor = $(this).val();
if (valor.length >= 1) {
var consulta = $.ajax({
type: 'POST',
url: 'cliente.php',
data: {codigo: valor},
dataType: 'JSON'
});
consulta.done(function (data) {
if (data.error !== undefined) {
$('#estado').html('Ha ocurrido un error: ' + data.error);
return false;
} else {
if (data.nombre !== undefined) {
$container.find('.nombre_input').val(data.nombre);
}
return true;
}
});
consulta.error(function(a,b,c){
console.log(a);
console.log(b);
console.log(c);
});
}
});
});
</script>
</body>
</html>
PHP
$codigo = $_POST['codigo'];
$conexion = mysqli_connect("localhost", "root", "", "gabu");
if (mysqli_connect_errno()) {
echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}
$registros = mysqli_query($conexion, "select * from estudiantes where estudiante_id='$codigo'") or
die("Problemas en el select:" . mysqli_error($conexion));
if (mysqli_num_rows($registros) > 0) {
$reg = mysqli_fetch_assoc($registros);
$return = array('nombre' => $reg['nombre_estudiante']);
} else {
$return = array('nombre' => 'No existe el registro');
}
header('Content-Type: application/json');
echo json_encode($return);
I'd suggest to debug the frontend and backend separately.
I've rewritten the clinte.php to only display json
<?php
$codigo=$_POST['codigo'];
$return = $_POST;
$return = array('nombre' => 1337);
die(json_encode($return));
?>
and it seems it's working.
The question is if you're selecting by the ID column, should it be number?
Can you add your db structure as well?

add and retrieve record from mysql using ajax

As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors

Categories