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
Related
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;
}
How I create a do...while loop (or if there is a better way to go about this - please advise) for a form with potentially additional information?
Background - I've got a form that will accept a users assessment of a particular location (such as a basement). Using only 1 location per form, this works nicely and submits to my db without a problem.
Now I want to enhance this form with a "add new location" button. I don't (obviously) want to create new pages but rather a loop that can store the first location, save it (which I know could be done with be a session variable) and then clear the fields for locations 2, 3, 4, etc.
My confusion is around the functionality of the button. What type of button is this? Reset with a unique id such as new_loc[]?
And then when I write this as a do...while loop should I do it like this:
<?php
do {
all my form fields
} while (some condition that looks for the button submit);
?>
ok so I have a created a simple JS that can "handle" this.
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " locations");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><br><input type='text' name='location[]'>";
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
Now the problem is that JS will add 1 new field - any suggestions on how to add a massive block of HTML to the JS? I tried adding all my fields to the JS and I get a whole bunch of unclosed string errors.
So first of all your form must have action="" method="post"
then add this php to your page:
session_start();
if (isset ($_POST['NameOfSubmitButtonInsideForm'])) {
if (!isset ($_SESSION['sessionName'])) {
$_SESSION['sessionName'] = 1
}
for ($i = 0; $i <= $_SESSION['sessionName']; $i++) {
echo 'some html code like a form with a input that has
<input type="submit" name="submit- . $i .'EndInputTag>';
};
}
So this will loop the number of times the user clicked the button and you can echo out html code based on that number, or what ever it is you need to do in the loop.
Ok I've figured this out. Thanks to Marc B for suggesting JS.
HTML for the button
<input style="margin-left:5px;" class="btn btn-primary" type="button" value="Add Additional Location" onClick="addInput('locInformation');">
JS
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<h3>Location " + (counter + 1) + "</h3>" + document.getElementById('additionalLoc').innerHTML;
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
And then lastly is the new locInformation stuff:
<div id="additionalLoc" language="text">
huge block of HTML with additional fields
</div>
I have an app for making questionnaires. Users have index.php page where they create the questions and choose minimum number of answers, then they have process.php page where they can enter their answers or add more answers.
PROBLEM: When user clicks add more button, it creates textarea of the particular question but with the wrong name. The add more button should add a textarea and change its name according to the minimum of the defined textareas. So if you for ex. have 4 defined textareas in question2, the next textareas should be like odg25, odg26, odg27, odg28 etc...
The problem is in variable $k (process.php) - because it is not defined in addmore function, but I don't know how to pass somehow in this part of code to make it happen.
THIS IS THE TESTING LINK
INDEX.PHP
<input id="btntxt" type="submit" value="TEXT" onclick="addtxt();" /><br/><br/>
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
PROCESS.PHP
<script type="text/javascript">
<?php $chars = $_POST['chars']; ?>
function addmore(index) {
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + //WHAT SHOULD I ADD HERE???;
textarea.rows = 3;
textarea.setAttribute('maxlength',<?php echo $chars ?>);
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
<body>
<?php
$bla = "";
$pitanje = $_POST['question'];
$length = count($_POST['question']);
$req = $_POST['req'];
$requiem = '';
$min = $_POST['min'];
$area = array("","","","","","","","","","","","","","","");
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
if(($min[$j])!="") {
for($k=1;$k<=$min[$j];$k++) {
$area[$j] .= '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea><br/>';}}
if(($min[$j])=="") {
$area[$j] = '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea>';}
$addmore = '<input type="button" name="more" value="Add more" onClick="addmore('.$j.');">';
$bla .= $j.') '.$pitanje[$j].'<br/>'.$area[$j].'<div id="inner'.$j.'"></div>'.$addmore.'<br/>';}}
echo $bla;
?>
FNCS.JS
var n = 1;
function addtxt() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var required = document.createElement("input");
required.type = "checkbox";
required.name = "req[" + n + "]";
var minimum = document.createElement("input");
minimum.type = "text";
minimum.name = "min[" + n + "]";
var div = document.createElement("div");
div.innerHTML = n + ". Question: " + "<br />" + textarea.outerHTML + "<br />" + "Required: " + required.outerHTML + "<br />" + "Min: " + minimum.outerHTML + "<br /><hr/><br/>";
document.getElementById("brain1").appendChild(div);
n++;
}
I did the same kind of dev.
I had a globalized counter (cpt) in the javascript is incremented by 1 each duplication
My variables were duplicated like this id = "foo_" + cpt.
I added a hidden field for the counter <input type="hidden" id = "cpt"> and its value was changed for each replication.
Php side, I recovered the counter and then a loop to iterate through all the duplicate fields.
// For example
$cpt = $_POST['cpt'];
for ($i = 1; $i <= $cpt; $i++) {
$foo[$i] = $_POST['foo_' . $i];
}
I hope it will help.
You're mixing JavaScript and PHP. PHP is doing some part of the question generation and then JavaScript has to pick up where it left off.
The problem with that approach is that you'll find you end up duplicating a lot of functionality.
The answer the quesiton WHAT SHOULD I ADD HERE??? is "odg" + $j + $k
If instead you start by doing:
var questions = <?php echo json_encode($_POST["question"]);?>;
You now have all your question data available in JavaScript. You can move the for loop from PHP to JavaScript and have j and k there.
What you're going to have to do is make $k able to be passed into process.php.
That is accomplished with something like this:
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input id="numRows" type="hidden" name="numRows" value="1"/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
notice I've added a new <input> element with the name "numRows" which will be passed via POST to process.php. I've given it an arbitrary default value of 1, you can set this however you wish.
Now, when a user clicks the "add more" button, within fncs.js do this:
document.getElementById("numRows").value++;
and finally, in your process.php you need to read in the value of this, as $k:
<?php $k = isset($_POST['numRows']) ? urldecode($_POST['numRows']) : 1; ?>
within process.php you may do as you wish, then, with that value $k.
You need to store last text area value in hidden variable and always increment that
first step: At start set value of hidden variable and your counter
'n' same
second step : at each step where you are adding new text area ,
overwrite the hidden value by new counter value of text area
Remember Textarea counter should be always fetched from hidden value
I think this may help you to solve your problem
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;
});
});
I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.