Update page without page reload - javascript

I have this php code with a sql query and I want the page(more like a part of the page) to update without page reload. I also have a button that when I click it updates the variable(?date=) on the link. What I want now is to also execute this block of code without page reload.
Here are pictures what I want to achieve:
[So when I click the date, it updates the ?date variable on the link][1]
[and I want this to also update based on the sql query I have without reloading the page][2]
<?php
if (isset($_GET["date"])) {
foreach ($db->query("SELECT DayName, StartTime, EndTime FROM event_availability
INNER JOIN days ON days.DayID = event_availability.DayID
WHERE EventID = ? AND DayName = ?", $_GET["eventid"], date('l', strtotime($_GET["date"]))) as $availtime) {
?>
<?php
$i = 1;
$start = date('h:i A', strtotime($availtime["StartTime"]));
$end = $availtime["EndTime"];
while (strtotime($start) <= strtotime($end)) {
?>
<input type="radio" class="btn-check shadow-none" name="timeradio" id="btnradio<?php echo $i ?>" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio<?php echo $i ?>"><?php echo $start ?></label>
<?php
$start = date("h:i A", strtotime("$start + 30 mins"));
$i++;
}
?>
<?php
}
}
?>
[1]: https://i.stack.imgur.com/lHxCq.png
[2]: https://i.stack.imgur.com/aQP5k.png

Related

How do i add a button that on clicking will take me to the product page with more product description along with comments and rating

I'm trying to do a project for uni and am stuck at this one particular part.
I'm trying to display a button that would open a specific product and let users order/add to cart/rate it
I've almost very little knowledge of java script and started PHP about 2months back.
Here is my code.
$sql="select * from products";
$rs=$db->query($sql);
echo "<form method='post' action=viewitem.php>";
echo "<table>";
foreach ($rs as $row) {
$id=$row[0];
echo "<tr><td><img src = '/3331/333/bootstrap-shop/pimages/MensShirts/$row[6]' width='250' height='250'></td>
<td><pre>$row[5]</pre></td></tr>";
echo "<tr><td>$row[3] - <strong>BD$row[4]</strong></td></tr>";
echo "<td><input type='submit' name='$id' value='View more'/></td></tr>";
}
echo "</table>";
echo "</form>";
The form I'm submitting to is
$pid=$id;
$sql="select * from products where pid='$pid'";
$rs=$db->query($sql);
echo "<form method='post' action=addtocart.php>";
echo "<table>";
foreach ($rs as $row) {
$id=$row[0];
echo "<tr><td><img src = '/3331/333/bootstrap-shop/pimages/MensShirts/$row[6]' width='250' height='250'></td></tr>";
echo "<tr><td>$row[3] - <strong>BD$row[4]</strong></td></tr>";
}
echo "</table>";
echo "</form>";
I'm supposed to add more items there but I cant seem to find out what product the user has exactly clicked on. it keeps saying $pid/$id are undefined.
So instead of submitting a form to view a product, simply create a link and pass the product id as a parameter.
For example, on your listings page you would have...
<?php $query = $db->query( "SELECT * FROM products" ); ?>
<table>
<?php foreach ( $query as $row ): ?>
<tr><td><img src="/3331/333/bootstrap-shop/pimages/MensShirts/<?php echo $row[ 6 ]; ?>" width="250" height="250"></td>
<td><pre><?php echo $row[ 5 ]; ?></pre></td></tr>
<tr><td><?php echo $row[ 3 ]; ?> - <strong>BD<?php echo $row[ 4 ]; ?></strong></td></tr>
<td>View more</tr>
<?php endforeach ?>
</table>
Specifically View more
When clicked this will take the user to a URL something like: http://example.com/viewitem.php?id=123
And then in the viewitem.php file we grab the id parameter from the URL and perform the query. For example:
<?php
$pid = !empty( $_GET[ 'id' ] ) ? (int)$_GET[ 'id' ] : null;
if ( $pid ) {
$query = $db->query( "SELECT * FROM products WHERE pid = {$pid}" );
?>
<form method="post" action="addtocart.php">
<table>
<?php foreach ( $query as $row ): ?>
<tr><td><img src="/3331/333/bootstrap-shop/pimages/MensShirts/<?php echo $row[ 6 ]; ?>" width="250" height="250"></td>
<tr><td><?php echo $row[ 3 ]; ?> - <strong>BD<?php echo $row[ 4 ]; ?></strong></td></tr>
<?php endforeach ?>
</table>
</form>
<?php
} else {
echo 'No product ID';
}
URL parameters are accessible via the $_GET array but because we will be using the value of this parameter in the SQL query we have to sanitise the data as you'll be susceptible to SQL injection attacks.
The below line is basically checking if the id parameter exists in the url, if it does make sure it's a valid integer.
$pid = !empty( $_GET[ 'id' ] ) ? (int)$_GET[ 'id' ] : null;
This is the same as...
$pid = null;
if ( !empty( $_GET[ 'id' ] ) ) {
$pid = (int)$_GET[ 'id' ];
}
Now for a quick example of what can happen if you don't sanitise the input data...
If you passed the $_GET[ 'id' ] value directly into the sql query, for example:
$db->query( "SELECT * FROM products WHERE pid = " . $_GET[ 'id' ] );
An attacker could then start running their own SQL queries on your database, so if they visited http://example.com/viewitem.php?id=1; SELECT * FROM users; the following query would be run...
SELECT * FROM products WHERE pid = 1; SELECT * FROM users;
This is a very basic example of SQL injection, I would highly recommend researching it in more depth.

How Do I Edit a Single Row?

So I am currently working on a forum, and I want to be able to have users edit their own questions and replies. Currently I am able to edit questions (sort of *other error is below) just fine. But replies are my biggest problem right now. Currently it shows an edit button under a reply but then it will allow me to edit ALL the other replies on the page and then when I save it, it saves the very last row.
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', '<p id="reply'.$rows['a_id'].'">'.$text.'</p>');
} else {
?>
<p id="reply<?php echo $rows['a_id']; ?>"><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
if($_SESSION['username'] == $rows['a_username']) {
$editReply = true;
?>
<div id="questionId"><?php echo $rows['question_id'];?></div>
<div id="replyId"><?php echo $rows['a_id'];?></div>
<button id="editReply">Edit</button>
<button id="saveReply">Save</button>
<button id="cancelReply">Cancel</button>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#saveReply').hide();
$('#cancelReply').hide();
});
</script>
<?php
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#editReply').click(function() {
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','true');
$('#reply<?php echo $rows['a_id']; ?>').css('background','white');
$('#reply<?php echo $rows['a_id']; ?>').css('border','solid 1px');
$('#saveReply').show();
$('#cancelReply').show();
$('#editReply').hide();
});
$('#saveReply').click(function() {
// Get edit field value
$detail = $('#reply<?php echo $rows['a_id']; ?>').html();
$q_id = $('#questionId').html();
$a_id = $('#replyId').html();
$.ajax({
url: 'editReply.php',
type: 'post',
data: {detail: $detail, q_id: $q_id, a_id: $a_id},
datatype: 'html',
});
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
$('#cancelReply').click(function() {
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
});
</script>
<?php
}
?>
editreply.php:
<?php
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = ""; // Mysql password
$db_name = "db"; // Database name
$tbl_name = "fanswer"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$detail = htmlspecialchars($_POST['detail']);
$q_id = $_POST['q_id'];
$a_id = $_POST['a_id'];
// Add your validation and save data to database
echo $detail;
echo $q_id;
echo $a_id;
$sql = "UPDATE $tbl_name SET a_answer = '$detail' WHERE question_id='$q_id' AND a_id= '$a_id'";
$result = mysqli_query($conn, $sql);
?>
Originally I had all the editable content in divs but for some reason it made some pages load funny so for now I was hoping to use the p tag.
How can I make it so only one of the replies are editable and so it only sends that information to the editreply.php script?
*My other problem which is sort of a side problem, when I go to edit something that has a link in it I get a load of gibberish posted into my database. E.g. a user post LMAO: https://afunnypic.com, the information in my database says:
LMAO: <a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="https://afunnypic.com" rel="nofollow">https://afunnypic.com</a><br>
Which I don't understand.
Just found my answer to the first problem, all I did was move the script inside the if ($editReply = true) statement and it worked!
If anyone can help with the second bit on editing the links bit that would be great!

Continue counting after page 1

I have this simple counter php code and use it in Wordpress. Here is the code:
$counter = 0;
while ($query->have_posts())
{query->the_post();$counter++;
Which works fine. But when I go to page 2, then the counter resets and starts back at 1. Is there a way that it continues counting on page 2, page 3 and so on?
the url in the browser address is: /?sf_paged=2 for page 2 and /?sf_paged=3 for page 3 etc...
Is there some if code I can do, like:
if $url = /?sf_paged=2 {
$counter2++; }
else if $url = /?sf_paged=3 {
$counter3++; }
something like that?
Init your counter like this
$counter = $_GET['sf_paged'] ? intval($_GET['sf_paged']) * $posts_per_page : 0;
Then $counter++ will be what you want.
If you want to get the number of all the posts in the query, use:
$query->found_posts
If you want to see how many posts are there from page 1 to n (where 'n' is the current page) I suggest use a simple multiplication:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$postnum = $paged*$query->posts_per_page;
Or you could try to store it in a $_GET parameter, a cookie or a sessionStorage / localStorage. :)
try this one should works fine
<?php
$i = 0; //counter
$post_in_page = 4; //number of posts in loop
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; //pagi
$guide = "post_type=post&posts_per_page=$post_in_page"; //loop option
?>
<?php query_posts($guide.'&paged=' . $paged); while(have_posts()) : the_post(); ?>
<?php
$i++; //here counter
if(get_query_var('paged') != 1){ // here if current page not first page
echo get_query_var('paged')*$post_in_page+$i-$post_in_page; // that's it :D
}else{
echo $i;
}
?>
<li>
<?php echo get_the_title(); ?>
<br />
</li><!--End Loop-->
<?php endwhile; ?>
<ul class="pagnum">
<li><?php next_posts_link();?></li>
<li><?php previous_posts_link(); ?></li>
</ul><!--End pagnum-->
<?php wp_reset_query();?>

php code to get count from multiselect listbox and store in database

Below is my textbox values....i am unable to put my screen shots here..
i used multiple input tag jquery from this site..
http://loopj.com/jquery-tokeninput/demo.html
and second option of this demo. plz visit demo link ...
but i used multiple input textbox..in which we select multiple tags in one textbox okay.
like 700X 701X 702X
I need to get this textbox value and store in 3 rows..
FOR EX - in above screenshot there are 3 values 700,701,702 ok...now i need to ask you...when i click save i need to store this values in 3 different rows...
Rows No - used_receipt
1 700
2 701
3 702
i try like below but wont work...
textbox code
<input id="demo-input-local" type="text" value="<?php echo $data['used_receipt'];?>" name="used_receipt" />
javascript
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([
<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2 where SM.receipt_no not in (select used_receipt from book_return)");
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
php code to insert multiple values in database
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", $used_receipt);
$max = count($arr);
for ($i = 0; $i < $max; $i++)
{
$insertrow = $database->insertRow("INSERT INTO book_return (book,surveyor,used_receipt,city,return_date,created)
VALUES (:book,:surveyor,:used_receipt,:city,:return_date,:created)",
array(':used_receipt'=>$arr[$i]);
}
Instead of
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
Try this
$r = array();$i=1;
foreach($receipt as $row){
$r[]['name'] = $row['receipt_no'];$r[]['id'] = $i++;
}
echo "JSON.parse(\"".json_encode($t)."\")";
below is script which i used
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2");
foreach($receipt as $row){ ?>
{id:<?php echo $row['receipt_no']; ?>,name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
and get this input in like
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", rtrim($used_receipt));

Get all data from mysql display in div php javascript

Hello my problem is simple , i have a table news , i have a button bt1 , and a div to show the results , i want to display all rows from table when i click the button,i only get the first row , how can i display all results ?
<script>
function shownews(id) { <? php
include('db.php');
$query = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($query)) {
$a = $row['news_title'];
} ?>
var ab = <? php echo json_encode($a); ?> ;
id.innerHTML = ab;
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
try
$a = array();
while ($row = mysql_fetch_array($query)) {
$a[] = $row['news_title'];
} ?>
// print array
print_r($a);
Your echo json_encode($a); is not in your while loop, so you only render 1 line.
Also if i understand what you're doing, you want your PHP to be executed only when you trigger your button click ? This is not the way to do it... php is a server language where javascript is executed only by your browser.
I didn't
Try this :
<script type="text/javascript">
function shownews(id) {
document.getElementById(id).innerHTML = document.getElementById('news').innerHTML ;
}
</script>
<div id="news" style="display:none ;">
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
echo $row['news_title'] . '<br />' ;
}
?>
</div>
<div id="results"></div>
<button id="btn1" onclick="shownews('results')">See news</button>
You are overwriting $a, hence you will only get the last row.
Change
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
}
to
$a = array();
while($row=mysql_fetch_array($query)){
array_push($a, $row['news_title']);
}
Edit: Royal_bg is correct - extra info:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. http://us2.php.net/array_push
You execute all the while before writing anything. Try to change the closing bracket after writing the answer...
<script>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
?>
var ab = <?php echo $a; ?>;
id.innerHTML += ab;
<?php
}
?>
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a[]=$row['news_title'];
}
?>
id.innerHTML=<?php echo json_encode($a); ?>;
}

Categories