Can't get into my $.getJSON - javascript

I've created a webpage in order to get a table based on both a json and a user entry.
I have a script in my home page but it doesn't enter in my $.getJSON while getvalues() works and I really don't understand why...
My home page :
<html>
<head>
<meta charset="utf-8" />
<script src="http://****/js/jQuery.js"></script>
<link rel="stylesheet" href="http://****/style/style.css"/>
<title>****</title>
<link href='http://fonts.googleapis.com/css?family=Audiowide|Artifika' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div class="contenu">
<form action="#" class="tableau"> <!--Creation du formulaire pour l'entree utilisateur-->
</br></br>Quel TI recherchez vous ?</br></br>
<table border=0>
<tr>
<td>Nom du TI</td>
<td>
<input type="text" name="nom_TI" id="Filtre_ti">
</td>
</tr>
<tr>
<td COLSPAN=1>
<button onclick="get_values()">GO</button>
</td>
</tr>
</table></br>
<table id="mon_tableau" border=1><tbody></tbody></table>
</form>
</div>
</body>
</html>
<script type="text/javascript">
function get_values(){
var titre_colindex = 0;
var json = "http://****/get_json.php?callback=?";
console.log(document.getElementById('Filtre_ti').value);
if(document.getElementById('Filtre_ti').value!=""){
$.getJSON( json , {'nom_TI' : document.getElementById('Filtre_ti').value}).done(function( json ) {
var myjson = json;
console.log(myjson);
newRow = document.getElementById('mon_tableau').getElementsByTagName('tbody')[0].insertRow(-1);
$.each(myjson[0], function(index, valeur){ //Pour chaque colonne
newCell = newRow.insertCell(titre_colindex);
newCell.innerHTML = index;
titre_colindex+=1;
console.log("premier for each");
});
$.each(myjson, function(i,ti){
var newRow;
var newCell;
newRow = document.getElementById('mon_tableau').getElementsByTagName('tbody')[0].insertRow(-1);
newCell = newRow.insertCell(0);
newCell.innerHTML = ti.TI;
console.log("deuxieme");
var i_colindex=1;
$.each(ti, function(index, valeur){
if(index != "TI"){
newCell = newRow.insertCell(i_colindex);
newCell.innerHTML = valeur;
i_colindex+=1;
}
});
}); //End each
}); //End getJSON
}
}
</script>
My get_json.php page :
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header("content-type: application/json");
$DB_HOST="****";
$DB_PORT="****";
$DB_USER="****";
$DB_PASS="****";
$DB_NAME="****";
$pdo = new PDO('mysql:host='.$DB_HOST.';port='.$DB_PORT.';dbname='.$DB_NAME, $DB_USER, $DB_PASS); //Connexion base de donnees
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Affichage des erreurs
$mon_tableau = array();
if (isset($_GET['nom_TI'])){
$ti = $_GET['nom_TI'];
$sql = "
SELECT ti.TI, ti.SYSTEM_TYPE, ti.SYSTEM_NAME, ti.ENTITY_IN_CHARGE
FROM technical_item ti
WHERE ti.TI LIKE '%$ti%';
";
//La connexion est lancee et stockee dans l'objet $pdo
$sth = $pdo->prepare($sql);
$sth->bindvalue(':ti','%'.$ti.'%', PDO::PARAM_STR); //On selectionne en fonction de la saisie de l'utilisateur
$sth->execute();
$result = $sth->fetchall(PDO::FETCH_ASSOC);
if($result){
foreach ($result as $donnees){
$mon_tableau[] = $donnees;
} //end foreach
}
}//end if
if(isset($_GET['callback'])){
echo json_encode($mon_tableau);
}
else {
$mon_tableau = array('error',true);
echo json_encode($mon_tableau);
}
?>
I've launched several tests : change script position, delete the if, fix a value for 'Filtre_ti' but I couldn't find a solution.
Would you know why I can't get into this $.getJSON ?
Thanks for your help,
Corentin.

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();
?>

PHP MySQL JavaScript

Please help me. Thanks
I have a form which contains function's javascript and in function's javascript contains html code.
My question is : how to send in database my form ?
This is my form :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Créer une facture</title>
<link rel="stylesheet" href="style.css" media="all" />
</head>
<body>
<form action="affiche.php" method="post">
<fieldset>
<legend>Contenu de la facture formation</legend>
<div id="ID_container">
<textarea name="prestation[]" rows="4"
placeholder="Prestation" required></textarea>
<input type="number" placeholder="Nombre de jours" name="nbjours[]" required>
<input type="number" placeholder="Tarif journalier" name="tarifjour[]" required>
</div>
<button onclick="ajout(this);">+ Ajouter une prestation</button>
<br/><br/>
<input type="submit" name="envoyer" value="Envoyer"/>
</fieldset>
</form>
<script src="js/fonct.js"></script>
</body>
</html>
This is function JS:
function ajout(element){
var container = document.getElementById('ID_container');
var str ='<span><textarea name="prestation[]" rows="4" type="text" placeholder="Prestation"></textarea> </span><span><input name="nbjours[]" type="number" placeholder="Nombre de jour"> </span><span><input name="tarifjour[]" type="number" placeholder="Tarif journalier"> </span><span><input type="button" onclick="suppression(this)"; value="x"></span><br/>';
var divNewExp = document.createElement("div");
divNewExp.innerHTML = str ;
container.appendChild(divNewExp);
}
function suppression(element){
var container = document.getElementById('ID_container');
container.removeChild(element.parentNode.parentNode);
}
Here i want send these data in database and displays data, but it is not work, data are not send in database :
<?php
require_once 'connexion.php';
// On vérifie si la variable existe et sinon elle vaut NULL
$prestation = isset($_POST['prestation']) ? $_POST['prestation'] : NULL;
$nbjours = isset($_POST['nbjours']) ? $_POST['nbjours'] : NULL;
$tarifjour = isset($_POST['tarifjour']) ? $_POST['tarifjour'] : NULL;
//On récupère les différentes valeurs sous forme d'une chaine de caractères séparées par une virgule
$prestation=implode(",", $_POST['prestation']);
$nbjours=implode(",", $_POST['nbjours']);
$tarifjour=implode(",", $_POST['tarifjour']);
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour)
VALUES ("'.$prestation.'", "'.$nbjours.'", "'.$tarifjour.'")');
$req->execute(array( 'prestation'=> $prestation,
'nbjours'=> $nbjours,
'tarifjour'=> $tarifjour));
echo "les données ont bien étés insérées dans la base de données";
$base = null;
?>
<tr>
<?= foreach((array)$req as $presta) ?>
<td class="desc"><?php echo $presta['prestation'] ?></td>
<td class="qty"><?php echo $presta['nbjours'] ?></td>
<td class="unit"><?php echo $presta['tarifjour'] ?></td>
<td class="total"><?php echo $presta['tarifjour'] * $presta['nbjours'] ?></td>
</tr>
You're trying to get data from INSERT request, and you're not using prepare/execute properly. It just can't work the way you made it.
As aynber said, you should read PDO documentation
Here is some tips that can help you out :
1. Fix your prepare statement / execute
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES (:prestation, :nbjours, :tarifjour)');
$req->execute(array(
':prestation' => $prestation,
':nbjours' => $nbjours,
':tarifjour' => $tarifjour
));
I guess you need to add one row for each of your prestation, not saving every added prestation in one row, so you have to update your query to reflect that
// generate request params
$params = [];
$values = '';
foreach ($_POST['prestation'] as $key => $prestation) {
$params[':prestation' . $key] = $prestation;
$params[':nbjours' . $key] = $_POST['nbjours'][$key];
$params[':tarifjour' . $key] = $_POST['tarifjour'][$key];
$values .= '(:prestation' . $key . ', :nbjours' . $key . ', :tarifjour' . $key . '),';
}
// remove trailing ","
$values = rtrim($values, ',');
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES ' . $values);
// insert every rows in DB
$req->execute($params);
2. Generate rows from posted data or fetch them from database
In this example, I'll only show you the first option
// prepare facturation data
$facturation[] = [
'prestation' => $prestation,
'nbjours' => $_POST['nbjours'][$key],
'tarifjour' => $_POST['tarifjour'][$key],
];
<?php foreach ($facturation as $presta) : ?>
<tr>
<td class="desc"><?= $presta['prestation'] ?></td>
<td class="qty"><?= $presta['nbjours'] ?></td>
<td class="unit"><?= $presta['tarifjour'] ?></td>
<td class="total"><?= $presta['tarifjour'] * $presta['nbjours'] ?></td>
</tr>
<?php endforeach; ?>
3. Fix your buttons to prevent submitting form when using + or x buttons
As Magnus Eriksson said, you need to add type="button" in your button elements.
In your index file, use
<button type="button" onclick="ajout(this);">+ Ajouter une prestation</button>
Instead of
<button onclick="ajout(this);">+ Ajouter une prestation</button>
In fonct.js, use
<button type="button" onclick="suppression(this)">x</button>
Instead of
<input type="button" onclick="suppression(this)"; value="x">
4. Check if every needed data exists before executing every other steps to prevent errors
Here's my full working affiche.php file (without variables check) :
<?php
require_once 'connexion.php';
// On vérifie si la variable existe et sinon elle vaut null
$prestation = isset($_POST['prestation']) ? $_POST['prestation'] : null;
$nbjours = isset($_POST['nbjours']) ? $_POST['nbjours'] : null;
$tarifjour = isset($_POST['tarifjour']) ? $_POST['tarifjour'] : null;
//On récupère les différentes valeurs sous forme d'une chaine de caractères séparées par une virgule
$prestation=implode(",", $_POST['prestation']);
$nbjours=implode(",", $_POST['nbjours']);
$tarifjour=implode(",", $_POST['tarifjour']);
// generate request params
$params = [];
$values = '';
$facturation = [];
foreach ($_POST['prestation'] as $key => $prestation) {
$params[':prestation' . $key] = $prestation;
$params[':nbjours' . $key] = $_POST['nbjours'][$key];
$params[':tarifjour' . $key] = $_POST['tarifjour'][$key];
$values .= '(:prestation' . $key . ', :nbjours' . $key . ', :tarifjour' . $key . '),';
// prepare facturation data
$facturation[] = [
'prestation' => $prestation,
'nbjours' => $_POST['nbjours'][$key],
'tarifjour' => $_POST['tarifjour'][$key],
];
}
// remove trailing ","
$values = rtrim($values, ',');
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES ' . $values);
$req->execute($params);
echo "les données ont bien étés insérées dans la base de données";
$base = null;
?>
<table>
<thead>
<tr>
<th>Prestation</th>
<th>Nb jours</th>
<th>Tarif /jour</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($facturation as $presta) : ?>
<tr>
<td class="desc"><?= $presta['prestation'] ?></td>
<td class="qty"><?= $presta['nbjours'] ?></td>
<td class="unit"><?= $presta['tarifjour'] ?></td>
<td class="total"><?= $presta['tarifjour'] * $presta['nbjours'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I hope it helps !

Strange behaviour of my javascript

Sorry for the vague title, but this behaviour is pretty hard to explain.
I have a form where I enter some information. When the user click the submit button (values "programma"), I call a javascript. I check that the info are correct and use AJAX to add a record in my local database. The strange behaviour is the following:
I fill up the form. The record doesn't exist in my DB. Everything works correctly and my record is inserted. Success: I write in the span tag "Esecuzione registrata correttamente!"
Then I try to insert the same record. Since it exists in my DB, the error gets notified correctly in my span: "Esiste un condannato con gli stessi dati"
At this point my form is still full of text, if the user want to correct his mistake and insert a non-existing record. What happens is that, when I change some input (and I'm sure that record doesn't exist in my DB) and click the submit button, literally nothing happens. I still see my error message "Esiste un condannato con gli stessi dati", even if I saw in my console that my AJAX worked correctly
programma.php (what you see in my screenshot)
<?php
session_start();
if(!isset($_SESSION["nickname"]) && !isset($_SESSION["password"]) ) {
header("location: index.php");
exit();
}
else
{
echo "<p> Sessione di ".$_SESSION["nickname"]." con password ".$_SESSION["password"]." </p>";
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="programma.css">
<style type="text/css">
.container {
width: 500px;
clear: both;
}
.container text {
width: 100%;
clear: both;
}
</style>
<title>RIPconvicts - Programma esecuzione</title>
</head>
<body>
<?php require 'snippets/menu.php'; ?>
<form>
<fieldset class="centered">
<legend>Programma nuova esecuzione</legend>
<label for="nome"> Nome* </label> <br>
<input type="text" name="nome" id="nome"> <br> <br>
<label for="cognome"> Cognome* </label> <br>
<input type="text" name="cognome" id="cognome"> <br> <br>
<label for="classe"> Classe* </label> <br>
<input type="text" name="classe" id="classe"> <br> <br>
<label for="materia"> Materia* </label> <br>
<input type="text" name="materia" id="materia"> <br> <br>
<label for="data">Data* </label> <br>
<input type="date" name="data" id="data"> <br> <br>
Note <br>
<textarea name="note" id="note" rows="6" cols="50"> </textarea> <br> <br>
<span id="avviso" style="color:red"></span> <br>
<input type="button" onclick="programma_esecuzione()" value="Programma">
</fieldset>
</form>
<?php require 'snippets/footer.php'; ?>
<script>
function programma_esecuzione() {
// Verifica che tutti i campi necessari siano stati riempiti
document.getElementById("avviso").innerHTML = "";
var nomi = ["nome", "cognome", "classe", "materia"];
var campi_mancanti = "";
for(var i=0; i<nomi.length-1; i++) {
if(document.getElementById(nomi[i]).value == "") {
campi_mancanti+=" "+nomi[i];
}
}
if(!Date.parse( document.getElementById("data").value )) {
campi_mancanti+=" data";
}
// Se ci sono campi mancanti, ritorna alla pagina principale
if(campi_mancanti!="") {
window.alert("Riempire i seguenti campi mancanti:"+campi_mancanti);
return;
}
// Se tutti i campi necessari ci sono, allora è possibile richiedere l'aggiunta del record
var xhttp;
xhttp = new XMLHttpRequest();
var nome = document.getElementById("nome").value;
var cognome = document.getElementById("cognome").value;
var classe = document.getElementById("classe").value;
var materia = document.getElementById("materia").value;
var data = document.getElementById("data").value;
var note = document.getElementById("note").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var risposta = this.responseText;
if(risposta.indexOf("Esecuzione registrata correttamente!") > -1) {
// Svuota tutti i campi
document.getElementById("nome").value = "";
document.getElementById("cognome").value = "";
document.getElementById("classe").value = "";
document.getElementById("materia").value = "";
document.getElementById("data").value = "";
document.getElementById("note").value = "";
}
document.getElementById("avviso").innerHTML = risposta;
}
};
xhttp.open("POST", "./snippets/programma_esecuzione.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("nome="+nome+"&cognome="+cognome+"&classe="+classe+"&materia="+materia+"&data="+data+"&note="+note);
}
</script>
</body>
</html>
programma_esecuzione.php (where I execute my query)
<?php
//Include
require 'connetti_a_DB.php';
// Variabili per il login
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$classe = $_POST["classe"];
$materia = $_POST["materia"];
$data = $_POST["data"];
$note = $_POST["note"];
/*echo $nome."<br>";
echo $cognome."<br>";
echo $classe."<br>";
echo $materia."<br>";
echo $data."<br>";
echo $note."<br>";*/
// Inizia una sessione
session_start();
$username = $_SESSION["nickname"];
$password = $_SESSION["password"];
// Stabilire e chiudere connessione
$conn = connetti_a_DB($username, $password);
// Verifica se c'è un record "clone"
$nome_completo = $nome." ".$cognome;
$sql = " SELECT *
FROM `lista`
WHERE `NOME_COMPLETO`='$nome_completo' OR
`CLASSE`='$classe' OR
`MATERIA` ='$materia' OR
`DATA` ='$data'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
echo 'Esiste un condannato con gli stessi dati';
}
else
{
$sql = "INSERT INTO `ripconvicts`.`lista` (`ID`, `NOME_COMPLETO`, `CLASSE`, `MATERIA`, `DATA`, `NOTE`)
VALUES (NULL, '$nome_completo', '$classe', '$materia', '$data', '$note')";
$result = $conn->query($sql);
echo "Esecuzione registrata correttamente!";
}
$conn->close();
// Salta alla pagina iniziale
//header("location: ../programma.php");
//exit();
?>

JavaScript not working properly in Safari

So i made this countdown generator; it's based on a PHP input to fill the JavaScript, the problem is that in Safari it doesn't show this:
or
Is there a way to fix it in Safari? I've been thinking of disabling that input when in Safari and enabling a more basic numbers one but I don't know how to detect, is there another fix?
My code:
Form page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://monopolo11.ninja/tests/css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://monopolo11.ninja/tests/js/dropdown.js"></script>
<title>Countdown Maker</title>
</head>
<body class="lato">
<?php include("assets/navbartools.html");?>
<div class="lato container-fluid text-center" id="contents">
<p>Introduce la fecha</p>
<form action="countdownres.php" method="get" >
Fecha:
<input type="date" name="datein">
<br/>
Hora:
<input type="time" action="countdownres.php" method="get" name="timein">
<p>Cuantos argumentos quieres que se visualicen:</p>
<input type="checkbox" name="mil" value="1">Milenios
<input type="checkbox" name="cen" value="1">Siglos
<input type="checkbox" name="dec" value="1">Decadas
<input type="checkbox" name="yr" checked value="1">Años
<input type="checkbox" name="mo" checked value="1">Meses
<input type="checkbox" name="wk" value="1">Semanas
</br>
<input type="checkbox" name="da" checked value="1">Dias
<input type="checkbox" name="h" checked value="1">Horas
<input type="checkbox" name="m" checked value="1">Minutos
<input type="checkbox" name="s" checked value="1">Segundos
<input type="checkbox" name="mili" value="1">Milisegundos
<input type="submit" class="center-block btn btn-primary">
</form>
</div>
</body>
</html>
Result page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://monopolo11.ninja/tests/css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://monopolo11.ninja/tests/js/countdown.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://monopolo11.ninja/tests/js/dropdown.js"></script>
<title>Countdown</title>
</head>
<body class="lato">
<?php include("assets/navbartools.html");?>
<?php
//variables
$date = $_GET[datein];
$date = explode('-', $date);
$time = $_GET[timein];
$time = explode(':', $time);
$hour = $time[0];
$minute = $time[1];
$year = $date[0];
$month = $date[1];
$day = $date[2];
$mil = 0;
$cen = 0;
$dec = 0;
$yr = 0;
$mo = 0;
$wk = 0;
$da = 0;
$h = 0;
$m = 0;
$s = 0;
$mili = 0;
//variables de get
$mil = $_GET[mil];
$cen = $_GET[cen];
$dec = $_GET[dec];
$yr = $_GET[yr];
$mo = $_GET[mo];
$wk = $_GET[wk];
$da = $_GET[da];
$h = $_GET[h];
$m = $_GET[m];
$s = $_GET[s];
$mili = $_GET[mili];
if ($mil == 1){
$mil = "countdown.MILLENNIA";
}
else{$mil=0;};
if ($cen == 1){
$cen = "countdown.CENTURIES";
}
else{$cen=0;};
if ($dec == 1){
$dec = "countdown.DECADES";
}
else{$dec=0;};
if ($yr == 1){
$yr = "countdown.YEARS";
}
else{$yr=0;};
if ($mo == 1){
$mo = "countdown.MONTHS";
}
else{$mo=0;};
if ($wk == 1){
$wk = "countdown.WEEKS";
}
else{$wk=0;};
if ($da == 1){
$da = "countdown.DAYS";
}
else{$da=0;};
if ($h == 1){
$h = "countdown.HOURS";
}
else{$h=0;};
if ($m == 1){
$m = "countdown.MINUTES";
}
else{$m=0;};
if ($s == 1){
$s = "countdown.SECONDS";
}
else{$s=0;};
if ($mili == 1){
$mili = "countdown.MILLISECONDS";
}else{$mili=0;};
?><h1 class="lato text-center">Cuenta Regresiva para el <?php echo $_GET[datein]." ".$_GET[timein];?>
<div id="cuenta" class="lato text-center text-capitalize"><strong></strong></div>
</h1>
<script>
//labels
countdown.setLabels(
' milisegundo| segundo| minuto| hora| dia| semana| mes| año| década| siglo| milenio',
' milisegundos| segundos| minutos| horas| dias| semanas| meses| años| décadas| siglos| milenios',
' y ',
' + ',
'Ahora');
//variables de fechas
var dia = <?php echo $day?>;
var mes = <?php echo $month?> - 1;
var year = <?php echo $year?>;
var hour = <?php echo $hour?>;
var minute = <?php echo $minute?>;
//variables de atributos que se mostraran
var mil = <?php echo $mil?>;
var cen = <?php echo $cen?>;
var dec = <?php echo $dec?>;
var yr = <?php echo $yr?>;
var mo = <?php echo $mo?>;
var wk = <?php echo $wk?>;
var da = <?php echo $da?>;
var h = <?php echo $h?>;
var m = <?php echo $m?>;
var s = <?php echo $s?>;
var mili = <?php echo $mili?>;
var ref =1000;
if (mili == 1){
ref = 1;
}
//countdown clock
var clock1 = document.getElementById("cuenta")
, tdy = new Date();
clock1.innerHTML = countdown(new Date(tdy.getFullYear(), tdy.getMonth(), tdy.getDate()) ).toString();
setInterval(function(){
clock1.innerHTML = countdown(new Date(year, mes, dia, hour, minute),null,mil | cen | dec | yr | mo| wk | da | h | m | s | mili ).toString();
},ref);
console.log(ref);
console.log(mili);
console.log(tdy);
</script>
</body>
</html>

Why the AJAX don't work here?

i'm trying to learn to use AJAX, so i search a tut about make a crappy login system with ajax and start to learn, the thing is i do some little modifications to it, (PDO instead my_sql for example) and is not working, seeing that tut over and over again doesn't seems to show why there is not working.
What happend than doesn't work?
Well, it moves me from the index.php page to the admin.php page instantly, it musn't be that way, if i'm correct, it must bring the data back to the index.php right?
it works if the AJAX doesn't exist, instead of bring the data from admin.php, it makes me move to that page, like if it was pure PHP and none AJAX involved in the script.
The PHP is not calling the AJAX, it just use header(location
Thats the problem.
Here is the code of all files:
index.php
<?php
session_start();
if($_POST){
include("3325d7a55a4550ee85156f5f9a6762bede9d3021.php");
$nombre = $_POST['login'];
$pw = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tuser WHERE USER = :USER");
$rslt = $stmt->execute(array(':USER' => $nombre));
$stmt->bindParam(':USER', $nombre, PDO::PARAM_STR);
$usuario = $stmt->fetch();
if ($usuario) {
$_SESSION['usuario_logeado'] = $usuario;
header('Location: admin.php');
} else {
$error = 'Usuario y/o password incorrecto.';
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Temporis</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$('#login-form').submit(function(e) {
e.preventDefault();
$.post('ajax.php', $(this).serialize(), function(resp) {
if(!resp.error) {
var html= '<h3>Hola, ' + resp.['NOMBR1'] + ' ' + resp.['NOMBR3'] + '!</h3>' + '<p>' +
'Logout' +
'</p>';
$('.sidebar').html(html);
} else {
var error = '<p class="error">' + 'Usuario y/o password incorrecto.' + '</p>';
$('#login-form .error').remove();
$('.actions').before(error);
};
}, 'json');
});
});
</script>
</head>
<body>
<h5>INDEX!!!</h5>
<center>
<?php if(!isset($_SESSION['usuario_logeado'])): ?>
<form id="login-form" action="" method="post" class="form-stacked">
<input type="text" name="login" id="login">
<input type="password" name="pwd" id="pwd">
<?php if(isset($error)): ?>
<p>
<?php echo $error ?>
</p>
<?php endif;?>
<input type="submit" value="Login" id="btn">
</form>
<?php else :?>
<h3>Hola, <?php echo $_SESSION['usuario_logeado']['NOMBR1'] .' '. $_SESSION['usuario_logeado']['NOMBR3'] ?></h3>
Logout
<?php endif;?>
<br />
<br />
<div class="sidebar"></div>
<br />
<br />
<div class="actions"></div>
<br />
<br />
Admin
<br />
<br />
<div id="RBUG"> Si tienes cualquier duda, problema tecnico o quieres dar una sugerencia usa el
<a href=RBuGFm.php>Reporte de Bugs</a> </div>
</center>
</body>
</html>
admin.php
<?php
session_start();
if(!$_SESSION['usuario_logeado']){
header('Location: index.php');
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Temporis</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/menu.js"></script>
</head>
<body>
<center>
<h4>TROLOLOLOLO!</h4>
<h3>Hola, <?php echo $_SESSION['usuario_logeado']['NOMBR1'] .' '. $_SESSION['usuario_logeado']['NOMBR3'] ?></h3>
Logout
<div id="RBUG"> Si tienes cualquier duda, problema tecnico o quieres dar una sugerencia usa el
<a href=RBuGFm.php>Reporte de Bugs</a> </div>
</center>
</body>
</html>
ajax.php
<?php
session_start();
include("3325d7a55a4550ee85156f5f9a6762bede9d3021.php");
$nombre = $_POST['login'];
$pw = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tuser WHERE USER = :USER");
$rslt = $stmt->execute(array(':USER' => $nombre));
$stmt->bindParam(':USER', $nombre, PDO::PARAM_STR);
$usuario = $stmt->fetch();
if ($usuario) {
$_SESSION['usuario_logeado'] = $usuario;
echo json_encode($usuario);
} else {
echo json_encode(array('error' => true));
}
?>
3325d7a55a4550ee85156f5f9a6762bede9d3021.php (conection.php)
<?php
$host = "localhost";
$user = "root";
$pss = "password";
$db = "somedb_name";
$authz = "authc";
// Los comandos auxiliares estan comentados para que no funcionen a menos que sean necesarios
// var_dump($_POST);
try{
$con = new PDO('mysql:host='.$host.';dbname='.$db,$user,$pss);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
// $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Success ";
}catch(PDOException $e){
echo $e->getMessage;
}
?>
logout.php
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
I don't know what can be the problem and i'm running out of ideas, so i'm trusting in your eyes and experience to solve my problem and learn how to do this stuff correctly..
Any comment, suggestion, question improvement or question about it for clarification, please feel free to say it, and i try to edit the post with the answer as soon as i can.
Thanks in advance

Categories