Problem: My php form does not submit.
This is my page:
It has a php rendered list of colors:
<div class="table-container">
<div>
<table class="myTable" id="myTable">
<tr class="header">
<th>Variants</th>
<th>Size</th>
<th>Price (€)</th>
</tr>
<?php
$current_name = $_GET['prod-name'];
$get_product_det = "SELECT * FROM product_details WHERE product_name='$current_name' ORDER BY position";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$id = $row_product_det['id'];
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
$position = $row_product_det['position'];
echo "<tr data-index='$id' data-position='$position'>
<td><a id='$id'>$product_variant</a></td>
<td>$product_size</td>
<td>$product_price</td>
</tr>";
};
?>
</table>
</div>
Each color has a unique ID. Clicking on a color fires the AJAX script that works fine:
<div class='product-det-div' id='product_details'>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = function() {
var id = this.id;
var product_details = document.getElementById('product_details');
var request = new XMLHttpRequest();
request.open('POST', 'product_details.php?variant_id=' + id, true);
request.onreadystatechange = function() {
if (request.readyState === 4 & request.status === 200) {
product_details.innerHTML = request.responseText;
} else {
product_details.innerHTML = 'An error occurred during your request: ' + request.status + ' ' + request.statusText;
}
};
request.send();
};
};
</script>
</div>
When the ajax call happens, what happens to the URL of the page? I'm passing the ID of the color through the URL but when trying to GET it with PHP it seems it doesn't find it.
Here's the code of the page:
$current_id = $_REQUEST['variant_id'];
$get_product_det = "SELECT * FROM product_details WHERE id=$current_id";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
echo "
<form action='' method='post'>
<h2 style='margin-bottom: 20px;'>$product_variant</h2>
<div><label>Nome Prodotto</label><input value='$product_variant'></div>
<div><label>Dimensione</label><input value='$product_size' type='number' name='product_size'></div>
<div><label>Prezzo (€)</label><input value='$product_price' id='product_price' name='product_price'></div>
<button type='submit' name='edit_variant_btn'>Send</button>
</form>
";
if(isset($_POST['edit_variant_btn'])) {
$variant = $_POST['product_size'];
$current_id = $_REQUEST['variant_id'];
$update_size = "UPDATE product_details SET size = '$variant' WHERE id = '$current_id'";
$run_update = mysqli_query($con, $update_size);
if($run_update) {
echo "<script>window.open('variable_product.php?prod-name=Polycolor', '_self');</script>";
}
}
};
?>
Thank you for your time, any help appreciated.
EDIT: I tried all the changes you all adviced, also tried $_REQUEST["variant_id"] as Banujan Balendrakumar said, but still no result.
The only way I found to make it work was to change the form action from this:
<form action='' method='post'>
to
<form action='product_details.php?variant_id=$current_id' method='post'>
This way it works because on button click, it opens that page and gets the ID value from there but it's just a way to get around the problem...
Any other ideas?
It's working for me....
<div class="table-container">
<div>
<table class="myTable" id="myTable">
<tr class="header">
<th>Variants</th>
<th>Size</th>
<th>Price (€)</th>
</tr>
<?php
$con = new mysqli('localhost','root','','check');
$get_product_det = "SELECT * FROM product_details ORDER BY position";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$id = $row_product_det['id'];
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
$position = $row_product_det['position'];
echo "<tr data-index='$id' data-position='$position'>
<td><a id='$id'>$product_variant</a></td>
<td>$product_size</td>
<td>$product_price</td>
</tr>";
};
?>
</table>
</div>
<div class='product-det-div' id='product_details'>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = function() {
var id = this.id;
var product_details = document.getElementById('product_details');
var request = new XMLHttpRequest();
request.open('POST', 'product_details.php?variant_id=' + id, true);
request.onreadystatechange = function() {
if (request.readyState === 4 & request.status === 200) {
product_details.innerHTML = request.responseText;
} else {
product_details.innerHTML = 'An error occurred during your request: ' + request.status + ' ' + request.statusText;
}
};
request.send();
};
};
</script>
</div>
product details
<?php
$current_id = $_REQUEST['variant_id'];
$con = new mysqli('localhost','root','','check');
$get_product_det = "SELECT * FROM product_details WHERE id=$current_id";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
echo "
<form action='' method='post'>
<h2 style='margin-bottom: 20px;'>$product_variant</h2>
<div><label>Nome Prodotto</label><input value='$product_variant'></div>
<div><label>Dimensione</label><input value='$product_size' type='number' name='product_size'></div>
<div><label>Prezzo (€)</label><input value='$product_price' id='product_price' name='product_price'></div>
<button type='submit' name='edit_variant_btn'>Send</button>
</form>
";
if(isset($_POST['edit_variant_btn'])) {
$variant = $_POST['product_size'];
$current_id = $_REQUEST['variant_id'];
$update_size = "UPDATE product_details SET size = '$variant' WHERE id = '$current_id'";
$run_update = mysqli_query($con, $update_size);
if($run_update) {
echo "<script>window.open('variable_product.php?prod-name=Polycolor', '_self');</script>";
}
}
};
?>
Related
I have a page filter.php?category_id=1. It comes from a index.php <a href="filter.php?category_id=<?php echo $category_id; ?>"> I try to send category_id to file fetch_data.php.
filter.php
$(document).ready(function(){
filter_data(1);
function filter_data(page)
{
//$("#preloader").show();
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var filter_category = get_filter('filter_category');
var filter_material = get_filter('filter_material');
var filter_source_light = get_filter('filter_source_light');
var filter_dimming_options = get_filter('filter_dimming_options');
var filter_color_temperature = get_filter('filter_color_temperature');
var filter_degree_tightness = get_filter('filter_degree_tightness');
$.ajax({
//url:"fetch_data.php",
url:'fetch_data.php?category_id=<?php echo $_GET['category_id']; ?>',
method:"POST",
data:{action:action, filter_category:filter_category, filter_material:filter_material, filter_source_light:filter_source_light, filter_dimming_options:filter_dimming_options, filter_color_temperature:filter_color_temperature, filter_degree_tightness:filter_degree_tightness, page:page},
success:function(data){
$('.filter_data').html(data);
}
});
}
fetch_data.php
//$category_id = "1";
$category_id = $_GET['$category_id'] ?? '';
if(isset($_POST["action"])) {
$sql1 = "SELECT * ";
$sql1 .= "FROM photographs ";
$sql1 .= "WHERE category_id='" . $database->escape_string($category_id) . "' ";
I don't know what I'm doing wrong. When I set $category_id = "1"; or "2" everything works
Solution:
filetr.php
$(document).ready(function(){
filter_data(1);
function filter_data(page)
{
//$("#preloader").show();
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var filter_category = get_filter('filter_category');
var filter_material = get_filter('filter_material');
var filter_source_light = get_filter('filter_source_light');
var filter_dimming_options = get_filter('filter_dimming_options');
var filter_color_temperature = get_filter('filter_color_temperature');
var filter_degree_tightness = get_filter('filter_degree_tightness');
var category_id = "<?php echo $_GET['category_id']; ?> ";
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, filter_category:filter_category, filter_material:filter_material, filter_source_light:filter_source_light, filter_dimming_options:filter_dimming_options, filter_color_temperature:filter_color_temperature, filter_degree_tightness:filter_degree_tightness, page:page, category_id:category_id},
success:function(data){
$('.filter_data').html(data);
}
});
}
fetch_data.php
$category_id = $_POST['category_id'] ?? '';
if(isset($_POST["action"])) {
$sql1 = "SELECT * ";
$sql1 .= "FROM photographs ";
$sql1 .= "WHERE category_id='" . $database->escape_string($category_id) . "' ";
Imagine that I have 1 2 3 4pages in my table, then if I click the page 1 the number 1 will be background: black Then the problem is the whole pages will be black, when I executing. Please help me out of this problem. I want to change the background color of the page if what page I click. Tyia
Here's the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="table-responsive" id="pagination_data"></div>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagination.php",
method:"POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
$(".pagination_link").css({"background":, "black"});
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
$(".pagination_link").css({"background":, "black"});
});
});
</script>
PHP code:
<?php
//pagination.php
$connect = mysqli_connect("localhost", "root", "", "psbr");
$record_per_page = 6;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM accounts ORDER BY id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<div class='grid-container'>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<div class="grid-content">
<img src="../accounts/table/upload/'.$row['image'].'" class="grid-image">
</div>
';
}
$output .= '</div> <br /><div align="right">';
$page_query = "SELECT * FROM accounts ORDER BY id DESC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
So the issue i'm having is that when I click the post button nothing happens and a comment doesn't display or go to my database. I have checked for spelling mistakes and believe I have got them all.
This is my HTML form called community.php
<div class="page-container">
<?php
get_total();
require_once 'check_com.php';
?>
<form action="" method="post" class="main">
<label>Enter a Brief Comment</label>
<textarea class="form-text" name="comment" id="comment"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Post">
</form>
<?php get_comments(); ?>
</div>
This is my js script called global.js
$(document). ready(function() {
$(".child-comments").hide();
$("a#children").click(function() {
var section = $(this).attr("name");
$("#C-" + section).toggle();
});
$(".form-submit").click(function() {
var commentBox= $("#comment");
var commentCheck= commentBox.val();
if(commentCheck == '' || commentCheck == NULL) {
commentBox.addClass("form-text-error");
return false;
}
});
$(".form-reply").click(function() {
var replyBox= $("#new-reply);
var replyCheck= replyBox.val();
if(replyCheck == '' || replyCheck == NULL) {
replyBox.addClass("form-text-error");
return false;
}
});
$("a#reply").one("click", function() {
var comCode = $(this).attr("name");
var parent = $(this).parent();
parent.append("<br / ><form actions='' method='post'><textarea class='form-text' name='new-reply' id='new-reply' required='required'></textarea><input type='hidden' name='code' value='"+comCode"' /><input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply'/></form>")
});
})
Check_com.php file
<?php
// new comment fucntion
if(isset($_POST['new_comment'])) {
$new_com_name = $_SESSION['user'];
$new_com_text = $_POST['comment'];
$new_com_date = date('Y-m-d H:i:s');
$new_com_code = generateRandomString();
if(isset($new_com_text)) {
mysqli_query($conn, "INSERT INTO `parents` (`user`, `text`, `date`, `code`) VALUES ('$new_com_name', '$new_com_text', '$new_com_date', '$new_com_code')");
}
header ("Location: ");
}
// new reply
if(isset($_POST['new_reply'])) {
$new_reply_name = $_SESSION['user'];
$new_reply_text = $_POST['new-reply'];
$new_reply_date = date('Y-m-d H:i:s');
$new_reply_code = $_POST('code');
if(isset($new_reply_text)) {
mysqli_query($conn, "INSERT INTO `children` (`user`, `text`, `date`, `par_code`) VALUES ('$new_reply_name', '$new_reply_text', '$new_reply_date', '$new_reply_code')");
}
header ("Location: ");
}
?>
Functions.php File
<?php
session_start();
$_SESSION['user'] = 'Admin';
function get_total() {
require 'includes/dbh.inc.php';
$result = mysqli_query($conn, "SELECT * FROM `parents` ORDER BY `date` DESC");
$row_cnt = mysqli_num_rows($result);
echo '<h1>All Comments ('.$row_cnt.')</h1';
}
function get_comments() {
require 'includes/dbh.inc.php';
$result = mysqli_query($conn, "SELECT * FROM `parents` ORDER BY `date` DESC");
$row_cnt = mysqli_num_rows($result);
foreach($result as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$user = $item['user'];
$comment = $item['text'];
$par_code = $item['code'];
echo '<div class="comment" id="'.$par_code.'">'
.'<p class="user">'.$user.'</p> '
.'<p class="time">'.$date.'</p>'
.'<p class="comment-text">'.$comment.'</p>'
.'<a class="link-reply" id="reply" name="'.$par_code.'">Reply</a>';
$chi_result = mysqli_query($conn, "SELECT * FROM `children` WHERE `par_code`='$par_code' ORDER BY `date` DESC");
$chi_cnt = mysqli_num_rows($chi_result);
if($chi_cnt == 0){
}else {
echo '<a class="link-reply" id="children" name="'.$par_code.'"><span id="tog_text">replies</span> ('.$chi_cnt.')</a>'
.'<div class="child-comments" id="C-'.$par_code.'">';
foreach ($chi_result as $com) {
$chi_date = new dateTime($com['date']);
$chi_date = date_format($chi_date, 'M j, Y | H:i:s');
$chi_user = $com['user'];
$chi_com = $com['text'];
$chi_par = $com['par_code'];
echo '<div class="child" id="'.$par_code.'-C">'
.'<p class="user">'.$chi_user.'</p> '
.'<p class="time">'.$chi_date.'</p>'
.'<p class="comment-text">'.$chi_com.'</p>'
.'</div>';
}
echo '</div>';
}
echo '</div>';
}
}
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characterLength = strlen($characters);
$randomString = '';
for($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $characterLenght - 1)];
}
return $randomString;
}
?>
Either remove action="" or change it to action="community.php"
I have a table with the following.
Table parts_stock
*--------------------*
| id | sku | stock |
| 1 | 101 | 2 |
| 2 | 102 | 3 |
*--------------------*
This is my code so far, i'm sure there are many ways to achieve this but ideally I want the qty value to change based on which button is clicked on without the page being refreshed (AJAX probably).
<tbody>
<?php
$query = 'SELECT stock_id, sku, in_stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['stock_id'];
$sku = $row['sku'];
$qty = $row['in_stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td>".$qty."</td>";
echo "<td>
<a href='' onclick='rem_qty()' id='minus' name='minus' class='btn btn-warning'><span class='glyphicon glyphicon-minus'></span></a>
<a href='' onclick='add_qty()' id='plus' name='plus' class='btn btn-success'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
</td>";
}
}?>
</tbody>
ajax_search.js
<script>
function rem_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: {id_m: stock_id}
});
}
function add_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: 'id_p: stock_id'
});
}
</script>
update_qty.php file
<?php
if (isset($_POST['id_m'])) {
$r = $_POST['id_m'];
echo $r;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$r."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$rem_stock = $row['in_stock'];
$rem_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$rem_stock."' WHERE stock_id = '".$value."'";
$inv_query = mysqli_query($connection, $inv_update);
}
if (isset($_POST['id_p'])) {
$a = $_POST['id_p'];
echo $a;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$a."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$add_stock = $row['in_stock'];
$add_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$add_stock."' WHERE stock_id = '".$value."'";
}
?>
A simple and complete solution: just change mysqli_connect config in both page
index.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); //change dbname
$query = 'SELECT id, sku, stock FROM parts_stock';
//confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
?>
<table>
<tr>
<th>Sku</th>
<th>Stock</th>
<th>Action</th>
</tr>
<?php if($num>0){
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td class='stock-{$id}'>".$qty."</td>";
echo "<td>
<a class='btn btn-warning' onclick='add_qty({$id})' href='#'><span class='glyphicon glyphicon-minus'>Value Add</span></a>
<a class='btn btn-success' onclick='rem_qty({$id})' href='#'><span class='glyphicon glyphicon-plus'>Value Deduct</span></a>
</td>";
echo "</tr>" ;
}
}?>
</table>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
function add_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'add'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
function rem_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'rem'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
</script>
update_qty.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); ////change dbname
header('Content-Type: application/json');
$success = false; $msg ="";
if (isset($_POST['id'])) {
$id = $_POST['id'];
$cur_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$cur_query = mysqli_query($connection, $cur_inv);
if(mysqli_num_rows($cur_query)>0){ //if id is exist in database
if($_POST['type']=="add"){
$inv_update = "UPDATE parts_stock SET stock = (stock+1) WHERE id = {$id}"; //increase your stock dynamically
}elseif($_POST['type']=="rem"){
$inv_update = "UPDATE parts_stock SET stock = (stock-1) WHERE id = {$id}"; //increase your stock dynamically
}
$inv_query = mysqli_query($connection, $inv_update);
if($inv_query){ //If sucess
$msg = "Successfully Updated";
$success = true;
}else{ //if failed
$msg = "Failed to Update";
}
}else{
$msg="Id is not found.";
}
$last_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$last_query = mysqli_query($connection, $last_inv);
$row = mysqli_fetch_assoc($last_query);
echo json_encode(array('success'=>$success, 'msg'=>$msg, 'data'=>$row));
}
?>
No need extra js file just index.php and update_qty.php
Working example
demo.php
<?php
$query = 'SELECT id, sku, stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
$data = "";
$data .= "<tr>";
$data .= "<td>{$sku}</td>";
$data .= "<td>{$qty}</td>";
$data .= "<td>
<a class='btn btn-warning' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-minus'></span></a>
<a class='btn btn-success' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
echo $a;
exit;
}
}?>
AJAX:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<table >
<tr>
<th>Id</th>
<th>Sku</th>
<th>Qty</th>
</tr>
<tbody id="mytable">
</tbody>
</table>
<button id="clickme">Click</button>
<script>
$(document).ready(function(){
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"GET",
beforeSend:function() {
$("#mytable").empty();
},
success:function(response){
$("#mytable").append(response);
}, error:function(err) {
console.log(err);
}
})
});
});
In your HTML Button to have a onClick event like this onclick="buttonSubtract1('<?php if(isset($val['itm_code'])){echo $val['itm_code'];}?>')"(You can fetch the itm_code from your db).Then Write your AJAX for Request and Response. And You need to Pass the itm_code through var x. e.g for like this xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
In AJAX file
$item_cat = $_SESSION['item_cat']; // get a category from session
$iname=$_GET['val']; //get the value from main php file
if(!key_exists($item_cat)
{
$_SESSION['main'][$iname] = "1";
}
else
{
$_SESSION['main'][$item_cat][$iname]++;
}
echo "<pre>";
print_r($_SESSION['main']);
echo "</pre>";
EDIT 1
function buttonSubtract1(x)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.location.assign('items.php');
}
}
xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
xmlhttp.send();
}
<?php
$singleSQL = mysql_query("SELECT * FROM questions WHERE subject_id='$subject' AND question_id='$question'");
$row = mysql_fetch_array($singleSQL);
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysql_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="checkbox" 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()">Atsakyti</button></span>';
echo $output;
?>
Doesn't POST questions on selected subject. The do not find the question in database, because questions have different subject ID and it's not in any order.
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 = '';
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("post", "questions.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send("subject=<?php echo $subject; ?>&question=<?php echo $next; ?>");
}
}
p.send(vars);
}
this is the function that button triggers
check your query. $question_id missing.
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question_id' ORDER BY rand()");