I'm creating some checkboxes via php like this:
$query = mysql_query("SELECT user FROM login");
while ($row = mysql_fetch_assoc($query)) {
$readUser = $row['user'];
if($readUser == "mod"){}
else {
$checkboxUserId = $readUser;
echo "<p><input class='filled-in item' type='checkbox' id='$checkboxUserId' checked='checked' /><label for='$checkboxUserId'>Team: $checkboxUserId</label></p>";
}
some code after this, I do:
I'm drawing some polygones via a Javascript function based on some values I stored in a database.
$query = mysql_query("SELECT * FROM questionAnswers");
while ($row = mysql_fetch_assoc($query)) {
$readUser = $row['user'];
$someMoreVars = $row['var']; //like ten more or that
if ($user == "mod"){
if ($readUser == "mod"){}
else{
echo "drawUserPoly($someMoreVars, $iDontWantToListThemAll, $thatsJustForTheContext)";
//Some More Code here
}
Now the problem: I need to check for the checkboxes which one is checked so i don't draw them and this needs to be updated live (like: checking the checkbox again and the polygon will be drawn, uncheck the checkbox and the polygon is not drawn).
my attempt:
else {
if(isset($_POST['$readUser'])){
echo "drawUserPoly($someMoreVars, $iDontWantToListThemAll, $thatsJustForTheContext)";
}
}
my second attempt:
else {
if($_POST['$readuser'] == 'checked'){
echo "drawUserPoly($someMoreVars, $iDontWantToListThemAll, $thatsJustForTheContext)";
}
}
Remember that all PHP code is executed before the page is sent to the browser, and that PHP cannot see whatever happens on the page after that. As a result, PHP and the HTML do not interact live.
Your solution is to use Javascript which does see what's happening in the HTML, and CSS styles. A simple approach would be to register an event listener on the checkbox checked event in JavaScript. When the box is unchecked, just hide the polygon by applying a CSS class that has display:none style. When checkbox is checked, remove that class and the polygon will reappear.
Related
I am currently working on a multi-user privat chat-system (pretty similar to the Facebook chat). There is a sidebar with all users and when I click on a user a chat window gets dynamically generated by JavaScript.
The chat window contains a .chat-container with all messages between the selcted user and the logged in user.
The .chat-container has to get updated like every 3 seconds with AJAX, but for some reason I am unable to make it work!
My current try is the following:
Every user-element in the sidebar has a hidden form .chat-ident-form inside it. The form has two inputs "to_user" and "from_user", which values get populated with PHP:
<div class="sidebar-name">
<form class="chat-ident-form" action="./src/assets/widgets/chat-widget/get-messages.php" method="post" onclick="submit_ident_form_via_ajax();">
<a href="javascript:register_popup('<?php echo $member['username'] ?>', '<?php echo $member['username'] ?>');">
<img class="img-circle chat-sidebar-user-avatar" src="<?php echo $member["avatar"]; ?>" />
<span><?php echo $member['username'] ?></span>
</a>
<input type="hidden" name="to_user" value="<?php echo $member['username'] ?>">
<input type="hidden" name="from_user" value="<?php echo $_SESSION['username'] ?>">
</form>
</div>
When the user clicks on a user-element in the sidebar a chat window opens up (which is working!) and then the trouble begins!
I then want to submit the hidden .chat-ident-form to a PHP-Script (at ./src/assets/widgets/chat-widget/get-messages.php) via AJAX. I currently trigger the AJAX with onclick, when the user clicks on the user-element in the sidebar.
The PHP-Script then gathers the massages between the users from the database and echos them as HTML-Code, which I then want to retrieve again via AJAX to display it in the .chat-container.
First things first, the PHP-Script is working. When it gets the neccessary $_POST-Variables it produces the HTML for the messages:
if (isset($_POST["from_user"]) && isset($_POST["to_user"])) {
try {
$from_user = $_POST["chat_user"];
$to_user = $_POST["chat_target_user"];
$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";
$statement = $db->prepare($query);
$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));
$to_messages = $statement->fetchAll(PDO::FETCH_ASSOC);
$from_user = $_POST["chat_target_user"];
$to_user = $_POST["chat_user"];
$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";
$statement = $db->prepare($query);
$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));
$from_messages = $statement->fetchAll(PDO::FETCH_ASSOC);
$all_messages = array_merge($to_messages, $from_messages);
usort($all_messages, "sortFunction");
$html_messages = "";
foreach ($all_messages AS $message) {
if ($message["from_user"] == $to_user) {
$html_messages .= "<div class='chat-massage-container'><div class='chat-massage-a'>". $message["message"] ."</div></div>";
} else {
$html_messages .= "<div class='chat-massage-container'><div class='chat-massage-b'>". $message["message"] ."</div></div>";
}
}
echo $html_messages;
} catch (PDOException $ex) {
echo "An error occured!";
}
}
Sadly the PHP-Skript does not receive the neccessary $_POST-Variables. So there has to be something wrong with the AJAX submitting the .chat-ident-form. It looks like this:
function submit_ident_form_via_ajax () {
$(this).ajaxSubmit(function() {
getMessages();
});
setTimeout(submit_ident_form_via_ajax, 3000);
}
function getMessages () {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
document.getElementsByClassName('.chat-container').innerHTML = request.responseText;
}
};
request.open('GET', './src/assets/widgets/chat-widget/get-messages.php', true);
request.send();
}
Notice that I am using the jQuery Form Plugin for the AJAX. When the submission returns success the getMessages() function is called, which retrieves the HTML from the PHP-Script and displays it in the .chat-container. Well at least in theory it does. In reality, nothing happens. So the form is not submitted by the AJAX and the HTML is neither retrieved from the PHP-Script nor displayed in the .chat-container.
I am pretty new to AJAX and I am completely lost here! What would be the right AJAX to send the .chat-ident-form to the PHP-Script? (Can be with JS, jQuery or jQuery Form Plugin... idc) How should I trigger the submission of the .chat-ident-form? Via onclick - as I currently do - or is there a better way?
And then there is also the question: How do I retrieve the HTML echoed by the PHP-Script and display it in the dynamically generated .chat-container? What is the correct AJAX to do that? When does this happen? Does it happen with the submission or does it happen seperatly? How does it get triggered?
So I need to know two things from you guys:
The right AJAX to send the hidden .chat-ident-form and how to trigger it.
The right AJAX to get the HTML echoed in the PHP-Skript and display it in the dynamically generated .chat-container and also when to do this.
Overall I am just confused and my brain hurts after several hours of thinking about it!!! Maybe there is a much easier way, but I dont see it right now. Or maybe my whole thought process is flawed... =/
Anyways, I tried to explain my problems as well as I could. If anything is missing feel free to ask and please have some mercy (this is my first ever question at StackOverflow).
I would be really happy, if anyone has a solution. =)
I want to get the refreshed option values from database only when i click on select box.
Suppose two waiter open the same order panel page at same time. Then table no:2 is shown as free in both of the panel.
Now a waiter booked table no:2. Then another waiter when clicked on the select box, he will not get the table no:2 in the options.
<select name="table_id" class="form-control tablename">
<option disabled="disabled">Select Table</option>
<?php $result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
while ($row=mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['table_id'];?>"><?php echo $row['table_name']; ?></option>
<?php } ?>
</select>
table_status
rtable
Create function in php to generate options ( sending html is not good practice but I am adjusting to this example). In this particular example i suggest to create functions.php file and there add printSelectOptions function declaration:
function printSelectOptions(){
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result)){
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
}
Above function prints all html options for select.
Use it function in generating select ( remember that functions.php should be included in any file with usage of printSelectOptions ):
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
?>
<select name="table_id" class="form-control tablename">
<?php printSelectOptions() ?>
</select>
In frontend bind Your select ( javascript code ):
document.addEventListener("DOMContentLoaded", function(event) {
var select=document.querySelector("select"); //this is pure selector gets first select on page
//function sends ajax and refresh options of select
function refreshOptions(){
//send ajax request
select.innerHTML="<option>Loading..</option>"; //loading info
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", 'yourSecondPHPScript.php');//here example url where we get updated options
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
select.innerHTML = xmlhttp.responseText;//set new options
}else{
console.log('Error: ' + xmlhttp.statusText )
select.innerHTML="<option>Connection problem</option>";
}
}
}
xmlhttp.send();
};
//bind our select
select.addEventListener("focus",function(){
refreshOptions();
});
});
Last create example yourSecondPHPScript.php and in it use function:
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
printSelectOptions();//outputs options
To be sure that users will not take the same table besides checking in focus check it again in some submit of order form. So if table was taken refresh select ( by ajax using refreshOptions() ) and show info that this table was taken.
Last thing is to secure it on server side, create some check function in php ( PHP CODE ):
function tableCanBeTaken($optionId){
//this code adds **and** to query with id to check but optionId should be validate before using in query
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
and ts.table_id=$optionId ")or die(mysql_error());
return mysql_fetch_array($result); //if row exists - will be false if not exists row with table_id==$optionId and not booked
}
}
Then use it (PHP CODE ):
if (tableCanBeTaken($youOptionId)){
//here code for taking option
}else{
//here option is taken
}
Have the ajax call in the focus event of the select box.In the success of the call, append the data(available tables) to the select input.Until then, leave the select box options as 'Loading. Hope this helps!
#Maciej Sikora
problem is fixed. printSelectOptions() function can not be called from another file like yourSecondPHPScript.
And also needs to remove the back-slash from url.
xmlhttp.open("GET", 'yourSecondPHPScript.php');
i just paste the same code in yourSecondPHPScript.php like below
<?php
include("connect.php");
$result = mysql_query("select * from rtable r inner join table_status as ts on ts.status_id=r.status_id where ts.status!='Booked' order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result))
{
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
?>
I am in a big trouble. It's 2:45am and I have been since 6pm searching for ideas or examples or whatever you wanna name it!
I have this js function called from a but I can get it to work AT ALL.
The idea is type you city name and get suggestion in a select box. Than, from the select box you can click in one of the cities and this information going back to your form field.
There are two files: index.php (js function showhint and a form calling another .php file to load the cities as suggestions)
The code can be see at www.bfamily.net
I will be very great-full for any help.
Regards,
Add an event onchange on your select to set the value
function(inputName, event) {
document.getElementByName(inputName)[0].value = event.target.selectedOptions[0].value;
}
But I recomand you to do something like that on your inputs :
<input type="text" name="zipCode1" onkeyup="showHint(this.value)" size="20" value="" style="text-transform:uppercase" list="suggestion">
<datalist id="suggestion">
<option>Houston, TX 77070</option>
<option>Cypress, TX 77433</option>
<option>Cypress, TX 77429</option>
</datalist>
Of course you can either generate the datalist with PHP on the page load or with an AJAX request.
May be this will be helpfull
if (filter_var($q, FILTER_SANITIZE_STRING) || !filter_var($q, FILTER_SANITIZE_STRING) === false) {
if ($q !== "") {
$str = "<select name='suggestion'>";
$q = strtolower($q);
$len=strlen($q);
foreach($zipArray as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name.'<br/>';
} else {
$hint .= "$name".'<br/>';
}
$suggestion[] = $name;
$str .= "<option value='".$name."'>".$name."</option>";
}
}
$str .= "</select>";
if(count($suggestion) > 0) echo $str
}
}
But I think the better way is to have a hidden selectBox in your html and then send json "suggestions" list from .php to your .js file from Ajax and then there add proper options to your selectBox and make it visible
i'm working on this site that allows to students to book seats for training sessions by selectiong theme on a drop down list and clincking on a button. i created a javascript(ajax) script that contains a function which calls a php script that reduces the number of seats on my database.
But unfortunately it's not working... i need your help guys :
here's my javascript :
<select name="Branche" name="clock" id="clock" onchange="count()"></select>
<a onclick="count()" class="button">
<span class="user">Réserver une place</span>
</a>
<script>
function count(){
var place = document.getElementByTagName(clock);
var option = place.options[place.selectedIndex].id;
alert(option);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "count.php?place=" + place,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var reponse = xmlhttp.responseText;
if(reponse == "yes") {
alert("Votre place a été réservé");
} else {
alert("Vous êtes arrivé trop tard !");
}
}
}
}
</script>
and here's my php script :
try {
$db = new PDO('mysql:host=localhost;dbname=projet','root','',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(Exception $e){
echo $e->getMessage();
die();
}
$nom = $_GET['place'];
$sq="SELECT place FROM formation WHERE nom='$nom'";
$re = $db->query($sq);
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i > 0){
$sqq="UPDATE formation SET place = place - 1 WHERE nom='$nom'";
$res = $db->query($sqq);
echo 'yes';
} else {
echo 'no';
}
The first errors are in this line:
var place=document.getElementTagName(clock);
You need to find the element by it's id, not its tag name. Also click is an non-existing variable; you should use "clock" with quotes:
var place=document.getElementById("clock");
That way place will be the select element. But then later you use this in building the URL parameter:
xmlhttp.open("GET","count.php?place="+place,true);
But place is not the selected value; it is the select element, so that will not work right. Instead you should send the value you have in the option variable:
xmlhttp.open("GET","count.php?place="+option,true);
This is assuming that the value of option is correct. Without seeing the HTML and your database table content, this is impossible to say at this moment.
The PHP script has an error here:
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i>0){
You use $i as if it is the selected value, but that is not true. fetch() returns an array with values, in this case an array with one value. The comparison as you have it will always return true, even if the selected place value is 0.
Furthermore you should alter your PHP script so you do not concatenate values into an SQL string, as it makes you vulnerable to SQL injection. Instead use prepared statements.
Also, your PHP script is not working well when there is a lot of concurrency. Imagine that there is one seat left and two make the PHP call at the same time, then both will see there is one place left before the other one has decreased the count, and both will get a "yes".
Instead you should first perform the update and check for availability within the update statement. Then check if the statement updated a record. If not, then there were no places left. As an update statement locks the record during the update, only one process can do it at a time.
Suggested PHP code after database connection is established:
$stmt = $db->prepare("UPDATE formation
SET place = place - 1
WHERE nom = ?
AND place > 0");
$stmt->execute(array($_GET['place']));
echo $stmt->rowCount() ? 'yes' : 'no';
When i click the more. I wanted the content should expand. I my page i have about 10 question with more option. The question content is coming through the php script.
<?php
$result = mysqli_query($conn, $query) or die("error: " . mysqli_error($conn));
//fetch the data.
if (mysqli_num_rows($result) > 0) {
while($data = mysqli_fetch_assoc($result)) {
$question = $data['question'];
echo "<span class=\"spanstyle\" id=\"fullquestion\">" . substr($question, 0, 170);
echo "...more</span><br>";
}
}
?>
I try to do that by javascript. ContectExpand() fire of when i click.
<script>
function contentExpand() {
var question = <?php echo $question; ?>;
document.getElementById("content").innerHTML = question;
}
</script>
Problem is, $question is changing the value as it is inside the loop. It doesn't have a fixed value.
Also I want to know that I can do that only along with php without javascipt.
For my solution you need some sort of $data['id'], which is unique for each question.. I think it cannot be done only in PHP, but you should try to use jQuery, it makes javascript much easier
<?php
$result = mysqli_query($conn, $query) or die("error: " . mysqli_error($conn));
//fetch the data.
if (mysqli_num_rows($result) > 0) {
while($data = mysqli_fetch_assoc($result)) {
$question = $data['question'];
echo "<span class='spanstyle' id='shortQuestion{$data['id']}'>" . substr($question, 0, 170).
"...<a href='#' onClick='return contentExpand({$data['id']});'>more</a></span>
<span class='spanstyle' id='longQuestion{$data['id']}'>{$data['question']}</span>
<br>";
}
}
?>
Javascript
<script>
function contentExpand( fullcontentId ) {
document.getElementById('shortQuestion'+fullcontentId).style.display = "none";
document.getElementById('longQuestion'+fullcontentId).style.display = "inline";
return false;
}
</script>
There are several issues with you code. Regarding your question, the most important are:
The while loop is generating several span elements with the same id.
The onClick function should content a reference to the element you want to expand.
You dind't include any code constraining the size of the span element, so there is nothing to be expanded.
How to fix them:
Modify the while loop
Create a $i variable that counts the rows and add it to the span id, to the link id and to the javascript function in this way:
$i = 0;
while($data = mysqli_fetch_assoc($result)) {
$i++;
$question = $data['question'];
echo "<span class='spanstyle' id='fullquestion_" . $i. "' >";
echo "<a href='#' id='link_" . $i . "' onClick='contentExpand(" . $i. ");'>more</a> ";
echo $question."</span><br>";
}
Create a javascript function that resize the span element:
You didn't tell us how you want to expand the content. There would be a lot of different ways to achieve it. This is just one that tries to respect your HTML markup, but surely not the best:
<script>
function contentExpand(id) {
var link = document.getElementById('link_'+id);
var span = document.getElementById('fullquestion_'+id);
if(link.innerHTML=='more')
{
link.innerHTML = 'less';
span.style.width = '100px';
}else{
link.innerHTML = 'more';
span.style.width = 'auto';
}
}
</script>
Modify the css of the span element:
A block element like a div would suit better anyway, but maybe you have very good reasons to use a span.
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: right;
}
How to do it without javascript (just PHP):
It is certainly possible, but I guess you don't want to do it.
But if still you want to do so, generate the loop with just partial information about the related $question (as you do in the original code, substr($question, 0, 170)) but put the elements inside a form.
When the user click the more span element, submit the form to send from the client back to the server the information about the selected item.
Then, the PHP script would generate again the page but, this time, the selected item will load the full text of the question ($question instead of substr($question, 0, 170)).
So, you will have to make a new HTTP request call (that means to reload the page, AJAX is not an option if you don't want to use javascript).
Doing all this add a new layer of complexity and make it less efficient.
My advice is, if you don't have strong reasons to don't use javascript, use it.