checkbox error in editing using php - javascript

I just wanted to share my problem regarding checkbox here, because i know many can help me here. i have an array of checkboxes named skills[] and i stored the checked checkbox in a single column in my database because this is an application form project. I use implode() to separate the skills selected in the database by:
$skills = implode(',',$skills);
now this is my real problem because I don't have any idea how to retrieve the checked checkboxes in the database because whenever i will try to edit my checked checkbox. nothing in the checkboxes are checked even though the values are in the database.
the php code for getting the value of skills:
$skills = $wpdb->get_results("SELECT skills FROM php_employee_skills WHERE id=13");
if($skills!=null){
foreach($skills as $value):
$skills=$value->skills;
endforeach;
}else{
echo"<div class='updated' style='height:50px; font-size:12px;'>"."<br>".$message." in table skills in database"."</div>";
}
I dont have any idea what to put here in my html code to retrieve the data:
<td><input type="checkbox" name="skills[]" Value="C# Java" class="cbox">C# Java</td>
note: the skills in the application form which is in the form of checkbox are more than 10 so i use implode to save them in my database. is it right to use implode or explode in the situation of my application form?

Like this?
$str="php,mysql,java";
$skills=explode(",",$str);
//print_r($str2);
foreach ($skills as $chk)
{
echo '<input type="checkbox" value="'.$chk.'">'. $chk."\n";
}

Add checked attribute for checked checkbox
<td><input type="checkbox" name="skills[]" Value="C# Java" class="cbox" checked>C# Java</td>
that's no problem if you working only in the checkbox. but if you trying to list who have specified "skill" in database, you should separate them.

if ( $skills != null ) {
foreach ( $skills as $skill) {
....
}
}
Please make sure you read about coding standards in WP. It can improve your code to follow them.
Now, the next problem ist that you need a way to identify your skill:
<td><input type="checkbox" name="skills[]" value="C# Java" class="cbox" <?php echo (in_array('C# Java', $skills) ? 'checked' : '' ) ?> /> C# Java</td>
In this line, you check if the skill is in your skillset. If so, you add the checked attribute, else nothing happens.

Related

How to use JS to hold a variable from a PHP form before submit

I'm quite new to PHP so apologies for not being fully aware of code structures.
In a PHP file I have a form with the options in a drop-down menu being populated from a database query (how many rounds for a tournament based on the number of entrants). Once a user has selected an option for the round of fixtures they want to view that option gets passed as a variable to determine what to display on form submit. On form submit the rest of the page changes to display the fixtures from the database that relate to the Round that the user selected from the drop-down.
My challenge is that after selecting the Round number from the drop-down menu I have to click the submit button twice - once to assign the variable and then the second press of submit to be able to use the variable as part of the process to display the fixture information from the database.
I'm aware that it is possible to use JS to store a variable that can then be used on form submit but I'm not sure how to integrate it with the way the form / has been written.
After looking at a few places on the web (like W3Schools) I've got some basic JS and have tried that but I think there's still a disconnect between the user selecting and storing the variable ready to be used when the submit is clicked.
//Basic JS
<script>
function getFormIndex() {
document.getElementById($_POST['roundselect']).innerHTML =
document.getElementById("roundselect").selectedIndex;
}
</script>
//PHP Elements
if(isset($_POST['submit'])){
$roundnum = $_POST['roundselect']; }
<?php
function setround(){
$roundnum = $_POST['roundselect'];
echo $roundnum;
}
?>
//Form
<div class="h2_select">
<? if($fnum) {
$select_opt = (isset($_GET['round'])) ? $_GET['round'] : 1;
?>
<form method="post" action="/tournaments/<?=$lid; ?>/fixtures/<?= $roundnum; ?>" name="rf">
<!--<input type="hidden" name="id" value="/<?=$lid; ?>" />
<input type="hidden" name="page" value="/fixtures" /> -->
<span class="minput">Select Round
<select size=1 class="mselect" name="roundselect" onChange=getFormIndex();>
<? for($i=1; $i <= $total_rounds; $i++) { ?>
<option value="<?= $i ?>" <?php if($i == $select_opt){ echo 'selected'; } ?> > <?= $i?> </option>
<? }
?>
</select>
<input type="submit" name="submit" value="<?= $lang[185] ?>" class="minput"/>
</form>
<? } ?>
</div>
To confirm, the form works and displays the correct information. The problem is that I currently need to click "submit" twice.
Thanks
Good start, I would do it with a bit of AJAX that allows us to send a request and receive an answer "in the background" - so that first time user changes the select I would fetch data from backend in the background and display it without double-submitting needed.
Please check this thread - I think it is illustrating the same thing;
How to Submit Form on Select Change
It is based on JQuery and I think it is a good start for new developers.
But - if you do not want to use a framework and does not care for older browsers you can just use "vanilla" Javascript with Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and onchange https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Fetch returns the result so then you have to pass it back to the website.
It is very easy to do so with :
1. set a div on your page and add a unique ID to it (like )
2. use document.getElementById("result").innerHTML = resultFromFetch;
So:
listen to onchange on select
fetch from backend when select changes
display fetch result
AJAX is really neat and very good for the user experience as it allows us to get the data asynchronously and in the "back stage" of our application. But then it is a good user experience measure to show also some "please wait" indications and also make sure to show some potential errors (the connection can go "down" when waiting for results and then it is wise to show errors to users instead of them waiting forever).
Hope this helps to point you in a new and exiting direction.

Insert Query from Cloned Form Field

I have a project in which I have to be able make a multiple input if needed. I'm really new to JavaScript and the insert method that I'm familiar with is only POST method which I parsed it from Form. My question is how do I do to use query in my script?
This is my code and the query is needed between Do...While at the bottom:
<div id="form" class="hidden">
Nama : <input type="text" name="nama"><br/>
Kuantitas : <input type="text" name="kuantitas"><br/>
Kategori : <select name="idKategori">
<?php
while ($rowKategori = mysqli_fetch_object($resultKategori)) {
echo "<option value='".$rowKategori->id."'>".$rowKategori->nama."</option>";
}
?>
</select>
<input type="hidden" name="hidden" value="bahan">
<input type="button" id="remove" value="Remove">
</div>
<form>
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
$(document).ready(function() {
var form_index = 0;
$("#add").click(function() {
form_index++;
$(this).parent().before($("#form").clone().attr("id", "form" + form_index));
$("#form" + form_index).css("display", "inline");
$("#form" + form_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + form_index);
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove" + form_index).click(function() {
$(this).closest("div").remove();
});
});
$("#insert").click(function() {
var i = 0;
do {
i++;
} while (i != 5);
});
im really bad at english , so let me explain it as simple as i can.
i wanted to make a form field with submit button, like the usual.
the difference is i wanted to make a clone button so i could add
more form field with single submit button.
the code that i write is something that i learn from another page and im not familiar with it.
i dont know how to get vallue from the cloned page, and i dont know how to handle the value itself in the script as i really noob at javascript
what i wanted to do is how do you get value from all cloned form field while i click the submit button? the method i familiran with is POST method, but i thinking about writedown all my query on the javascript since the POST method could not do the looping for all the formfield, thats why i make the loop on the javascript
and im sorry with my english, im not really good at it
Ok here you go, here is a fiddle of it.
https://jsfiddle.net/2ngjqxge/3/
HTML/PHP
<div id="form_block_wrapper" class="hidden"> <!-- added an outside wrapper -->
<div class="form_block" class="hidden">
Nama : <input type="text" name="nama[]"><br/>
Kuantitas : <input type="text" name="kuantitas[]"><br/>
Kategori : <select name="idKategori[]">
<?php while ($rowKategori = mysqli_fetch_object($resultKategori)): ?>
<option value="<?php echo $rowKategori->id; ?>">
<?php echo $rowKategori->nama; ?>
</option>
<?php endWhile; ?>
</select>
<input type="hidden" name="hidden[]" value="bahan">
<input type="button" name="remove" value="Remove">
</div>
</div> <!-- close #form_block_wrapper -->
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
Please note, I changed a number of things. Most importantly all the names of the inputs that would get submitted i added [], so nama becomes nama[] etc. Now if you were to submit this as a form, on the server side you would get arrays instead of single elements. Single elements would get overwritten by the next dynamically created "form_block" so this is what we would need to process them. The data you would expect on submission of the form would be like this ( assuming we had 3 "form_blocks" ):
$_POST['nama'] = [
0 => 'nama from first form block',
1 => 'nama from second form block',
2 => 'nama from third form block',
];
$_POST['kuantitas'] = [
0 => 'kuantitas from first form block',
1 => 'kuantitas from second form block',
2 => 'kuantitas from third form block',
];
//etc...
Next, I removed any ID's as we know ids in HTML elements must be unique, so there is no point messing with them when we are creating and destroying dynamic content. We could append an index as you originally did, but the selectors are simple enough so we don't really need to do this. And it's worth it to keep things simple, why over complicate it.
I also used the "alternative" PHP syntax for the while block. while(..): with a colon instead of while(..){ with a bracket. It just looks better to me when mixed with HTML to have the <?php endWhile; ?> insteadd of <?php } ?>. It doesn't matter much here as this is small. But after adding buches of PHP, you would have all these hanging } brackets everywhere. It's easier to keep track of the close of code blocks when they are like endIf; endWhile; etc. I also kept the HTML as HTML and not a big string that has to be echoed out, again because it looks better to me that way. It also makes dealing with the quotes " easier then having to concatenate PHP '<tag attr="'.$php.'">'.
These things you can do either way, just I'm a bit particular and a perfectionist when it comes to formatting and readability. Sort of set in my ways.
Javascript (jQuery)
(function($){
$(document).ready(function() {
//get and cache Outer HTML for .form_block
var selectHtml = $('.form_block:eq(0)')[0].outerHTML;
$("#add").click(function() {
$('#form_block_wrapper').append(selectHtml);
});
//use .on for events on dynamic content ( event delegation )
$("#form_block_wrapper").on('click', 'input[name="remove"]', function() {
$(this).closest(".form_block").remove();
});
$("#insert").click(function() {
//I have no idea what you want to do here?
//Are you trying to insert something into the page
//or Are you trying to insert the data into the DB, ie submit it to the server.
//you can serialze all the data https://api.jquery.com/serialize/
//$('#form_block_wrapper').serialize();
//you can get the selected options and get their value
var d = [];
$('select[name="idKategori[]"]').each( function(){
d.push($(this).val());
});
alert(d.join(','));
});
}); //document.ready
})(jQuery); //assign jQuery to $ - for compatibility reasons.
The first thing to do here is not clone the select but instead take a snapshot of it's html. Stored in selectHtml. There is several reasons why this is better.
if user changes the value of these fields, when we clone we have to reset all those values.
if we remove all form blocks, there is nothing to clone and we are struck on a page without our form elements, tell we refresh.
based just on the length of my code -vs- your orignal code, it should be obvious which method is simpler to handle. Simple is easy to read and maintain, do more with less.
Another thing to note, is you were attaching the remove button's event to each button as they are created. While this is ok, we can do better by using event delegation $.on to handle this element.
I still have no Idea what you want done with Insert,
do you mean insert something into the page
do you mean submit the form and insert the data somewhere.
but hopefully this helps

Saving a response with the submit button (html)

2 weeks ago I taught myself html, css and javascript in my spare time. I know the basics of all three of these languages. I just need a little help with the submit button and server side programming.
Here's my problem:
I made a website (html & css) that randomly generates two things to rate (for example, girls). Under these, there is a radio button for left or right. Then under that there is a submit button. When you enter left or right and hit submit, there is no rating algorithm, so it just goes to the next file (which repeats this). I want to know how to put in a rating algorithm to keep score (like elo or a rating/10). How should I approach this? I thought of a couple of ways, but I don't know if I can pull it off in JS or I'll have to learn php.
For JS, the only idea I have is maybe making and if/else if. For example:
If girl1 and girl2 are available and girl1 is chosen:
Run this algorithm.
Else if girl1 and girl2 are available and girl2 is chosen:
Run this algorithm.
If I do this, will the variables change and be saved when anybody uses the site, or are there limits?
I will also be using a web hosting service, I don't have my own server.
Thanks a ton!
This is the form that you would use for selection. Lets say a file named abc.php
Write a bit of html in abc.php
<form method="POST">
<input type="radio" name="person" value="1" />
<input type="radio" name="person" value="2" />
<input type="submit" name="submit" />
</form>
This is the server side scripting
And a bit of php in abc.php
<?php
if(isset($_POST['submit']))
{
$person = $_POST['person'];
echo $person;
}
?>
This $person has now the value either 1 or 2. Since you have gotten the value now you can use it. for instance
<?php
if(isset($_POST['submit']))
{
$person = $_POST['person'];
echo $person;
ratePerson($person);
}
function ratePerson($person)
{
//some logic of your algorithm
}
?>

How to GET value from an input checkbox to use it in a query to show information

I'm trying to GET information about rooms and towers in an orientation system. It is a search device throw checkboxes. The point is to select each option to filter the information retrived from the database.
The problem is that the values i'm trying to GET are not even echoing, so I can't use them in the query. On the other hand they are showing in the URL and if I add a submit button I can GET the information I want, but the idea here is to get the information instantly without the button.
This is the refresh code i'm using
var auto_refresh = setInterval(
function()
{
$("#results").load("searchroom.php").fadeIn("slow");
}, 1000);
$.ajaxSetup({ cache: false });
This is how i'm saving the values that are selected in the URL
$('input[type="checkbox"]').on('change', function(e){
var data = $('input[type="checkbox"]').serialize(),
loc = $('<a>', {href:window.location})[0];
$.post('/showbytipo.php?'+data);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?'+data);
}
});
This are the HTML inputs
<form method="GET" action="searchroom.php" id="myform" name="myform">
<p>TIPOLOGIA</p>
<ul>
<li><input class="tipologia" id="tipologia"name="tipologia" type="checkbox" value="services" ><label>Serviços</label></li>
<li><input class="tipologia" name="tipologia" type="checkbox" value="class"><label>class</label></li>
</ul>
<p>TORRE</p>
<ul>
<li><input class="torre" name="torre" value="a" type="checkbox" value="a" ><label>A</label></li>
<li><input class="torre" name="torre" value="b" type="checkbox" value="b"><label>b</label></li>
</ul>
</form>
<div id="results" >
</div>
This is the PHP code to GET the values from the url
<?php
include("connect.php");
$tipo=$_GET['tipologia'];
echo $tipo;
$torre=$_GET['torre'];
echo $torre;
//$tipo='services';
$sql = "select * from rooms where tower='$torre' AND floor='$piso' AND typology='$tipo'";
//$sql = "select * from rooms where typology='$tipo'";
$query = mysql_query($sql) or die ("erro na query");
while($row = mysql_fetch_array($query)) {
echo $row["name"];
echo $row["tower"];
echo $row["typology"];
}
echo 'ola';
?>
Apart from that you have serious security issues by having get variables straight to your query, your input fields are named the same. e.g.: name="tipologia" and name="torre" has 2 instances and in the url only the second one will take effect (if it's selected).
If you want to pass multiple values your names should be like: name="tipologia[]" and this way you will see them in php as an array.
Also I know it's irrelevant, but why you are using $.post since you want to pass the values as get? Why don't you use $.get instead?
Edit:
I didn't saw that refresh part of the question.
You don't pass any variables in the refresh call if you want to pass variables the code should be like:
var auto_refresh = setInterval(
function()
{
$("#results").load("searchroom.php", $('#myform').serialize()).fadeIn("slow");}, 1000);
$.ajaxSetup({ cache: false });
I hope you know what are you doing, because the whole concept with refresh is quite messy to me, but still you have problem with the empty values from checkboxes:
You should have a javascript code which update a separate hidden field, which hold the state of the tipologia or torre fields. otherwise you can't rely on the checkboxes, their value will be always the last one checkbox.
Of course the easiest way is to use radio buttons and then you won't have this problem with the hidden field.
For debugging the variables you should use var_dump($_GET['torre']) and it will give you exactly what is in it. So, if it's empty you should see it or if it's undefined you will see null.
hope that helps.

How to retrieve value from database on check box click?

Hi i have three check box where i want that which one check box i select regarding that check box value should retrieve from database
Here is my check box
<input type="checkbox" name="test" value="X-Ray" style="margin-top:10px;margin-left:120px;"><label>X-Ray</label>
<input type="checkbox" name="test" value="Ecg" style="margin-top:10px;margin-left:20px;"><label>ECG</label>
<input type="checkbox" name="test" value="Blood Test" style="margin-top:10px;margin-left:20px;"><label>Blood Test</label>
mysql query
SELECT SUM(price) from test where test='x-ray' or test='' or test='bloodtest'
how can i get my desired output? Any help will be appreciated.
You could get a hold on the specific input checkbox using the jquery selector :checked. So something like this in your javascript should get you started :
$( "input" ).on( "click", function() {
var sel = $( "input:checked" ).val();
//Here you can just make a simple ajax request to a php script passing the
//specific checkbox value and let that script perform the mysql query.
$.post( "test.php", { test: sel })
.done(function( data ) {
alert( "Completed");
});
});
Your test.php script could look something like this:
<?php
$test = $_POST["test"];
//Replace with your sql database credentials
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT SUM(price) from test where test='".$test."'");
mysqli_close($con);
?>
This is a barebone starting template of how you could proceed with your problem. Ofcourse, the specific use case could vary. For instance you could make a get request instead of a post request and make your php script interact and fetch data differently.
I just gave you an example of how the workflow would look like in simple jquery and php. So you just get the value of input checkbox and pass on the value to a script that interacts with the database and fetches the specific SUM. You should probably read some documentation on Jquery Ajax or PHP Mysql to get a better hang of this. Hope it helps.
I think that the best solution to this is to output all the prices as a JavaScript variable somewhere on the page, Let's alter the HTML a little bit.
<input type="checkbox" class="chkbox-update" name="test" value="X-Ray"><label>X-Ray</label>
<input type="checkbox" class="chkbox-update" name="test" value="Ecg"><label>ECG</label>
<input type="checkbox" class="chkbox-update" name="test" value="Blood Test"><label>Blood Test</label>
Now, the prices. Use PDO to itterate through results and construct a JSON-formatted variable:
<script>
var prices = {"X-ray": 3900, "ECG": 2000, "Blood Test": 1200};
</script>
Then use JavaScript to update the price field, I'm using jQuery for this.
$('.chkbox-update').click(function() {
var total;
$.each($('.chkbox-update'), function(k,v) {
total += prices[$(this).val()];
});
$('#result').text('The total price is '+total);
});
Make Sure that the key for the prices variable matches the value of the <input>

Categories