A Product List is created using the PHP code each product having its own checkbox, I have used the Java Script code to get values of all the selected checkboxes now i need to call an other PHP page which will receive this string data and populate all the selected products list. Can you please tell me the way i can use to send data to another php page using javascript POST method.
Code used to create the product list and get value of selected checkboxes is as follows :
<?php
$cnt=0;
$rslt = mysqli_query($conn,"SELECT Icode,Name,Size,Style FROM productinfo");
if(!$rslt)
{
die(mysqli_error($conn));
}
else
{
echo " <table width='100%'>";
while($row = mysqli_fetch_assoc($rslt))
{
if($cnt==0)
{
echo "<tr>";
}
echo "<td width='30%'>
<div class='card'>
<img src='upload/"."download.jpg"."' alt='Avatar' style='width:100px' >
<div class='container'>
<h4><b>".$row['Name']." <input type='checkbox' name='prodchklist' value=".$row['Icode']." '/> </b></h4>
<p>".$row['Size']."</p>
<p>".$row['Icode']."</p>
</div>
";
?>
</div>
<?php
echo "</td>";
if($cnt==2)
{
$cnt=0;
echo "</tr>";
}
else
$cnt = $cnt + 1;
}
}
echo "</table>";
?>
</div>
<button id="SendInquiry" style="display: block;">Send Inquiry</button>
<script type='text/javascript'>
$(document).ready(function(){
$('#SendInquiry').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0)
{
var resultstring = result.length +"checkboxes are checked";
result.each(function(){
resultstring+=$(this).val();
}
);
$('#divrslt').html(resultstring);
}
else
{
$('#divrslt').html("nothing checked");
}
});
});
</script>
I don't know your reason to use javascript for collecting checkbox values and post it to another PHP page. You can achive what you want without javascript:
Wrap you checkboxes inside a form, set its action to second page, and don't forget to set its method to POST, eg:
<form action="second.php" method="post">
</form>
Put [] at the end of checkbox name to make it array that can send multiple values with one name, eg:
<input type="checkbox" name="prodchklist[]" value="item1">
<input type="checkbox" name="prodchklist[]" value="item2">
<input type="checkbox" name="prodchklist[]" value="item3">
But, if you really want to use javascript to call the second page, for example by using ajax, do this:
Store the selected values in an array, instead of appending each values in one variable.
// add this, to store the data you want to post
var data = {
prodchklist: []
};
var result = $('input[type="checkbox"]:checked');
if (result.length > 0)
{
var resultstring = result.length + " checkboxes are checked";
result.each(function(){
resultstring += $(this).val();
}
// add this
data.prodchklist.push($(this).val());
}
Then during ajax call:
$.post('second.php', data, function(response) {
....
});
In your second PHP file, just retrieve it as usual, eg:
$selectedProducts = $_POST['prodchklist'];
This works for both approach (without javascript and with ajax).
$selectedProducts will be an array instead of simple string value. Just iterate the array to use the values, eg:
foreach ($selectedProducts as $product) {
echo $product;
}
Related
I have a list of categories for products on my site and am trying to allow products to be listed under multiple categories.
When creating a product there is a list of categories with checkboxes generated from PHP like so:
$sql = "SELECT * FROM categories";
$stmt = DB::run($sql);
$categoryCount = $stmt->rowCount();
if ($categoryCount > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
$category_name = $row["category"];
$category_checkboxes .= "<input type='checkbox' value='$id' name='cat_$id' id='cat_$id'> $category_name<br />";
}
}
I created a hidden input to determine the amount of available categories
<input type="hidden" name="cat_count" id="cat_count" value="<?php echo $categoryCount; ?>">
I am then trying to loop through these in JS to get which ones were selected to send via AJAX to my parsing script to add to the DB.
var categories;
var cat_count = document.getElementById("cat_count").value;
var i;
for(i=1; i<=cat_count; i++){
var cat_id = 'cat_'+i;
var cat = document.getElementById(''+cat_id+'').value;
categories += cat+',';
}
I have two issues with this:
First a category can be deleted so although there might be 3 categories these could have ID's like '1,3,5'. So my checkboxes will have these ID's but the JS is looking for '1,2,3' and it obviously gets an error when it is trying to get the value of a NULL element.
Second, if it can get the values, it will get all of the values of all checkboxes not just the ones that are checked which is what I need. Although if I get a way to loop through the ID's correctly this shouldn't be too difficult to but in a if checked condition.
Any suggestions or assistance with this would be greatly appreciated.
Here is a cleaner way to do this. You don't need cat_count; Add a class to your checkboxes, select all of them, get their value and append it to the categories variable; Working fiddle
var categories = "";
var checkboxes = Array.from(document.getElementsByClassName("checkbox"));
checkboxes.forEach(function(element, index) {
categories += element.value;
});
Id need to be unique so this line var cat_count = document.getElementById("cat_count").value; will always return a single element.
Change it by adding index to it
Instead of Id you can use name with
document.getElementsByName("'cat_$id'")
Thanks to #CBroe for getting there first, that worked for me.
var categories = '';
var category = document.getElementsByClassName("product_category");
var i;
for(i=0; i<category.length; i++){
if(category[i].checked == true){
var category_value = category[i].value;
categories += category_value+',';
}
}
I'm calling viewlog.php which display the xx rows of log table in a frame
The viewlog.php SQl call work.
no issue initializing the $_SESSION
I'm trying to add a next and prev button using a function that increase or decreased $_SESSION['offset']
<input type="button" value=" < PREV " onclick="PIframe();">
<input type="button" value = " NEXT >" onclick="NIframe();">
<iframe src="viewlog.php?os=<?php echo $_SESSION['offset']."&osl=" . $_SESSION['limit'];?>" name="LogIframe" id="LogIframe" />
</iframe
I'm 100% sure the Viewlog.php is getting the value of &_SESSION['offset']
My problem is
I'm not sure if the function are being executed
I'm not sure if the $_SESSION['offset'] is being updated
I don't think document.getElementById is being run
<?php
function NIframe() {
$_SESSION['offset'] = $_SESSION['offset'] + $_SESSION['limit'];
document.getElementById('LogIframe').contentWindow.location.reload();
}
function PIframe() {
$_SESSION['offset'] = $_SESSION['offset'] - $_SESSION['limit'];
document.getElementById('LogIframe').contentWindow.location.reload();
}
?>
I tried converting the Function to Javascript. The reload works but the $_SESSION is not being updated
<script type="text/javascript">
function NIframe() {
<?php
$_SESSION['offset'] = $_SESSION['offset'] + $_SESSION['setofLimit'];
?>
document.getElementById('LogIframe').contentWindow.location.reload();
}
</script>
Help
I have jquery datatable which contains the data pulled from database. By default there's no filtering and it has all the data necessary for that user. There's custom search in input fields in addition to jquery datatables own search. Now i'd like to implement a checkbox action where if checkbox is checked, data is filtered out based on element data-attribute.
This is the checkbox:
<div class='checkbox' id='subplayers'>
<label><input type='checkbox' value=''>Show filtered content</label>
</div>"
The first column of the datatables is a <td> element with an attribute data-insub=x where x is 1 || x is 0 (<td data-insub='1'> or <td data-insub='0'>).
In script i detect the checkbox change:
$('#subplayers').change(function() {
if($(this).is(":checked")) {
//Checked
var playersInSub = document.querySelectorAll("[data-insub='1']");
}
else{
//Not checked
}
});
Now i'd like to filter out all the players who have data-attribute data-insubset as 0 (keep the ones which have it as 1). I think simple search is not sufficient here as this works on data written in table not on data attribute.
This is the PHP which is generating the table row data (more of an informative part of my code as i don't think it's relevant to the problem i'm having.).
$pid = $player['pid'];
$fname = $player['fname'];
$lname = $player['lname'];
$club = $player['club'];
$sameTourney = false;
if (in_array($pid, $playerIds)){
$sameTourney = true;
}
$sameSub = false;
if (in_array($pid,$subPlayers)){
$sameSub = true;
}
echo "<tr id='col+'".$playernumber."_filter'>";
if ($sameSub){
echo "<td class='playernumber' data-insub='1'>".$playernumber."</td>";
}
else{
echo "<td class='playernumber' data-insub='0'>".$playernumber."</td>";
}
echo "<td class='firstnames'>".$fname."</td>";
echo "<td class='lastnames'>".$lname."</td>";
echo "<td class='clubnames'>".$club."</td>";
if ($sameTourney){
echo "<td><a href='#' class='modifyplayer' id='removeModify".$pid."' data-actiontype='remove' data-playerid='".$pid."'>Remove</a></td>";
}
else {
echo "<td><a href='#' class='modifyplayer' id='addModify".$pid."' data-actiontype='add' data-playerid='".$pid."'>Add</a></td>";
}
echo "</tr>";
$playernumber += 1;
You can use jQuery hide() and show()
Hide all rows with attribute data-insub="1" use:
$("table").find("[data-insub='1']").hide();
Show all rows with attribute data-insub="1" use:
$("table").find("[data-insub='1']").show();
As i couldn't find a way to do it with data attributes, i made classes for my rows - if i wish to filter it out i added class allplayers and if i wished it to stay i added class insub.
$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
var myRowClasses = oSettings.aoData[iDataIndex].nTr.className.split(" ");
if($("#subplayers").is(":checked")) {
return myRowClasses.indexOf('insub') > -1;
}
else{
return myRowClasses.indexOf('allplayers') > -1;
}
});
The trick is that elements who have class insub need to have class allplayersas well.
I have a form where you can generate automatically additional form boxes and send them to be handeled at PHP-script. How ever as I am quite lousy with Javascript and I am running in the following problem.
When the form is filled out I can see everything is filled out on the URL, except the the boxes created with JS (every box has unique name!). My guess is that the JS generated field drop out of the form tags, but can not figure out how to fix this. I would appreciate if someone could give me pointers or tell me how to fix this. I shortened the code for clarity (if something got left out please tell me). If someone is wondering why I am not using the form action. It´s because drupal tries to forward the site to wrong place if I do (surprise, not too good with drupal either :D)
<?php
require_once('customer.php');
?>
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "<div class='product'><tr><td>Sku/ID: "+intTextBox+": <input type='text' name='sku_" + intTextBox + "'/></div>";
contentID.appendChild(newTBDiv);
}
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
<table>
<form name="activate">
<div class='cu'>
<tr><td>Sku/ID (oma): <input type="text" name="sku"></td>
<td><p><a href="javascript:addElement();" >Add product</a>
<a href="javascript:removeElement();" >Remove product</a></p></td></tr>
<div id="content"></div>
</div>
<tr> <td><input type="submit" value="Submit"></td> </tr>
</form>
Customer.php
<?php
if(isset($_GET["sku_1"]))
{
echo "found it";
}
else
echo "did not find it";
?>
Any help would be much appreciated!
You could dynamically change the url of the form tag to include textbox values:
var textboxes = document.getElementsByTagName("input");
for (var i = 0; i < textboxes.length; i++){
var data = "?";
if (textboxes[i].type == "text") {
data += (data == "?" ? "" : "&") + textboxes[i].name + "=" + textboxes[i].value;
}
}
form.action += data;
I haven't tested this, you might have to dynamically add all elements
[UPDATE]
If you have trouble with the form you can try using an absolute path, if you aren't already.
I have this block of code:
<div id='mydiv'>
<?php
for($i = 0; $i < count($array); $i++)
{
print"<span>";
print"<input type='button' value='+' />";
print"<input type='button' value='-' />";
print"<span>counter_value</span>";
print"</span>";
print"<br />";
}
?>
</div>
The idea is that you click on one of the buttons and the value in the inner <span> tag increments or decrements by 1. The HTML/PHP itself displays the above perfectly well and displays the elements. However, my issue is that $array can have an arbitrary number of elements. If there are (for example) five outer <span> tags, I want to know which one of the buttons has been clicked .(This would be done using jQuery) Because the HTML is generated in a for-loop I'm reluctant to give the elements IDs.
In the jQuery I think I will need something like this:
var div = $('#mydiv');
div.on("click", "a", function(){
//Determine the <span> tag where the button was clicked.
//Get the counter value from the inner <span> tag within this <span> tag.
//Determine which button was clicked.
//Add/subtract one from value and update value in inner <span> tag.
});
I hope I've made the issue clear enough to be understandable. Any help would be appreciated.
I've just given the button elements class names to determine whether to add or subtract
<?php
$array = array_fill(0,2,'Hello World');
?>
<div id='mydiv'>
<?php
for($i = 0; $i < count($array); $i++)
{
print"<span>";
print"<input type='button' value='+' class='plus' />";
print"<input type='button' value='-' class='minus' />";
print"<span class='counter_value'>0</span>";
print"</span>";
print"<br />";
}
?>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$('#mydiv').on('click','input[type="button"]',function(){
var el = $(this).parent('span').find('.counter_value');
if($(this).hasClass('plus')){
$(el).html(parseInt($(el).text()) + 1);
}else{
$(el).html(parseInt($(el).text()) - 1);
}
});
</script>
$("#mydiv :button").click(function() {
var span = $(this).siblings("span");
var direction = $(this).val() == '+' ? +1 : -1;
span.text(function(i, oldval) {
return parseInt(oldval, 10) + direction;
});
});