So i have a form that that does a simple calculation, depending on the users input. If the results is a certain value then it stores that value in a database, then it displays that value on a page. But i have to refresh the whole page for it to retrieve the latest updated value from the the database and display on the page.
I know how to write code to refresh the whole page, but in this case i only need the section where the it displays to be refreshed.
The original form to calculate
<div class="formC">
<form action="" method="post">
<label>Base Amount</label>
<input type="text" name="base"</input>
<label>Select Currency</label>
<div class="custom-select">
<span></span>
<select name="cur_name">
<option value="" selected>Choose a Base Currency</option>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
</select>
</div>
<button type="submit" value="Submit">SUBMIT</button>
</form>
</div>
The form that gets the new values from the database
<div class="formC">
<form action="test.php" method="post">
<label>Base Amount</label>
<input type="text" name="base" id="new_base" value="<?php
$results = mysqli_query($con, "SELECT * FROM contents_arr ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["new_base"];
}
?>">
<div id="load_data"></div>
<label>Select Currency</label>
<input type="text" name="cur_name" value="<?php
$results = mysqli_query($con, "SELECT * FROM gain_name_table ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["gain_name"];
}
?>">
<button id="btn_submit" type="submit" value="Submit">SUBMIT</button>
</form>
</div>
Calculation
<?php
$base = $_POST['base'];
$value = $_POST['val'];
$selected = $_POST['cur_name'];
if ($selected == 'EUR') {
$results_eur = $base * $value;
// USD
}elseif ($selected == 'USD') {
$results_usd = $base * $value;
}
if($selected == 'EUR'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_eur."')";
mysqli_query($con,$sql);
}elseif($selected == 'USD'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_usd"')";
mysqli_query($con,$sql);
}
I managed to find the solution for this code using Ajax and jQuery:
$(document).ready(function(){
$('#btn_submit').click(function(){
var get_data = $('#new_base').val();
if($.trim(get_data) != '')
{
$.ajax({
url:"db2.php",
method:"POST",
data:{new_base:get_data},
dataType:"text",
success:function(data)
{
$('#new_base').val("");
}
});
}
});
setInterval(function(){
$('#load_data').load("fetch.php").fadeIn("slow")
}, 1000);
});
This can be done by creating a seperate php file and replacing the content on your page with the content of that other php page using javascript. This is not a full description on how to do it, just a hint on how this is done. There are plenty of resources where it is described in detail.
One place to start could be here W3Schools Ajax & Php
getData.php
header('Content-Type: application/json; charset=utf-8');
// do your php database stuff here
$data = //...
$data = json_encode($data);
echo $data;
And in your main file, you can fetch() the content of your getData.php in javascript to get the latest result and then inject the results into your div using document.getElementById('content').innerHTML = ...
Using this method, only your div refreshed, not the whole page.
Related
I'm doing a program where I have several exercises with their id (e.g. Id = 1, 2, 3 ...) What I would like to do is that once the user is in an exercise, he can press the Next button and take him to the next exercise, for example id + 1.
Below I show what I've done. Can you help me?
This is my modified question, now it works:
<?php
include_once("functions.php");
// Start the session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
/*echo*/ $id=$_GET['id']; // Current question
$sql = "SELECT * FROM exercises where exercise_id='$id'";
$result = $conn->query($sql); /*Check connection*/
$question_ids = [];
$result2 = doSearch($conn, 'exercise_id');
while($row = $result2->fetch_assoc()) {
array_push($question_ids, $row["exercise_id"]);
}
$order = $_GET['order'];
$next_question_id = -1;
$next_question_order = $order + 1;
if (count($question_ids) >= $next_question_order) {
$next_question_id = $question_ids[$order];
}
?>
<div id="centered_B" class="header">
<?php
$row = $result->fetch_assoc();
?>
<p><?php echo $row["exercise_id"] . ". " . $row["text"]?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"]?>"><br/><br/>
<form action='' method='post'>
<input type="radio" name="choice" value= "1" /><img src="<?php echo $row["image_path_A"] ?>"/><br>
<input type="radio" name="choice" value= "2" /><img src="<?php echo $row["image_path_B"] ?>"><br>
<input type="radio" name="choice" value= "3" /><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p2>Select difficulty level:</p2>
<form action='' method='post'>
<select name="choose" id="choose">>
<option value="1" <?php if($row["difficulty"]=="1") { echo "selected"; } ?> >1</option>
<option value="2" <?php if($row["difficulty"]=="2") { echo "selected"; } ?> >2</option>
<option value="3" <?php if($row["difficulty"]=="3") { echo "selected"; } ?> >3</option>
<option value="4" <?php if($row["difficulty"]=="4") { echo "selected"; } ?> >4</option>
<option value="5" <?php if($row["difficulty"]=="5") { echo "selected"; } ?> >5</option>
</select>
<br><br><br>
<input class="buttonSubmit" type="submit" name="submit" value="Submit">
<?php
if ($next_question_id >= 0) {
?>
<a href="?id=<?php echo $next_question_id; ?>&order=<?php echo $next_question_order; ?>" class="buttonNext" >Next Question</a>
<?php
}
?>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
$user_id = $_SESSION['user_id'];
$user_check_query = "SELECT * FROM users WHERE id='$user_id'";
if(isset($_POST['choice'], $_POST['choose'])){
$choice_answer=$_POST['choice'];
$difficulty=$_POST['choose'];
// */$user_id = $_SESSION['user_id'];*/
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES ('$id','$user_id', '$difficulty', '$choice_answer')";
$sql=mysqli_query($conn,$query);
}
}
?>
Not sure what your JS or PHP level is, but here's a pure PHP solution - not using JS.
Things to notice:
Using PDO parameterized queries to secure against SQL injection
Using a hidden form field to pass around the current question ID. After the user submits, we insert their response in the DB, and then redirect to the next question by incrementing $id++
You had 2 <form> tags. I removed one.
Please note, this code is not tested. Let me know if you have any questions. Good luck!
<?php
session_start();
// Using PDO instead of mysqli. Nothing wrong with mysqli but I'm more comfortable with PDO.
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// This is your connection to the DB.
$pdo = new PDO($dsn, $user, $pass, $opt);
// This is the current question being displayed to the user.
$id = $_GET['id'];
// You should probably do some validation on $id here. Should it be numeric, not null etc.
// Notice that we're using ? instead of passing the value directly to the DB. This is called prepared statements.
// https://phpdelusions.net/pdo#prepared
$stmt = $pdo->query('SELECT * FROM exercises where exercise_id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// You should also validate the $row here. Did you actually find a question from the DB?
?>
<div id="centered_B" class="header">
<p><?php echo $row["exercise_id"] . ". " . $row["text"] ?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"] ?>"><br/><br/>
<!-- Changed the method to GET -->
<form action="" method="GET">
<!-- Notice that we're passing the question ID to server when the form submits. -->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<label>
<input type="radio" name="choice" value="1"/>
</label><img src="<?php echo $row["image_path_A"] ?>"/><br>
<label>
<input type="radio" name="choice" value="2"/>
</label><img src="<?php echo $row["image_path_B"] ?>"><br>
<label>
<input type="radio" name="choice" value="3"/>
</label><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p>Select difficulty level:</p>
<label for="choose"> Difficulty
<select name="choose" id="choose">>
<option value="1" <?php if ($row["difficulty"] == "1") {
echo "selected";
} ?> >1
</option>
<option value="2" <?php if ($row["difficulty"] == "2") {
echo "selected";
} ?> >2
</option>
<option value="3" <?php if ($row["difficulty"] == "3") {
echo "selected";
} ?> >3
</option>
<option value="4" <?php if ($row["difficulty"] == "4") {
echo "selected";
} ?> >4
</option>
<option value="5" <?php if ($row["difficulty"] == "5") {
echo "selected";
} ?> >5
</option>
</select>
</label>
<br><br><br><!--- Button --->
<!-- <button class="buttonSubmit" >Submit</button>-->
<input type="submit" name="submit" value="Submit">
<button class="buttonNext">Next Question</button>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
// Changed to a single if-statement
if (isset($_POST['choice'], $_POST['choose'])) {
$user_id = $_SESSION['user_id'];
$choice_answer = $_POST['choice'];
$difficulty = $_POST['choose'];
// Again, using prepared statements.
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES (?, ?, ?, ?)";
$pdo
->prepare($query)
->execute([$id, $user_id, $difficulty, $choice_answer]);
// Redirect to self with incremented question ID.
// https://stackoverflow.com/a/8131377/296555
header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $id++);
die;
}
}
Maybe this can help you:
var i=$_GET['id']){;
function getNext()
{
var = var + 1; //increase var by one
return var;
}</script>
<button class="buttonNext" onclick="getNext" >Next Question</button>
Uhm, I don't know where to start here...
Ok, for first your code is horrible - regarding in style, security and everything - sorry ;)
But to help with your problem:
Don't access the next id directly but go by
SELECT * FROM exercises WHERE exercise_id > $currentId ORDER BY exercise_id ASC LIMIT 0,2
This will help if you want to delete an exercise at some point, so have a gap like 1,2,4 (3 was deleted). You can also create a position field to sort the order of the question manually, but I guess that's too advanced for first.
However:
On start you check if there's a $_GET['id'] param and set this to $currentId. Best by $currentId = (int)$_GET['id'] to prevent a serious injection. If no GET param is there, set $currentId = 0 (first call then).
Then you run the query to get your exercise - it will be in the first row of the result.
On HTML side you just assign the exercise_id from the database result to the link which leads on the next exercise (so no JavaScript is required).
To test, if there's a next question at all check if a second row exists in the result (that's why LIMIT 0,2 instead of 0,1) to decide if to show the "next exercise button".
I am trying to get the value of the selected option from my select. And I am trying to see it's output through a javascript echo. Here's what I've got so far. I am not getting the value
<form method="post" action="">
<select class="form-control" name="empSel" id="empSel">
<?php
$sql2 = "SELECT * FROM employee";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row2 = mysql_fetch_assoc($result)) {
?>
<option value="<?php echo $row2['lastname'] ?>"><?=
/*$row2['user_surname']." ".*/
$row2['id']."-".$row2['lastname'] ?></option>
<?php
}
?>
</select>
<Label> Confirm</Label>
<div class="form-group col-md-6">
<input type="submit" class="btn btn-block btn-info"
name="submit"/>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$userid = $_POST['empSel'];
echo '<script type="text/javascript"> alert('.$userid.')</script>';
$userid = preg_replace('/\D/', '', $userid);
$sql2 = "SELECT * FROM employee where id ='userid'";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row = mysql_fetch_assoc($result)) {
echo '<script type="text/javascript"> alert("")</script>';
}
}
?>
An javascript alert doesn't pop out on this code. However, when I switch the value in the echo to a different variable an alert pops up. What does it mean? Do I properly get the value of my select and the page refreshed instantly that I didn't get to see it? Thanks
Edit:
An example of the option value would be 1-Lastname
And here's what I've tried.
<?php
if (isset($_POST['empSel'])){
$userid = $_POST['empSel'];
$userid = intval($userid);
echo '<script type="text/javascript"> alert('.$userid.')</script>';
}
?>
Now the javascript alert shows, but it echo 0. I think I am still not getting the value of my selected option
<option value="<?php echo $row2['id'] ?>">
This fixed it. In my previous code the option value was the surname...
I am trying to add items in my cart through Ajax call. I tried it doing simple just with php and it works fine. But now i am trying to convert my code for php+ajax. I have an index.php page in which i am dynamically changing my content. When i click on some nav list. It redirects me to page like this: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1 where page is passed through $_GET command every time a new page is called. I have a cart button on index.php header section.I want to refresh the div whose id is named as "cart". I am failing to do this through AJAX.Here i am pasting my code. Any suggestions or help will be appreciated.
cart div
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png">
Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
}
else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
</div>
item.php
<div>
<?php
$query=mysqli_query($con,"select * from products where cat_id='$cat_id' and s_cat_id='$s_cat_id' ORDER BY product_name ASC");
if(mysqli_num_rows($query)!=0){
while($row=mysqli_fetch_assoc($query)){
?>
<div>
<input type="hidden" id="pid" value="<?php echo $row['productid'] ?>">
<h4><?php echo $row['product_name']; ?></h4>
<h4>Price<?php echo "$" . $row['product_price']; ?> </h4>
<form method="post" action="">
<input type="hidden" id="page" name="page" value="items">
<input type="hidden" id="action" name="action" value="add">
<input type="hidden" id="id" name="id" value="<?php echo $row['productid']; ?>">
<input type="hidden" id="name" name="name" value="<?php echo $row['product_name']; ?>">
<input type="hidden" id="cat_id" name="cat_id" value="<?php echo $row['cat_id']; ?>">
<input type="hidden" id="s_cat_id" name="s_cat_id" value="<?php echo $row['s_cat_id']; ?>">
<input type="hidden" id="category" name="category" value="<?php echo $cat ?>">
<td>Colors:
<select name="color" id="color">
<option selected value="choose">choose</option>
<option value="blue" id="blue">Red</option>
<option value="blue" id="blue">Blue</option>
<option value="yellow" id="yellow">Yellow</option>
<option value="green" id="green">Green</option>
</select></td>
<td>Size : <select name="size" id="size"><option selected value="Choose size">Choose</option>
<option value="XL" id="XL">XL</option>
<option value="L" id="L">L</option></select>
</td>
</div>
<input type="submit" class="add-to-cart" id="addtocart" value="Add to Cart">
</form>
</div>
</div>
add_cart.php
<?php
include ("db/db.php");
session_start();
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(isset($_POST['Action']) && $_POST['Action']=="add" && isset($_POST['S_cat_id']) && isset($_POST['Cat_id']) ){
$id=intval($_POST['Id']);
$size = $_POST['Size'];
$color = $_POST['Color'];
$sql="SELECT * FROM products WHERE productid={$id}";
$data = mysqli_query($con,$sql);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$index = $id." ".$color. " ".$size;
if( isset($_SESSION['cart'][$index]) && isset($_SESSION['cart'][$index]['color']) && $_SESSION['cart'][$index]['color'] == $color && isset($_SESSION['cart'][$index]['size']) && $_SESSION['cart'][$index]['size'] == $size){
$_SESSION['cart'][$index]['quantity']++;
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}else{
$_SESSION['cart'][$index] = array('quantity' => 1,'id'=> $id, 'price' => $row['product_price'], 'size' => $size, 'color' => $color, 'name' => $row['product_name']);
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}
}
else{
$message="Product ID is invalid";
$output = json_encode(array('type'=>'error', 'text' => $message));
die($output);
}
}
}
?>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e){
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name= $("#name").val(),
cat_id= $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
id=$("#id").val(),
color=$("#color").val(),
size=$("#size").val(),
category = $("#category").val();
var proceed = true;
if(proceed){
post_data= { 'Page': page, 'Action': action,'Name': name, 'Cat_id': cat_id,'S_cat_id':s_cat_id, 'Category': category,'Id':id,'Color':color,'Size':size};
$.post('add_cart.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
//output=$('.alert-error').html(response.text);
}else{
output= $("#cart").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
So, I'm assuming that your PHP code works and that the data is sent properly. I'm also assuming that your $.ajax call works. If one of these isn't true let me know.
You should be able to simply use jQuery to update the data of the div.
$("some div").html = response.text;
Or if you want to process the data before hand.
$("some div").html = process(response.text);
I am also assuming both the php and ajax codes work well...
All you need do is store the current value state of the div by saying something like
div=document.getElementById('elem_id');
oldv = div.firstChild.nodeValue;
and then appending the new result as
newv = oldv + responseMessage;
and finally saying
div.innerHTML=newv;
I believe this should work perfectly for your refresh request situation. You could adopt and adapt this idea in various conditions.
Note: I am also assuming that both the old and new values are either text/HTML contents not requiring any mathematical calculations
I have the following select field, values are populating from mysql table. The dropdown contains around 8-10 values.
<select id ="name" name="name" class="form" required>
<option value="" disabled selected>Name</option>
<?php
$sql = "select name from accounts where id = '{$_SESSION['SESS_MEMBER_ID']}'";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $sql) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
if (mysqli_num_rows($result) > 0)
while ($row = mysqli_fetch_array($result)) {
$name = ($row['name']);
echo '<option value=".$name.">' . $name . '</option>';
}
?>
</select>
How can I pass the selected value from the above dropdown list to the below sql query(to where condition)? And also I need to populate the output of the below query to the below two input fields. Both the above select field and below input fields are in same page.
<?php
$sql = "select income,expense from accounts where name = '' and id = '{$_SESSION['SESS_MEMBER_ID']}'";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $sql) or die(((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
if (mysqli_num_rows($result) > 0)
while ($row = mysqli_fetch_array($result)) {
$inc = $row['income'];
$exp = $row['expense'];
?>
<div class="col-md-3">
<input value="<?php echo $inc ?>" class="form" readonly/>
</div>
<div class="col-md-3 ">
<input value="<?php echo $exp ?>" class="form" readonly/>
</div>
Thanks in advance for suggessions and advice.
Using Jquery you can do an on change function:
$('#name').change(function (e) {
var parameter = $(this).val();
Pass Parameter to your query and return values
$('#input1ID').val($row['income']);
$('#input2ID').val($row['expense']);
})
Sorry I don't know PHP or how to start the function, but this will pass a value to the query everytime you change the dropdown. This will not refresh the page.
I have products in table I wish to display some when page load and remain data should display on button click, I have set limit as 6 per page, when page loading it is displaying first six rows and if I click on Load More button it is displaying another six rows here problem coming after got 12 rows from table when I click again on Load More button it is not working even I have more data in table, I have cross checked parameters also, it is fine parameters also sending with request. please help me how to solve this.
NOTE: when I test this script in core php it is working fine, when I implement this script in codeigniter first time click load more data working second time when i click it is not wokring.
Javascript Code Block
$('.more').click(function(){
var ID = $(this).attr("id");
var cats = $('input[name=cats]').val();
$("#more"+ID).html('<img src="<?=ROOT;?>resources/moreajax.gif" />');
$.post('<?=ROOT;?>product/dataLoad', {id:ID,cats:cats}, function(data){
if(data)
{
$('ol#updates').append(data);
$("#more"+ID).remove();
}
else
{
$(".morebox").html('The End');// no results
}
});
return false;
});
codeigniter controller function
public function dataLoad() {
if(isset($_POST['id']))
{
$lastmsg=$_POST['id'];
$cats = $_POST['cats'];
$query=mysql_query("select * from product where id > '".$lastmsg."' AND category_id IN ($cats) order by id asc limit 4");
$numrows = mysql_num_rows($query);
while($ob = mysql_fetch_array($query))
{
?>
<div>
<p>ID: <?=$ob['id']; </p>
<p>NAME: <?=$ob['name']; </p>
</div>
<?php
}//while
?>
<?php
if($numrows > 0)
{
?>
<div id="more<?php echo $ob['id']; ?>" class="morebox" style="clear:both">
<input type="hidden" name="cats" value="<?=$cats;?>" />
Load More
</div>
<?php
}
}
?>
product page code
<ol class="timeline" id="updates">
$str = implode(",",$cats);
$query = "select * FROM product WHERE category_id IN (".$str.") order by id asc limit 4";
$result=mysql_query($query);
$numrows = mysql_num_rows($result);
while($ob = mysql_fetch_array($result))
{
?>
<div>
<p>ID: <?=$ob['id']; </p>
<p>NAME: <?=$ob['name']; </p>
</div>
<?php
}//while
?>
</ol>
<?php
if($numrows > 0)
{
?>
<div id="more<?php echo $ob['id']; ?>" class="morebox" style="clear:both">
<input type="hidden" name="cats" value="<?=$cats;?>" />
Load More
</div>
<?php
}
?>
I solved this problem insted of this
$('.more').click(function(){
$("#updates").on("click",".more",function(){