I have the following code which prints the values in a datatable.
<?php
foreach ($result as $val) {
?>
<input class="example" type="checkbox" value="yes" id="example" name="example"><?php echo $val->id; ?>
<?php } ?>
Now I want to send the value to the server when the checkbox is checked. I have the following code for the same, however I'm confused on how I can get the ID of the row which is echoed by PHP.
$(".example").change(function() {
var value = $('.example').attr('value');
console.log(value);
});
Thanks in advance.
You can set an another attribute to the checkbox like :
<input type="checkbox" data-id="<?php echo val->id ?>">
Then your code will :
$(".example").change(function() {
if($(this).prop("checked")) {
var value = $(this).val();
var id = $(this).data("id")
console.log(value);
console.log(id);
}
});
Related
I have a strange problem. I am getting the table values using PHP MySQL using a while loop and stored them in a array. Then I am displaying it one after another in a single page.
$sql = "select * from newsfeed order by id DESC";
$result = $db->query($sql);
$posts_array = array(); // Storing the result to an Custom Array
$index = 0;
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$posts_array[$index] = $row;
$index++;
}
}
I have successfully set the $post_id of the posts on to the HTML elements using the following code.
<?php
$array_size = sizeof($posts_array);
for($i = 0; $i < $array_size; $i++){
?>
<div class='wrapper' id='wrapper'>
<div class='user'>
<!-- Some Code -->
<?php
$post_id = $posts_array[$i][id];
?>
<input type='image' name='like' id='like' width='40' height='40' src='like_btn.png' value='<?php echo ($post_id);'?> />
<?php } ?>
Now I want to take that value using Jquery and do some Database Work. I have accessed the value using the following code:
<script type="text/javascript">
function justsomething() {
alert($(this).val());
}
</script>
The problem is I am only getting the last post's id as alert() for every post rather than getting different id's .
Please help me. I am confused whether the PHP script is loading every time I click and call the justsomething() function.
Note: I can display the $post_id of every post alone without any problem.
Beacuse the id should be unique to one html element try changing your code to this :
<?php $array_size = sizeof($posts_array); for($i = 0; $i < $array_size; $i++){ ?>
<input type='image' name='like_<?php echo $i ?>' id='like_<?php echo $i ?>' width='40' height='40' src='like_btn.png' value='<?php echo $post_id;?>' onclick='justsomething(this);' />
<?php } ?>
<script>
function justsomething(el) {
var img = el;
alert(img.value);
}
</script>
here is an example
function justsomething(el) {
var img = el;
alert(img.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='image' name='like_1' id='like_1' width='40' height='40' src='like_btn.png' value='15454' onclick='justsomething(this);' />
It works for loop, I hope You can make use of it
$("input[id=like]").each(function(i){
alert($(this).val());
});
It will alert values from every <input id="like"...
Try this code:
onclick='justsomething(this)'
function justsomething(obj) {
alert($(obj).val());
}
I have a problem with my ajax code... I have a list of checkbox, the idea is insert the data of the marked checkboxes into the database.
If I select only one check box, the insert is correct. But if I select for example 3, all data appears on the same field, as unique value.
This is the example:
HTML
<input type="checkbox" class="get_value" value="test1">test1</br>
<input type="checkbox" class="get_value" value="test2">test2</br>
<input type="checkbox" class="get_value" value="test3">test3</br>
<input type="checkbox" class="get_value" value="test4">test4</br>
<input type="checkbox" class="get_value" value="test5">test5</br>
<button type='button' name='submit' id="submit">Submit</button>
This is the ajax code
<script>
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked")){
insert.push($(this).val());
}
});
insert = insert.toString();
$.ajax({
url: "./functions/add_list.php",
method: "POST",
data:{insert:insert},
}
});
});
});
</script>
And this one the PHP that do the insert into the database:
if(isset($_POST["insert"])){
$query = 'INSERT INTO music (name,username) VALUES ("'.$_POST["insert"].'","'.$username.'")';
$result = mysqli_query($conn, $query);
}
For example if I check "test1" and "test2", I will see in my MySQL "name" field "test1,test2". But I need see them in diferent fields, not in the same.
I have tested the "foreach ($_POST["insert"] as $value) { insert... } but it did not help me.
Someone have an idea about my error?
I appreciate your help so much.
Regards,
you need to loop on the server side too :
$arr = explode(',', $_POST["insert"]);
foreach ($arr as $val) {
$query = 'INSERT INTO music (name,username) VALUES ("'.$val.'","'.$username.'")';
$result = mysqli_query($conn, $query);
}
I created a list of radio groups and attached them to a product category. So what am doing is checking the groups that the category is meant to have then am going to then pick up the radio values in those groups available to the category and display them to the user to fill.
The next thing is I want to pass them to my ajax function which will then inject it into database. The problem is I can't get the unique name of the radio input in my ajax since I am loading it from the database.
<?php $notarray = DataDB::getInstance()->select_from_where('pro_print_group','product_category_id',$cat);
while ($row = mysqli_fetch_assoc($notarray)) {?>
<div class="col-sm-12">
<label for="quantity"><?php echo DataDB::getInstance()->get_name_from_id('group_n','print_type_group','print_type_group_id',$row['print_type_group_id']); ?></label>
<div class="printd-group">
<?php
$not = DataDB::getInstance()->select_from_where('print_type','print_type_group_id',$row['print_type_group_id']);
foreach($not as $ow):?>
<label class="printd">
<input name="prind<?php echo $row['print_type_group_id'] ;?>[]" id="prind<?php echo $row['print_type_group_id'] ;?>[]" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>
</label>
<?php endforeach; ?>
</div>
</div>
<?php } ?>
Ajax Function
when form is submitted i call this function
function testpr() {
document.getElementById("load").style.display = "block";
var track = 'YU6758990';
var printd = $('#printd').val();
$.ajax({
type: 'post',
url: 'frverify.php',
data: "track=" + track + "&printd=" + printd + "&ins=testp",
success: function(data)
{
document.getElementById("load").style.display = "none";
jQuery('#get_prresult').html(data).show();
scroll_to('#messs');
}
});
}
PHP function
The ajax function then passes it to this php function where I am to receive the post request which in return inserts the selected radio values to the database and then returns the response back to my front end
function test(){
$track = $_POST['tack'];
$printd = $_POST['printd'];
echo DataDB::getInstance()->testp($track,$printd);
}
My guess is that there are more then one radiobutton generated, if that's the case you could try something like this.
<input name="printd[<?php echo $row['print_type_group_id'] ;?>]" id="<?php echo $row['print_type_group_id'] ;?>" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>
Then in your Javascript change the way you retrieve the values of your form by using serialize.
data: "track=" + track + "&" + $('form#id.selector').serialize() + "&ins=testp"
Then inside your PHP script iterate trough the values with some sort of foreach loop
function test(){
$track = $_POST['tack'];
foreach($_POST['printd'] as $key => $value){
//$key => print_type_group_id
//$value => print_type_id
}
echo DataDB::getInstance()->testp($track,$printd);
}
Not sure what you want to do with the data and what it is you actually need but this should send you in the right direction.
I'm new to this so I have a question regarding dependent drop down menu.
I have two drop down menu first, Leave Type and the second Available Balance.
Below shows the js and form.
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
$sql = mysql_query("SELECT * FROM leaves WHERE emp_id=$emp_id'");
<form method="get">
<label for="category">Leave Type</label>
<select name="parent_cat" id="parent_cat">
<option> Select one </option>
<?php
if ($row['leave_al'] == 1)
{
echo "<option value='Annual Leave'> Annual Leave </option>";
}
if ($row['leave_matl'] == 1)
{
echo "<option value='Maternity Leave'> Maternity Leave </option>";
}
?>
</select>
<label>Available Balance</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
loadsubcat.php
<?php
$parent_cat = $_GET['parent_cat'];
$emp_id = $_GET['emp_id'];
$query = mysql_query("SELECT * FROM leaves WHERE emp_id = 'OR9090'");
$row = mysql_fetch_array($query);
if ($parent_cat == 'Annual Leave')
{
echo "<option value='$row[id]'>$row[total_annual]</option>";
}
if ($parent_cat == 'Maternity Leave')
{
echo "<option value='$row[id]'>$row[maternity_days]</option>";
}
?>
Example above, parent_cat is been passed to loadsubcat in order to load the available balance. I would also like to pass $emp_id to loadsubcat so that the sql can read based on $emp_id. Right now, I can only assign the emp_id manually. Please help me thanks!
and you can try this:
<form method="get">
<input type="hidden" name="emp" value="<?php echo $emp_id ?>"/>
<label for="category">Leave Type</label>
<select name="parent_cat" id="parent_cat">
Put the emp_id on hidden input and then get the value on jquery change
$("#parent_cat").change(function() {
var emp = $(this).siblings('input[name=emp]').val(); (...)
and then complete with Drake said.
$.get('loadsubcat.php?parent_cat=' + $(this).val() + '&emp_id=' + emp, function(data) {
Oh, and be careful with the GET vars from the loadsubcat.php
use mysql_real_escape_string or PDO to protect SQL injections.
I would also like to pass $emp_id to loadsubcat
To add another parameter to the loadsubcat.php query string, you can change
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
to
$.get('loadsubcat.php?parent_cat=' + $(this).val() + '&emp_id=' + $("...").val(), function(data) {
where $("...").val() is the location of the employee ID value in some HTML tag, then in your PHP file you can access them with your code below:
$parent_cat = $_GET['parent_cat'];
$emp_id = $_GET['emp_id'];
my code is now working! I've changed the
var emp = $(this).siblings('input[name=emp]').val();
to
var $form = jQuery(this).closest('form');
var emp = $form.find("input[name='emp']").val();
The rest of code given above is working perfectly fine!
Im trying to add up the sum of two inputs that already have a value in it. I wanted the sum to change value if any of the other two inputs change in value. I have this the following, but its not working:
<?php
while($row = mysqli_fetch_array($test)) {
echo "<tr class='saved_add'>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><select'>";
echo "<option value='service'";
if ($row['type'] == "service") {
echo "selected='selected'";}
echo ">Service</option>";
echo "<option value='hours'";
if ($row['type'] == "hours") {
echo "selected='selected'";}
echo ">Hours</option>";
echo "<option value='days'";
if ($row['type'] == "days") {
echo "selected='selected'";}
echo ">Days</option>";
echo "<option value='product'";
if ($row['type'] == "product") {
echo "selected='selected'";}
echo ">Product</option></select></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input class='subtotal'/></td>";
echo "</tr>";
}
mysqli_close($con);
?>
JQuery:
$('.saved_add').each(function() {
sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
any ideas?
Something along these lines:
function calculateSum() {
$('.saved_add').each(function() {
sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
}
// On first load
calculateSum();
// On change
$("input").change(calculateSum);
Your code will only calculate the value WHEN IT LOADS. You want to calculate it when it loads AND when the value changes, so you need the .change() function.
When you call .val() on an element it returns its value as a string. You have to convert it to a number first before you can do mathematical operations with it. To convert strings to integers, you can use the parseInt() method.
$('.saved_add').each(function() {
var sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
Edit, updated
Try
$('.saved_add').each(function(i, el) {
$(el).on("change", function() {
// cast `sum` as `Number`
sum = Number($('input:eq(2)', this).val() * $('input:eq(5)', this).val());
$(".subtotal").text(sum);
}).change();
});
jsfiddle http://jsfiddle.net/guest271314/20jeoc9y/
Thanks everyone for helping, i figured it out. Helps out to make each input as an ID so you can change it accordingly.
HTML:
<div id="saved1">
<input type="text" value="10" /><input type="text" value="10" /> <input type="text" value="10" />
<div id="subtotal1"></div>
</div>
<div id="saved2">
<input type="text" value="10" /><input type="text" value="10" /> <input type="text" value="10" />
<div id="subtotal2"></div>
</div>
JQuery:
function calculateSum() {
$("[id^=saved]").each(function() {
sum = $('input:eq(0)', this).val() * $('input:eq(1)', this).val();
$('input:eq(2)', this).val(sum);
});
}
// On first load
calculateSum();
// On change
$("input").change(calculateSum);
JSFiddle