bug using session and jquery - javascript

In login and register php functions I'm using this line:
$_SESSION['username'] = $username;
If in jquery function I use username as var the session changes and Im not using sessions on jquery functions
For example I have a feed burner so I have 2 records for the feed number and email.
Im using as:
var nombre = $('#nombre').val();
var email = $('#email').val();
$.post(global_data.url + 'files/assets/php/ajax/feed.php', 'nombre=' + nombre + '&email=' + email, function(a){
I'm not having problemas with the session but if I change nombre for username like this:
var username = $('#username').val();
var email = $('#email').val();
$.post(global_data.url + 'files/assets/php/ajax/feed.php', 'username=' + username + '&email=' + email, function(a){
The session changes
This is my feed.php code:
require('../../../inc/config.php');
require('../../../libs/Plantilla.class.php');
$plantilla = new plantilla($serv,$user,$pass,$base,$url,$sitio);
$conexion = mysqli_connect($serv,$user,$pass,$base);
if ($_POST) {
$nombre = $Main->limpiar($_POST['nombre']);
$email= $Main->limpiar($_POST['email']);
if(isset($nombre) && !empty($nombre) && isset($email) && !empty($email)){
$hash = md5($nombre.$email);
$mysqli = $conexion;
$porter = $mysqli->query("SELECT * FROM feed where username = '$nombre' or email = '$email'");
if($porter->num_rows ==0){
if($mysqli->query('INSERT INTO `feed` (username, email, hash) VALUES (\''.$nombre.'\', \''.$email.'\', \''.$hash.'\')')){
die('1: <div class="dialog_box">Gracias por suscribirse a nuestro boletin</div>');
}else{
die('0: <div class="dialog_box">Ocurrió un error.</div>');
}
}else{
die('0: <div class="dialog_box">Ya estas Sucrito.</div>');
}
}else{
die('0: <div class="dialog_box">Por favor completa todos los campos</div>');
}
}else{
echo "<h1>404</h1>";
}
config.php
//Inicio de sesión
#session_start();
//Mostramos errores
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE ^ E_DEPRECATED);
ini_set('display_errors', TRUE);
//Definimos timezone
setlocale(LC_ALL,"es_ES");
date_default_timezone_set('America/Mexico_City');
define('ROOT_DIRECTORY', dirname(dirname(__FILE__)).'/');
//Datos MYSQL
$serv = "localhost";
$user = "angela";
$pass = "1q2w3e";
$base = "angela";
//conectamos..
$conexion_temporal = mysqli_connect($serv,$user,$pass,$base);
mysqli_set_charset("utf8");
if(!$conexion_temporal){
exit('<title>Error</title><body style="clear: both;background: #F6F6F6;padding: 2em 2em 1em;border: 1px solid #E7E7E7;-moz-border-radius: 5px;-webkit-border-radius: 5px;-o-border-radius: 5px;border-radius: 5px;"><h2 align="center" style="color:#222; font-size:25px; font-family:Century Gothic;">Error <br /><br />No se pudo establecer la conexión a la base de datos </h2></body>');
}
//Datos del sitio
$mysqli = $conexion_temporal;
$query = $mysqli->query('select * from config');
while ($row = $query->fetch_assoc()){$url = $row['url'];
$title = $row['title'];
$sitio = $row['sitio'];
$max_size = $row['max_size'];
$paypal = $row['email'];
}
//configuraciones extras
$PermitirImprecion = TRUE;
require(ROOT_DIRECTORY . '/libs/Main.class.php');
$Main = new Main($serv,$user,$pass,$base,$url,$sitio);
//json
function setJSON($data, $type = 'encode'){
require_once('JSON.php'); // INCLUIMOS LA CLASE
$json = new Services_JSON; // CREAMOS EL SERVICIO
if($type == 'encode') return $json->encode($data);
elseif($type == 'decode') return $json->decode($data);
}
$pfooter='fCBEZXZlbG9wZWQgYnkgPGEgaHJlZj0iaHR0cHM6Ly93d3cuZGF0dGFzb2x1dGlvbnMuY29tLm14
Lz9yZWY9c2l0ZV9hbmdlbGFtZWRpbmFfbXgiIHRhcmdldD0iYmxhbmsiPkRhdHRhIFNvbHV0aW9u
czwvYT4=';
$footer = base64_decode($pfooter);

Related

Problem with Javascript about taken or available username

I have a problem, I did a taken/available username status that work correctly, but when I want to disable my submit button, this isn't working, I don't know why, please help me.
HTML input :
<input onkeyup="checkUsername()" id="username" name="username" type="text" class="form-control" value="<?php echo $row['username'] ?>" placeholder="Nom d'utilisateur" required autocomplete="off">
Javascript :
<script>
function checkUsername() {
const username = document.getElementById("username").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "check_username.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = xhr.responseText;
const usernameMessage = document.getElementById("usernameMessage");
if (response === "Nom d'utilisateur disponible.") {
usernameMessage.innerHTML = "<span style='color:green;'>Nom d'utilisateur disponible.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = false;
} else if (response === "Ce nom d'utilisateur est déjà pris.") {
usernameMessage.innerHTML = "<span style='color:red;'>Ce nom d'utilisateur est déjà pris.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = true;
} else {
// gérer d'autres réponses ici
}
}
};
xhr.send("username=" + username);
}
</script>
PHP and MySQL :
<?php
session_start();
// Connexion à la base de données
include "./config.php";
// Vérification de la connexion
if ($mysqli->connect_errno) {
echo "Erreur de connexion à la base de données: " . $mysqli->connect_error;
exit();
}
// Récupération du nom d'utilisateur envoyé en POST
$username = $_GET['username'];
// Requête SQL pour vérifier si le nom d'utilisateur est déjà pris
$query = "SELECT COUNT(*) as count FROM users WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
// Vérification du résultat
header('Content-Type: application/json');
if ($count > 0) {
echo "<div class='usernameMessage no'>Ce nom d'utilisateur est déjà pris.</div>";
echo "<script> document.getElementById('submit-button').disabled = true; </script>";
} else {
echo "<div class='usernameMessage yes'>Ce nom d'utilisateur est disponible.</div>";
echo "<script> document.getElementById('submit-button').disabled = false; </script>";
}
// Fermeture de la connexion à la base de données
$mysqli->close();
?>
<style>
.usernameMessage {
}
.yes{
color: green;
}
.no {
color: red;
}
</style>
I tried to put
document.getElementById('submit-button').disabled = false;
but it doesn't work, maybe because something is enabling my button ...
There are many flaws in your code.
You are using $_GET method in PHP code but $_POST method in Javascript code.
PHP code response does not seem to adapt to Javascript code
Here is the corrected code
HTML
<input onkeyup="checkUsername()" id="username" name="username" type="text" class="form-control" value="<?php echo $row['username'] ?>" placeholder="Nom d'utilisateur" required autocomplete="off">
<div id="usernameMessage"></div>
<button type="submit" id="submit-button" disabled>Submit</button>
JavaScript:
function checkUsername() {
const username = document.getElementById("username").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "check_username.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
const usernameMessage = document.getElementById("usernameMessage");
if (response.available) {
usernameMessage.innerHTML = "<span style='color:green;'>Nom d'utilisateur disponible.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = false;
} else {
usernameMessage.innerHTML = "<span style='color:red;'>Ce nom d'utilisateur est déjà pris.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = true;
}
}
};
if (username.trim() !== '') {
xhr.send("username=" + username);
}
}
PHP:
session_start();
// Connexion à la base de données
include "./config.php";
// Vérification de la connexion
if ($mysqli->connect_errno) {
echo json_encode(['error' => "Erreur de connexion à la base de données: " . $mysqli->connect_error]);
exit();
}
// Récupération du nom d'utilisateur envoyé en POST
if (isset($_POST['username'])) {
$username = $_POST['username'];
// Requête SQL pour vérifier si le nom d'utilisateur est déjà pris
$query = "SELECT COUNT(*) as count FROM users WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
if ($stmt->execute()) {
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
// Vérification du résultat
if ($count > 0) {
echo json_encode(['available' => false]);
} else {
echo json_encode(['available' => true]);
}
} else {
echo json_encode(['error' => "Erreur lors de l'exécution de la requête SQL."]);
}
} else {
echo json_encode(['error' => "Le paramètre 'username' n'a pas été fourni."]);
}

Getting Undefined index when making a session

Hi I'm trying to make a session in my main page but its just giving me an error of undefined index in uniqueID line 5.
The connection between my webqr.js and server.php have no errors but when I tried to connect it to my wow.php it gives me an error of undefined index.
webqr.js Code
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID; }
server.php Code
session_start();
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
wow.php Code
<?php include('server.php');?>
<?php if (isset($_SESSION['unique_id'])) : ?>
Welcome User:
<input type="text" value="<?php echo $_SESSION['unique_id']; ?>" disabled>
<?php endif ?>
Now I'm receiving this error.
okay so this solve my own question.
session_start();
if(isset($_GET['uniqueID'])){
$uniqueID = " ";
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
}
I put my code in another if statement.

php and ajax JavaScript pagination comment system

Trying to build a commenting system. Were comments are posted with AJAX. With comment count with Pagination. I have success achieving both, but putting them together is another story. I have tried doing 2 ajax calls. One for getting records from the database and showing pagination. The other call for recording records to the database.
// this is the first ajax call to to get the results and show pagination buttons
<script>
function request_page(pn){
var two = <?php echo $img_id; ?>;
var showmax = <?php echo SHOWMAX; ?>; // results per page
var totalpages = <?php echo $totalpages; ?>;
//controls for pigmintation
var pagination_controls = document.getElementById("pagination_controls");
var results_box = document.getElementsByClassName(two)[0];
params = 'showmax=' + showmax + '&totalpages=' + totalpages + '&pn=' + pn + '&img_id=' + two;
request = new ajaxRequest()
request.open("POST", "response5.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
results_box.innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(totalpages != 1)
{
if( pn > 1){
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+totalpages+'</b> ';
if (pn != totalpages) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
<script> request_page(<?php echo $totalpages; ?>); </script>
/// the response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$curPage = (int) sanitizeString($_POST['pn']);
$showmax = (int) sanitizeString($_POST['showmax']);
$totalpages = (int) sanitizeString($_POST['totalpages']);
$z = (int) sanitizeString($_POST['img_id']);
if ($curPage < 1) {
$curPage = 1;
} else if ($curPage > $totalpages) {
$curPage = $totalpages;
}
$offset = ($curPage-1) * $showmax;
// var_dump($showmax);
$one = $showmax;
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
//fetch resuls
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
////ajax call # 2 is triggered when ever the comment form is submitted
<div>
<form method='post' id="form<?php echo $img_id; ?>" name="<?php echo $img_id; ?>">
<textarea class='lake' name='one' placeholder="Comment" id='<?php echo $img_id; ?>'></textarea>
<input id="submit" onclick="showUser(document.getElementById(<?php echo $img_id; ?>).value, <?php echo $img_id; ?>);" type="button" value="Submit">
</form>
</div>
//// the ajax call function
function showUser(a, b){
name = a;
two = b;
yes = "form" + two;
params = 'name1=' + name + '&two1=' + two;
request = new ajaxRequest()
request.open("POST", "response10.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementsByClassName(two)[0].innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
document.getElementById(yes).reset();
return false;
}
The response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
define('SHOWMAX', 5);
$q = sanitizeString($_POST['name1']);
$z = sanitizeString($_POST['two1']);
$b = sanitizeString($_SESSION['user_id']);
$sql = 'INSERT INTO img_comment (img_id, comment, user_id)
VALUES(:img_id, :comment, :user_id)';
// prepare the statement
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':img_id', $z, PDO::PARAM_INT);
$stmt->bindParam(':comment', $q, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $b, PDO::PARAM_INT);
$stmt->execute();
$OK = $stmt->rowCount();
$getCount = 'SELECT COUNT(*) FROM img_comment WHERE img_id ='. $z;
// submit query and store result as $totalPix
$total = $pdo->query($getCount);
$totalCount = $total->fetchColumn();
// var_dump($totalCount);
$total = (int)$totalCount;
$totalpages = (int) ceil($total/ SHOWMAX);
$offset = ($totalpages-1) * SHOWMAX;
$one = SHOWMAX;
if($totalCount > 0){
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
}

$.post JQuery not working

I have a problem with form. After i click Dodaj button nothing happens.
I've putted alert dialog to see when it stops and it stops after
$.post('dodaj_ztoner.php', post_data, function(response){
I have made similar forms with similar code (names and number of items was different) and it worked
alert('post'); is not displaying. so looks like problem is here $.post('dodaj_ztoner.php', post_data, function(response){
html code:
<body>
<div id="dialog" title="Błąd Wprowadzania!">
<p>Proszę uzupełnić podświetlone pola.</p>
</div>
<div class="container">
<fieldset id="contact_form">
<h2>Zużycie Tonera</h2>
<div id="zresult"></div>
<label for="id"><span>ID</span></label>
<input type="text" name="zid" id="zid" value="<?php
$zapytanie = "select max(id) as id from zuzycie_toner";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo $wynik['id']+1;
}
mysql_free_result($widok);
?>" disabled />
<label for="zdata"><span>Data wydania</span></label>
<input type="text" name="zdata" id="zdata" />
<label for="ilwyd"><span>Ilość wydrukowanych</span> </label>
<input type="text" name="ilwyd" id="ilwyd" />
<label for="drukarka"><span>Drukarka</span></label>
<select type="text" name="zdrukarka" id="zdrukarka" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from drukarki order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="toner"><span>Toner</span></label>
<select type="text" name="ztonery" id="ztonery" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from tonery order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="user"><span>Użytkownik</span> </label>
<select type="text" name="zuser" id="zuser" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwisko_imie as id from uzytkownicy order by nazwisko_imie";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[id]</option>";
}
mysql_free_result($widok);
?>
</select>
<label><span> </span>
<button type="submit" class=submit_btn" id="zsubmit_btn">Dodaj</button>
</label>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var divObj = $('#dialog');
divObj.dialog({
autoOpen: false
}
);
$( "#zdrukarka" ).selectmenu();
$( "#zuser" ).selectmenu();
$( "#ztonery" ).selectmenu();
$("#zdata").datepicker();
$( "button[type=submit]" )
.button()
$("#zsubmit_btn").click(function() {
//Pobieramy dane
var ztoner_id = $('input[name=zid]').val();
var ztoner_data = $('input[name=zdata]').val();
var ztoner_wydr = $('input[name=ilwyd]').val();
var ztoner_toner = $('select[name=ztonery]').val();
var ztoner_user = $('select[name=zuser]').val();
var ztoner_drukarka = $('select[name=zdrukarka]').val();
//Prosta walidacja (kolorujemy na czerwono pole jeśli jest puste
var proceed = true;
alert( '1');
//wszystko w porządku idziemy dalej
if(proceed)
{
//Dane do wysłania
post_data = {'ztonerID':ztoner_id, 'ztonerWydr':ztoner_wydr, 'ztonerData' :ztoner_data, 'ztonerToner' :ztoner_toner,
'ztonerUser':ztoner_user, 'ztonerDrukarka':ztoner_drukarka};
//Przesłanie danych poprzez AJAX
$.post('dodaj_ztoner.php', post_data, function(response){
alert( 'post');
//wczytanie danych zwrotnych JSON
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#zresult").hide().html(output).slideDown();
}, 'json');
} else divObj.dialog("open");
});
//resetujemy kolorowanie po zaczęciu pisania
});
</script>
PHP file:
<?php
include './includes/html_elements.php';
//pokaz_zmienna($_SERVER);
$db_link = connect_db();
if(!$db_link)
{
$out='<p>Brak połączenia z bazą danych</p>';
print_page($out, 'Baza książek');
exit;
}
if($_POST)
{
//Sprawdzamy czy jest to rządanie Ajax, jeśli nie..
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//Kończymy skrypt wysyłając dane JSON
$output = json_encode(
array(
'type'=>'error',
'text' => 'Rządanie musi przejść przez AJAX'
));
die($output);
}
//Sprawdzamy czy wszystkie pola zostały wysłane. kończymy skrypt jeśli nie (tutaj dodawaj więcej pól, które są wymagane)
if(!isset($_POST["ztonerID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'POLA SĄ PUSTE!'));
die($output);
}
//Pobieramy dane z formularza
$ztoner_id = filter_var($_POST["ztonerID"], FILTER_SANITIZE_STRING);
$ztoner_data = filter_var($_POST["ztonerData"], FILTER_SANITIZE_STRING);
$ztoner_wydr = filter_var($_POST["ztonerWydr"], FILTER_SANITIZE_STRING);
$ztoner_drukarka = filter_var($_POST["ztonerDrukarka"], FILTER_SANITIZE_STRING);
$ztoner_toner = filter_var($_POST["ztonerToner"], FILTER_SANITIZE_STRING);
$ztoner_user = filter_var($_POST["ztonerUser"], FILTER_SANITIZE_STRING);
//Dodatkowa validacja PHP (tylko dla pól wymaganych)
if(!is_numeric($ztoner_id)) //sprawdzamy czy telefon jest numeryczny
{
$output = json_encode(array('type'=>'error', 'text' => 'Tylko liczby są dozwolone'));
die($output);
}
die($output);
}
$zapytanie = "select idd from drukarki where nazwa = '$ztoner_drukarka'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_drukarka = $wynik['idd'];
}
mysql_free_result($widok);
$zapytanie = "select idu from uzytkownicy where nazwisko_imie = '$ztoner_user'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_user = $wynik['idu'];
}
mysql_free_result($widok);
$zapytanie = "select idt from tonery where nazwa = '$ztoner_toner'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_toner = $wynik['idt'];
}
mysql_free_result($widok);
$insert = "Insert INTO zuzycie_toner Values ($ztoner_id, '$ztoner_data', $ztoner_wydr, $ztoner_drukarka, $ztoner_toner, '$ztoner_user')";
$wykonaj = mysql_query($insert);
if ($wykonaj)
{
$output = json_encode(array('type'=>'message', 'text' => 'Dodano '.$drukarki_nazwa.' do tabeli'));
die($output);
}else{
$output = json_encode(array('type'=>'error', 'text' => 'Dodawanie nie powiodło się '.$insert));
die($output);
}
}
?>
Your page doesn't conatains any form tag, so simple use
<button class=submit_btn" id="zsubmit_btn">Dodaj</button> instead of input type = submit
This will Work!!!!

How to push data from database and see vote count after each data?

What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
On a different php file:
require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$connection = mysqli_connect('localhost', 'root', '', 'alsp');
$sql = mysqli_query($connection,"SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: start-quiz.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your username and submit</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<button class="btn btn-action" type="submit" value="finish">Submit</button>
</form>';
exit();
}
$singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()"class="btn btn-action">Submit</button></span>';
echo $output;
}
}
I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.

Categories