I want to create a test pattern in PHP using MySQL database.Here i want to fetch questions form database and display those in my html pages. Now i want to create a division with next button and when user clicks it should display the next question that fetched from database in the same division dynamically. i guess it can be achieved through jQquery or javascript but unable to get the logic.
can anyone help.
thanks in advance.
here is a sample code that i have tried to display multiple divisions with javascript.
this is my database structure,
fields : qid,question,opt1,opt2,opt3,opt4
this is php code for fetching data form database.
<?php
$result=executeQuery("select * from quest");
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
//echo $row['qid'];echo "<br/>";
echo $row['question']; echo "<br/>";
?>
<input type="radio" name="a1" value="'<?php echo $row['opt1']; ?>'" ><?php echo $row['opt1']; echo "<br/>"; ?>
<input type="radio" name="a1" value="'<?php echo $row['opt2']; ?>'" ><?php echo $row['opt2']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt3']; ?>'" ><?php echo $row['opt3']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt4']; ?>'" ><?php echo $row['opt4']; echo "<br/>";?>
<?php
}
}
?>
<input type="submit" name="submit" value="submit">
now this fetches all the rows at a time and displays it.
this is javascript
var x=1;
function myfunc(){
document.getElementById(x).style.display="block" ;
x++;
}
when i click on button every time,respected division is displayed, but i want to display all data within one common division when each time the button is clicked.
If you don't want to reload a page when clicking the next button, we can use a Javascript library called jQuery.
I would also suggest that you use prepared statement rather than using the deprecated mysql_* API.
Lets start first by re-establishing your mysql_* and turn it to mysqli_*:
/* ESTABLISH CONNECTION */
$con = new mysqli("Host", "username", "password", "database"); /* REPLACE NECESSARY DATA INSIDE */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest ORDER BY qid LIMIT 1")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4); /* BIND THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close();
} /* END OF PREPARED STATEMENT */
After we get the data, we can now put it inside your form.
<h1 id="question"><?php echo $question; ?></h1>
<input type="hidden" id="qid" value="<?php echo $qid; ?>">
<input type="radio" name="a1" id="op1" value="<?php echo $opt1; ?>"><span id="op1text"><?php echo $opt1; ?></span><br/>
<input type="radio" name="a1" id="op2" value="<?php echo $opt2; ?>"><span id="op2text"><?php echo $opt2; ?></span><br/>
<input type="radio" name="a1" id="op3" value="<?php echo $opt3; ?>"><span id="op3text"><?php echo $opt3; ?></span><br/>
<input type="radio" name="a1" id="op4" value="<?php echo $opt4; ?>"><span id="op4text"><?php echo $opt4; ?></span><br/>
<input type="submit" name="submit" id="submit" value="Next"> <!-- THIS SERVES AS THE SUBMIT AND NEXT BUTTON -->
Before you proceed, download the library here.
Now, we can create a script that will take the answer and go to the next question. We will submit the answer of the user to the database using AJAX.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script>
$(document).ready(function(){
$("#submit").click(function(){ /* WHEN SUBMIT IS CLICKED */
var qid = $("#qid").val(); /* GET THE question id */
var selected = $("input[type='radio'][name='a1']:checked");
if (selected.length > 0) { /* CHECK THE SELECTED RADIO BUTTON */
answer = selected.val();
}
$.ajax({
type: "POST", /* THE METHOD WE WILL BE USING TO PASS THE DATA */
url: "action.php", /* THIS IS WHERE THE DATA WILL GO */
data: {"questionid" : qid, "answer" : answer}, /* THE DATA WE WILL BE PASSING */
dataType : 'json',
success: function(result){ /* WHEN IT IS SUCCESSFUL */
/* THIS WILL REPLACE THE DATA IN OUR QUESTION PAGE */
$("#qid").val(result.questionid);
$("#question").html(result.question);
$("#op1").val(result.op1);
$("#op2").val(result.op2);
$("#op3").val(result.op3);
$("#op4").val(result.op4);
$("#op1text").html(result.op1);
$("#op2text").html(result.op2);
$("#op3text").html(result.op3);
$("#op4text").html(result.op4);
}
}); /* END OF AJAX */
});
});
</script>
Then, we can create the action.php which takes the data/answer from the question page.
<?php
if(isset($_POST["questionid"])){
/* INCLUDE OUR NEW ESTABLISHED CONNECTION HERE */
/* PUT HERE YOUR INSERT QUERY WHICH STORES THE USER'S ANSWERS */
/* THEN FETCH THE NEXT QUESTION */
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest WHERE qid > ? ORDER BY qid LIMIT 1")){
$stmt->bind_param("i", $_POST["questionid"]);
$stmt->execute();
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4);
$stmt->fetch();
$stmt->close();
} /* END OF PREPARED STATEMENT */
/* THIS SET OF DATA WILL REPLACE THE DATA IN OUR CURRENT QUESTION PAGE */
echo json_encode(array("questionid" => $qid, "question" => $question, "op1" => $opt1, "op2" => $opt2, "op3" => $opt3, "op4", => op4));
} /* END OF ISSET */
?>
if you dont want to implement with ajax. Then list all questions and use jQuery to display single div. Use 'click' functions on next button to display the next questions.
If you are going by this method, try the following instruction. Hope It will be simple for you.
Display all the questions and answers.
while($row=mysql_fetch_array($result)){ ?>
<li class="test " id="qid_<?php echo $row['id']; ?>" >
<?php echo $row['question']; /* here display the stuff */ ?></li>
<?php }
Create "prev" and "next" buttons.
<span class="prev_q">Prev</span>
<span class="next_q">Next</span>
Add this css( to make first question as active )
li.test { display:none; }
li.activequestion{ display:block;background:#cccccc; color:#c40001; }
Add the script to make prev, next buttons working
<script>
jQuery(document).ready(function(){
jQuery('li.test:first').addClass('activequestion');
jQuery('.next_q').click(function(){
var nonext=jQuery('.test:last').hasClass('activequestion');
if(nonext)
{ alert("no next available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').next().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
jQuery('.prev_q').click(function(){
var noprevious=jQuery('.test:first').hasClass('activequestion');
if(noprevious)
{ alert("no previous available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').prev().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
});
</script>
Related
I am a beginner on coding. I am working on a WordPress website using beaver builder theme. My challenge is to display a login form (when the user is not logged in) and the user name when he is logged in, to a specific area of the header that has a class "header-text".
Here is my php code located in a file named "file.php"
<?php
if(is_user_logged_in()) {
$user = wp_get_current_user();
$var1 = "<p>Welcome <?php echo $user->display_name; ?></p>
<p><a href='/login/login.php?logout=true'>Click here to log out</a></p>";
$var2 = "<form action='login.php' method='post'>
<input type='text" autocomplete='off' placeholder='Username' name='username'/>
<input type='text' autocomplete='off' placeholder='Password' name='password'/>
<button type='submit' value='Submit'>Submit</button>
</form>";
echo echo json_encode($var1);
} else {
echo echo json_encode($var2);
}
?>
Here is javascript
<script type="text/javascript">
jQuery(document).ready(function($){
function displayAccess() {
$.get("login/file.php");
return false;
}
if(<?php echo json_encode($var1); ?>) {
var variable1 = <?php echo json_encode($var1); ?>;
document.getElementByClassName("header-text").innerHTML = variable1;
}
if(<?php echo json_encode($var2); ?>){
var variable2 = <?php echo json_encode($var2); ?>;
document.getElementByClassName("header-text").innerHTML = variable2;
}
});
</script>
I need help to correct my script. Thanks!
in this case, javascript an jquery is not necessary, because the login status changes on reload, anyway.
all you need is a change in your php code:
<?php
/* put this to your template file (e.g. header.php) */
if(is_user_logged_in()) {
$user = wp_get_current_user();
/* change $var1 to echo it via html block inside php */
?>
<p>Welcome <?php $user->display_name; ?></p>
<p>Click here to log out</p>
<?php
/* cut $var2 because it is not accessible in the else clause */
} else {
/*
paste $var2 here and echo it
btw:
* For tags that are self-closing, the forward slash should have exactly one space preceding it (https://make.wordpress.org/core/handbook/best-practices/coding-standards/html/#self-closing-elements)
* use single or double quotes – make a decision!
*/
?>
<form action="login.php" method="post">
<input type="text" autocomplete="off" placeholder="Username" name="username" />
<input type="text" autocomplete="off" placeholder="Password" name="password" />
<button type="submit" value="Submit">Submit</button>
</form>
<?php
}
?>
I'm trying to make an image uploading website where users can post their images and other logged-in users can reply to them. I'm trying to make this using php, mysql and ajax. I'm actually following a tutorial and I have modified their code to suit my website. But everytime I click submit, the page seems to refresh because I'm redirected to the top of my website and the new comment is not posted on top of the old comments as I want it to and also there is no inserting of the information of the new comment in the commentstable in my database.
Here is the code:
This is the php file in which I display the image and print out the comments and set a textarea to input new comments by the user. In this file, I import a javascript file which contains a function called postcomment() that performs the ajax part. The comments table has a column called commentForImageId which stores the id of the image for which a particular comment is posted.
<?php
//image is displayed above this set of code with all the required data
date_default_timezone_set('Asia/Kolkata');//to set my country's timezone
?>
<form method="post" action="" onsubmit="return postcomment();">
<input type="hidden" id="imageId" value="<?php echo $imageId; ?>">
<input type="hidden" id="datetime" value="<?php echo date('Y-m-d H:i:s'); ?>">
<textarea id="comment" placeholder="Write comment"></textarea><br>
<button type="submit">post comment</button>
</form>
<div id="allcomments">
<?php
$sql= "SELECT * FROM commentstable ORDER BY datetime DESC";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$commentForImageId=$row['commentForImageId'];
if($commentForImageId==$imageId){
$username=$row['commentByUserName'];
$comment=$row['comment'];
$datetime=$row['datetime'];
?>
<hr>
<div class="comment_div">
<p class="comment"><?php echo $comment; ?></p>
<p class="username">Posted By:<?php echo $username; ?></p>
<p class="datetime"><?php echo $datetime; ?></p>
</div>
<hr>
<?php
}}?>
</div>
Here is the function that performs the ajax part. "commentsystem.php" performs the part of storing the data in the databse:
function postcomment(){
var comment = document.getElementById("comment").value;
var datetime = document.getElementById("datetime").value;
if(comment && datetime)
{
$.ajax
({
type: 'POST',
url: 'commentsystem.php',
data:
{
comment:comment,
datetime:datetime
},
success: function (response)
{
document.getElementById("allcomments").innerHTML=response+document.getElementById("allcomments").innerHTML;
document.getElementById("comment").value="";
}
});
}
return false;
}
Here is commentsystem.php. Here, "dbh.php" is the database handling file where the connection to the database is established:
<?php
session_start();
include 'dbh.php';
if(isset($_SESSION['id'])){//if user has logged in
if(isset($_POST['comment']) && isset($_POST['datetime']) && isset($_POST['imageId']))
{
//if user has submitted the comment
$comment=$_POST['comment'];
$datetime=$_POST['datetime'];
$imageId=$_POST['imageId'];
$username=$_SESSION['username'];
$userId=$_SESSION['id'];
$sql="INSERT INTO commentstable (commentForImageId, commentByUserId, commentByUserName, likes, numberOfReplies, comment, datetime) VALUES ('$imageId', '$userId', '$username', 0, 0, '$comment', '$datetime')";
$result=mysqli_query($conn,$sql);
?>
<div class="comment_div">
<p class="comment"><?php echo $comment; ?></p>
<p class="username">Posted By:<?php echo $username; ?></p>
<p class="datetime"><?php echo $datetime; ?></p>
</div>
<?php
exit;
}
}
else{
header("LOCATION: signup.php");
}
?>
Thank you very much for your help! I'm very new to this and am completely confused about what is going wrong!
Thanks in advance once again!
I would give the button a class for example postcomment and the call this $('.postcomment').click( function(){ $.ajax.... return false;})
Also make sure you set the $imageId as in commentsystem.php you require it to be set
So I've got a regular form
<form action="includes/send.php" method="post" onsubmit="return isValidForm()" />>
<h1>Opgeven workshops</h1>
<label for="name">Voornaam:</label>
<input type="text" autocomplete="off" id="name" name="firstname">
<label class="choice" data-id="1"><input type="checkbox" name="group1" value="use your apple1">use your apple<span class="left" ></span>
</label>---more stuff more stuff more stuff--
Now I submit the form I want to show the information the user filled in in the form like this
$f_name = $_POST['firstname'];
$l_name = $_POST['lastname'];
U hebt zich ingeschreven bij: <br />
Eerste workshop : <?php echo $first; ?><br />
Tweede workshop : <?php echo $second; ?><br />
Klopt dit?
<button type="submit" onclick="send()">Ja</button>
<button type="submit" onclick="noSend()">nee</button>
and when the user clicks on send it sends the information from the previous form to the query to insert it into the database. I'm trying to do this without having to make another 'hidden form' which submits it again because it is unnecessary code when you can just let the script 'wait' and continue with the script / insert functionallity when the button is pressed.
I tried setting a variable $submit= false; and inside the send function (which is in javascript) set submit to true but that doesn't seem to work because it automatically sets the variable to true without pressing the button.
function send(){
<?php $submit = true ?>
var submit = <?php echo $submit ?>;
console.log(submit);
}
if($submit){
echo 'submitted';
} else {
echo 'not true';
}
On your php side pass the values when calling your Javascript 'send()' function
<?php
$first = "First course";
$second = "Second course";
?>
U hebt zich ingeschreven bij: <br />
Eerste workshop : <?php echo $first; ?><br />
Tweede workshop : <?php echo $second; ?><br />
Klopt dit?
<!-- pass the required values into the function, this is just a basic implementation you could also use a loop to fill in the values -->
<button type="button" onclick="send(true, '<?php echo $first ?>', '<?php echo $second ?>')">
Ja
</button>
<button type="button" onclick="send(false)">
nee
</button>
For the receiving function you could implement something like this
<script type="text/javascript">
function send(submit){
//Get all arguments passed except the first variable, the submit boolean
var listOfVariablesToPost = Array.prototype.slice.call(arguments,1);
if(submit){
console.log("post");
console.log(listOfVariablesToPost);
/* Do POST here either by using XMLHttpRequest or jQuery AJAX/POST (Or any other way you like)*/
/* XMLHttpRequest: http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest */
/* jQuery POST https://api.jquery.com/jquery.post/ */
}else{
console.log("No post")
/* Don't post and do whatever you need to do otherwise */
}
}
</script>
This is a very simple implementation, but I hope it helps.
I have a webpage that needs to load data from a MySQL db into textboxes. So, the textboxes already exist and the values needs to be updated with those from the db. I have a JavaScript function for the button click, a PHP script to connect the db, but it doesn't seems to work. It just copies in the textboxes, but the value stored in the db.
Any idea what I do wrong?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
...
</style>
<script>
//LOAD DATA
function btn_load_Click(){
document.getElementById('item1').value ="<?php echo $row['item1'];?>" ;
document.getElementById('item2').value ="<?php echo $row['item2'];?>" ;
document.getElementById('item3').value ="<?php echo $row['item3'];?>" ;
document.getElementById('item4').value ="<?php echo $row['item4'];?>" ;
}
</script>
</head>
<body>
<?php
$servername = "something.com.mysql";
$username = "myName";
$password = "xxxx";
$dbname = "myDB"
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn){
die("Connection failed:".mysqli_connect_error());
}
else {
$sql = "SELECT item1, item2, item3, item4 FROM myTable";
$result = mysqli_query($conn, $sql);
$row = mysql_fetch_array($result);
}
mysqli_close($conn);
?>
<form id="form1" style="width:500px;" method="post">
<div><button type="button" id="btn_load" onClick="btn_load_Click();" ></button></div>
<div id="MyItems">
<div><input id="item1" type="text" value=""/></div>
<div><input id="item2" type="text" value=""/></div>
<div><input id="item3" type="text" value=""/></div>
<div><input id="item4" type="text" value=""/></div>
</div>
</form>
</body>
</html>
First things first.
Don't mix mysql_* API with mysqli_*. This will give error and problems.
Better if you could use prepared statement, as mysql_* is already deprecated.
PHP and Javascript is different with one another. You can't just assign a PHP value to Javascript variable.
I'll teach you step by step on how to achieve your goals using jQuery.
First, you have to download jQuery here.
The trick we can do is to hide the row we have fetched from your query using hidden inputs. You are also mixing mysqli_* API with mysql_*, so this is wrong. I'll also introduce to you prepared statement.
$mysqli = new mysqli($servername, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* START PREPARING YOUR QUERY */
if($stmt = $con->prepare("SELECT item1, item2, item3, item4 FROM myTable")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($item1, $item2, $item3, $item4); /* STORE THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULTS */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
Then we can store the fetched data to these hidden inputs.
<input type="hidden" id="hid-item1" value="<?php echo $item1; ?>">
<input type="hidden" id="hid-item2" value="<?php echo $item1; ?>">
<input type="hidden" id="hid-item3" value="<?php echo $item1; ?>">
<input type="hidden" id="hid-item4" value="<?php echo $item1; ?>">
After that, we can now create a script, which will get the values from our hidden inputs and put it in your textboxes when the button is clicked.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
$(document).ready(function(){ /* PREPARE YOUR SCRIPT */
$("#btn_load").click(function(){ /* WHEN THE BUTTON IS CLICKED */
/* GET THE VALUES OF THE HIDDEN INPUTS */
var hiditem1 = $("#hid-item1").val();
var hiditem2 = $("#hid-item2").val();
var hiditem3 = $("#hid-item3").val();
var hiditem4 = $("#hid-item4").val();
/* THEN PUT THEM INTO THE DESIGNATED TEXTBOXES */
$("#item1").val(hiditem1);
$("#item2").val(hiditem2);
$("#item3").val(hiditem3);
$("#item4").val(hiditem4);
});
});
</script>
You can also take a look at this jsfiddle for an example.
I have a PHP script that generates table rows with hidden input tags that have names like title1, title2 etc and price1, price2 etc. The user has the ability to remove and add rows as they see fit. My question is when I submit the rows how can I read those hidden inputs in order, either through PHP or Javascript?
EDIT: Sorry about the lack of detail. Here's some code:
The PHP that generates the rows
$result = mysql_query("SELECT * FROM `table`");
$i=0;
while ($list = mysql_fetch_array($result))
{
$i++;
$title = $list['title'];
$price = $list['price'];
$plu = $list['plu'];
?>
<tr id="row<?php echo $i; ?>"><td><input type="hidden" name="title<?php echo $i; ?>" value="<?php echo $title; ?>"></td></tr>
<tr><td><input type="hidden" name="price<?php echo $i; ?>" value="<?php echo $price; ?>"></td></tr>
<tr><td><input type="hidden" name="plu<?php echo $i; ?>" value="<?php echo $plu; ?>"> </td></tr>
<?php
}
?>
Now if users can remove rows, I know I can tell exactly how many rows there are, but when it comes time to read them and save them in order I'm lost.
I'm not sure you're guaranteed to get them in order based on location on the page, but since you can name the elements yourself, you could name them title[1], title[2], ...
For example:
<input type="hidden" name="title[1]" value="foo">
...
<input type="hidden" name="title[2]" value="bar">
This will allow you to access the submitted elements in PHP by, for example:
$_POST['title'][1], $_POST['title'][2], etc.
You can use only one or two (for title and price) hidden input rather separate inputs for each values...all you need to do is use some special characters like ';','#' as a delemeter to seperate each values.. and when user delete the row just remove that value from the entire string....you can do it easily using javascript..
so ultimately you will have to submit only one (or two) hidden values...