How would I show this checkbox on realtime? - javascript

I'm currently studying html and php and I made this little project about a "notification system". I guess I first have to explain this before I go in detail on my real problem.
My table looks like this:
My first php command would get the values of each feature column and store them into $a, $b, $c, $d and $e.
My second php command would echo 5 textboxes and mark them as checked based on the value of $a,$b,$c,$d and $e so the output based on my table would show five checkboxes with the 1st, 2nd and 4th checkbox with a check.
My third php command would gather the values from the checkboxes because the user might want to change his preferred notifications. After clicking submit the code would update the new values of the textboxes.
Below is the code on my current progress:
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('main_database') or die(mysql_error());
$fetchchoice=mysql_query("SELECT * FROM notification_table WHERE username='carl'");
while($getchoice=mysql_fetch_assoc($fetchchoice)){
$a=$getchoice['feature1'];;
$b=$getchoice['feature2'];
$c=$getchoice['feature3'];
$d=$getchoice['feature4'];
$e=$getchoice['feature5'];
}
?>
<html>
<head>
</head>
<body>
<form method="POST">
<?php
echo
'
<input type="hidden" name="choice1" value="">
<input type="checkbox" name="choice1" value="checked" '.$a.' > Feature 1 <br>
<input type="hidden" name="choice2" value="">
<input type="checkbox" name="choice2" value="checked" '.$b.' > Feature 2 <br>
<input type="hidden" name="choice3" value="">
<input type="checkbox" name="choice3" value="checked" '.$c.' > Feature 3 <br>
<input type="hidden" name="choice4" value="">
<input type="checkbox" name="choice4" value="checked" '.$d.' > Feature 4 <br>
<input type="hidden" name="choice5" value="">
<input type="checkbox" name="choice5" value="checked" '.$e.' > Feature 5 <br>
';
?>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
$f1choice = $_POST['choice1'];
$f2choice = $_POST['choice2'];
$f3choice = $_POST['choice3'];
$f4choice = $_POST['choice4'];
$f5choice = $_POST['choice5'];
echo "1.";
echo $f1choice;
echo "<br />";
echo "2.";
echo $f2choice;
echo "<br />";
echo "3.";
echo $f3choice;
echo "<br />";
echo "4.";
echo $f4choice;
echo "<br />";
echo "5.";
echo $f5choice;
$kweri = "UPDATE `main_database`.`notification_table` SET `feature1` = '".$f1choice."', `feature2` = '".$f2choice."', `feature3` = '".$f3choice."', `feature4` = '".$f4choice."', `feature5` = '".$f5choice."' WHERE `notification_table`.`username` = 'carl'";
mysql_query($kweri);
}
?>
</body>
</html>
PROBLEM
My problem now is that I have to refresh the page to have the updated checkbox to appear since this was only done on php, I have no experience in javascript at all but I think it's the best way to show my current textbox on realtime, however, I have no idea where to start or if there is another way I could go about showing my checkbox on realtime.
EXTRA PROBLEM (This has something to do with my system but not regarding this code. If you guys could take a look at this problem it would mean a lot.)
As you guys have seen, the table above was just to keep track of what a user's preference regarding notifications would be. But the system doesn't stop there, I need to figure out how to pass notifications after a feature has been used. What my idea was is that I should add an extra sql command after every feature to put what has happened on a different table. Example would be registration, after the insert command for the registration details to be saved, I would also insert that, user "example" has "registered" on "date" in a separate table, namely "notif_table". My columns would be, username, action and date so my notifications page can show that "User" has "Registered" on "January 18, 2015".
But then again, that was just my theory on notifications and I'm very open to suggestions and corrections.

Just put the part with if(isset($_POST['submit'])) prior to your select statement.
EXTRA PROBLEM:
Just add a column to your existing table (e.g. 'created') and put now() into it when inserting the row.

Related

How to limit the quantity of selected checkboxes and pass values to a different page using PHP/HTML

Sorry for my noobness here I'm trying to create a project with no PHP knowledge at all.
I have a database set up with a list of users and I am able to display users based on specific information through a search. Each search query has a checkbox. What I am trying to do now is limit the amount of selected checkboxes (up to 3 selections only) and save the selected queries to a different page. Can someone point me in the right direction? I'm sure my code is all over the place and probably wrong in many ways so I apologise in advance. I appreciate it.
Search Results Page:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/overallheader.php';
?>
<h1>New Staff Request</h1>
<p>Search for potential staff using the form below</p>
<form method="POST">
<input type="TEXT" name="search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>
<br/>
<p><b> Select only up to 3 results</b></p>
<form method="post" action="StaffingRequest.php">
<?php
if(isset($_POST['submit'])){
$mysqli = NEW mysqli('localhost','root','','lr');
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM users WHERE jobcat LIKE '%$search%' ");
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$education = $rows['education'];
$salary = $rows['salary'];
$jobcat = $rows['jobcat'];
echo "<br /><input type='checkbox' name='query[]' value=''> First Name: $first_name<br />Last Name: $last_name<br />Job Category: $jobcat<br />Education: $education<br />Salary: $salary<br /><br />";
}
} else {
echo "No Results";
}
}
?>
<input type="submit" name="submit" Value="Save">
</form>
<?php include 'includes/overall/overallfooter.php'; ?>
Here is the page I want the results to display on:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/overallheader.php';
?>
<h1>My Staff Requests:</h1>
<p></p>
<?php
$chkbox = $_POST['query'];
$i = 0;
While($i < sizeof($chkbox)) {
echo "CheckBox Selected Values = " . $chkbox[$i] . '</br>';
$i++;
}
?>
<?php include 'includes/overall/overallfooter.php'; ?>
You are going to want to use JS/jQuery to accomplish this.
What you are going to do is add some client side functionality that checks how many check boxes of the same class have a check in them.
I added the code for you. This is what it does.
Add the jQuery library.
Add a classname (class="checkboxes") to the input tag to be referenced later.
Detect when there has been a change to an element with the class name "checkboxes".
Count to see how many elements with the class name "checkboxes" have a checked checkbox.
If there are three checked check boxes, remove the check from the last(4th) selected check box.
Display an error to the user that only three check boxes can be selected.
Like so:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/overallheader.php';
?>
<h1>New Staff Request</h1>
<p>Search for potential staff using the form below</p>
<form method="POST" action="">
<input type="TEXT" name="search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>
<br/>
<p><b> Select only up to 3 results</b></p>
<form method="POST" action="StaffingRequest.php">
<?php
if(isset($_POST['submit'])){
$mysqli = NEW mysqli('localhost','root','','lr');
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM users WHERE jobcat LIKE '%$search%' ");
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$education = $rows['education'];
$salary = $rows['salary'];
$jobcat = $rows['jobcat'];
echo '<br /><input type="checkbox" name="query[]" class="checkboxes" value=""> First Name: ' . $first_name . '<br />Last Name: ' . $last_name . '<br />Job Category: ' . $jobcat . '<br />Education: ' . $education . '<br />Salary: ' . $salary . '<br /><br />';
}
} else {
echo "No Results";
}
}
?>
<input type="submit" name="submit" Value="Save">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".checkboxes").change(function (){
if($('.checkboxes:checkbox:checked').length > 3){
$(this).prop('checked', false);
alert("You can only select 3 checkboxes.");
}
});
});
</script>
<?php include 'includes/overall/overallfooter.php'; ?>
A couple other things.
I try real hard not to have more than one form on a page. For the most part you should only need one. I would say that if you have two forms it's a special case. Your first form that you use for the search could easily be replaced with an AJAX routine.
When echoing HTML though PHP, I recommend using single quotes. This will prevent alot of problems dealing with the quotes for the elements attributes. Here is an example of how I do it:
echo '<input id="myId">Test</input>';
This will save you some headaches down the road.
Hope this works for you..

Javascript button click change / create PHP variable on same page

I have searched stackoverflow for the past hour and have found similar questions but attempting the solution has given me only errors - it may be as I am trying to load it on the same page.
I have tried saving the value to a cookie in JS then loading it in php, also attempted through ajax, etc.
From what I've read it can't just be done within as PHP is server side and Javascript is browser side which I get.
I currently have a .html page with a form that sends values through POST:
form.html
<form id="calc" form name="calculator" method="post" action="/calculate.php">
The solution is not with the form, I can't have hidden fields as I need to user input. I could have a radio box in the form yes and then get the value that way, but that's not my question. My question is how I can get the user's input and turn it into php on the page the form redirects to calculate.php:
calculate.php
<?php
if(isset($_POST['submit'])){
$x= $_POST['value'];
echo "your something:";
echo $x;
?>
Click button below for option one to do this, or click two for that, or three for something else...
<button id="one"> one </button>
<script>
$(document).ready(
function() {
$("#one").click(function() {
make php value 1
});
</script>
use php value from click
So the user will already have clicked submit. Then be redirected onto the .php page with their inputs, they can then choose button 1, 2 or 3 for example through javascript on calculate.php NOT the form.
My problem is I need to know on the same page - calculate.php, which button has been clicked in php. So that I can use their input and do different things with it depending on which button.
Is it possible to get a value to be set or create one from a button click on calculate.php itself with the javascript button producing a php value on the same page? Does it need to be loaded from an external.php page through ajax? Is there any other way?
PHP Option:
<?php
if(isset($_POST['submit'])){
$x= (isset($_POST['one'])) ? $_POST['one'] : '';
$y = (isset($_POST['two'])) ? $_POST['two'] : '';
$z = (isset($_POST['three'])) ? $_POST['three'] : '';
echo "your something:";
echo $x;
echo $y;
echo $z;
?>
<form name="calculator" method="post">
<INPUT TYPE="RADIO" NAME="one" VALUE="1"> ONE
<INPUT TYPE="RADIO" NAME="two" VALUE="2"> TWO
<INPUT TYPE="RADIO" NAME="three" VALUE="3"> THREE
<input type="submit" value="Submit">
</form>
JS mode:
if(isset($_POST)){
$value= (isset($_POST['value'])) ? $_POST['value'] : '';
$previous = (isset($_POST['previous'])) ? $_POST['previous'] : '';
//play with value and previous one
$x = //your algorithm;
echo "your something:";
echo $x;
?>
<form name="calculator" method="post">
<button type="button" value='1'>ONE</button>
<button type="button" value='2'>TWO</button>
<button type="button" value='3'>THREE</button>
<input name='value' type='hidden' value=''>
<input name='previous' type='hidden' value='<?= (isset($x)) ? $x : ''?>'>
</form>
<script>
$(document).ready(
function() {
$("button").click(function() {
$('input[name=value]').val($(this).val());
$('form').submit();
});
</script>
use php value from click

I want to use onclick function to get data from HTML Form inside php loop to use it in Ajax

I'm developing discussion board and I want to make a reply system on each comment using jquery.
I created certain div inside a loop with different values in each iteration.
Now I'm working on submitting the reply form and I have a problem. It works only on the first comment. When I reply to the first comment only It works but when replying to any other comment It doesn't work and give me my error message the textbox is empty Then I realized that it reads data from the first form only through the loop.
Here is the code.
<div class="comment_form">
<textarea class="span10" id="replyC" name="replyC" placeholder="Reply comment" rows="6">
</textarea><br>
<input id="commentId" name="commentId" type="hidden" value="<?php echo $CommentID;?>">
<input id="userId" name="userId" type="hidden" value="<?php echo $uId;?>">
<input id="articleId" name="articleId" type="hidden" value="<?php echo $ArticleID; ?>">
<input class="btn btn-lg btn-default replyForm" id="<?php echo $CommentID; ?>" name="replyForm" type="submit" value="Reply">
</div>
The button with class name "replyForm" I get it by
$(".replyForm").click(function()
and here is the javascript and Ajax code.
$(".replyForm").click(function(){
//$(this).parents().next('.replyForm').click(function(){
var user_reply = $("#replyC").val();
var userId = $("#userId").val();
var comment_id = $("#commentId").val();
var articleId = $("#articleId").val();
$.ajax({
url:'articleReply.php',
data:{replyC:user_reply,userId:userId,commentId:comment_id,articleId:articleId},
type:'POST',
success:function(data){
$("#resultReply").html(data);
$('#replyC').val('');
}
});
});
The problem Now .. It doesn't work on all comments retrieved from the loop but works only on the first comment while trying reply on other comments I get my empty message appears under the first comment.
So it get data from the first comment only not from the rest.
Any help ??
Here it works:
Here is the problem:

Merging 2 search forms into 1 input, plus checkboxes

On my site I have a main search (powered by Google, placed throughout the site) and I have now created a second search (on its own page, which searches my DB for images based on user input text) which is a totally separate search to the google one.
What I want to do -
I want both Search forms to share a single text input field, but allow the user to choose which search to use (Google or Images Only) via radiobutton.
So we'd have:
[search input field][go] (o)Use Google (o)Image Search only
I'm no coder but can hack enough to just about get by, it just takes me a day or two to figure out and get working.
What I need and would save me a great deal of time, as I'm stumped on how to proceed with this or if it is even possible! If someone could tell me A) If it's possible, and B) A few pointers if it is. For instance I'm guessing it will probably need a bit of JavaScript to make it possible?
Any pointers would be appreciated, then I can see what I can do.
All the best,
Chris
// My Stand-alone Image Search Page ////////////////////////////////
<form method="post" action="imagesearch?go" id="search-form">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
// code for above form //
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$sql="SELECT ID FROM ImageTable WHERE Name LIKE '%" . $name . "%' Order by Date Desc LIMIT 50";
//-run the query against the mysql query function
$result=mysql_query($sql);
// Create while loop and loop through result set//
$content .= ' <p><div id="wrapper">';
while($row=mysql_fetch_array($result)){
$id=$row['ID'];
$img = new Image($id);
// Format results//
$content .= '<div id="imgrt"><img src="/img/M/'.$img->ID.'.jpg" class="searchimg"><br>'.$img->Name.'';
$content .= '</div>';
}
$content .= '';$content .= '</div>';
}
else{
$content .= ' <p>Please enter a search query</p>';
}
}
}
// End of Stand-alone image search page /////////////////////////
---------------------------------------------------------------------------
// My sites main Google powered Search
<form action="http://www.example.com/gsresults" id="cse-search-box" class="searchmain">
<input type="hidden" name="cx" value="partner-pub-XXXXXXXXXXXXXXX" />
<input type="hidden" name="cof" value="FORID:XX" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="mainsearch">
<input type="submit" name="sa" value="Go" class="mainsearchbutton"/>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang="></script>
OK so here we go. If you plonk this in an empty html file you can see it in action (Tried to make a jsfiddle but didnt work for some reason). What this does is set an "active" id on the selected combo option, and when you click the submit button it grabs the value of the combo option with that id, and goes to the page of that value. so if you click google and then the button you go to google.html, and same goes for image, image.html. If you want some more specifics you can ask, but thats the main logic there.
<script>
function replaceActive(obj) {
var activeElm = document.getElementById("active");
activeElm.id = activeElm.id.replace("active", "");
obj.id = "active";
}
function formFunction(obj) {
obj.action = document.getElementById("active").value + ".html";
}
</script>
<form action="#" onsubmit="return formFunction(this);" method="post">
<input type="text" />
<select>
<option value="google" id="active" onclick="replaceActive(this);">Google</option>
<option value="image" onclick="replaceActive(this);">Images</option>
</select>
<input type="submit" />
</form>
Basically you can change that "formFunction()" function's code and and use "document.getElementById("active").value" to do what ever you wanted to do.

How to save the content from a wysisyg inline-editor to a .php file

I found a 'HTML5 WYSISYG Inline Editor', I have it working on my localhost(Ubuntu 14.04).
The purpose for this is, to embed it in my website, and use it as my main writing tool for my website. I need to be able to choose the filename or have it add - in the whitespace of the filename.
this is the code i wrote on it to save its content
(CodePen from original author: HTML5 WYSISYG Inline Editor)
inline.php
<form action="effe.php" method="post">
<input type="text" name="author" value="" placeholder="Author">
<input type="text" name="header" value="" placeholder="header">
<input type="datetime" name="datetime" value="" placeholder="datetime">
<div id='editor' contenteditable contextmenu="mymenu" name='editor'>
<p>This is just some example text to start us off</p>
</div>
<div class="tags">
<input type="text" name="" value="" placeholder="tag">
<input type="text" name="" value="" placeholder="tag">
<input type="text" name="" value="" placeholder="tag">
</div>
<input type="submit" value="Submit">
</form>
save.php
<?php
if (!empty($_POST))
{
foreach ( $_POST as $key => $value )
{
if ( ( !is_string($value) && !is_numeric($value) ) || !is_string($key) )
continue;
?>
<?php echo htmlspecialchars( (string)$key ); ?>
<div class="article-meta">
<a class="author" rel="author" title="author" href="/about" target="_blank"><?php echo "$author";?></a>
<time datetime="<?php echo "$datetime";?>" title="<?php echo "$datetime";?>"><?php echo "$datetime";?></time>
</div>
<h1><?php echo "$header"; ?></h1>
<?php echo "$editor"; ?>
<div class="tags">
<span> <?php echo "$tag1"; ?> </span>
<span> <?php echo "$tag2"; ?> </span>
<span> <?php echo "$tag3"; ?> </span>
</div>
<?php
}
}
?>
RESULT:
I have been at this for a good day, and am just not seeing what am doing wrong. Do note that my php knowledge is pretty basic.
I know using a db is an option, but at the top of my head, i only wrote like 20+ article in the past year or two. When i hit a 100 articles i will consider switching to a database.
I'm not 100% sure what it is you;re trying to accomplish. I was the author of the article you mentioned, and I'd be glad to help.
I'm not sure the method you;re trying to use is practical. The best option here would be to set up a database and write the content in there.
With php thats pretty easy, I would suggest taking a look at PDO, the database abstraction layer. There are some others, but this one does some work for you relating to injection attacks etc so it's a nice starting point.
It sounds like you need a fairly simple database table, most likely something like:
create table articles (
article_id INT NOT NULL AUTO INCREMENT,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
article_date DATE
PRIMARY KEY (tutorial_id)
);
When you POST data back from your editor form, you can do something like:
$dbh = new PDO('mysql:host=localhost;dbname=articles', 'user', 'pwd');
$sth = $dbh->prepare('INSERT INTO articles (title, content, article_date) values (:title, :content, NOW())');
$sth->bindParam(':title', $_POST['title']);
$sth->bindParam(':content', $_POST['content']);
$sth->execute();
To recall that back out of the database, use something like:
$dbh = new PDO('mysql:host=localhost;dbname=articles', 'user', 'pwd');
$sth = $dbh->query('SELECT * FROM articles');
There's a little more to it than this, for example you'll want to add a try/catch block to avoid errors, and you may want to select a specific article (i.e. SELECT * FROM articles where article_id=45) but this I hope will point you in the right direction.
I think trying to avoid using a database will cause a lot of extra work, and once you start using something like MySQL you'll be up and running in no time!

Categories

Resources