Hidden input value to php session - javascript

I have a form, which uses the following input towards the end:
<input type="hidden" id="ct_count" name="ct_count" value=""/>
The initialisation of the form is:
<form action="email_submission.php" method="post" id="form1" onsubmit="mySubmit();">
And the mySubmit function is:
function mySubmit() {
document.getElementById('ct_count').value = ct;
document.getElementById("form1").submit();
}
When i hit submit, I want to pass the value of ct, which is a variable count on the page, to email_submission.php and store it in a session variable. The session variable is returning blank on every submit, and i'm unsure if the value of the "ct" variable used is being passed through on the hidden field.
Is someone able to pick up where i'm going wrong? There are already variables stored correctly through this, so it's not my session settings as far as i know.
tldr: What's the correct way to take a javascript variable count and pass it through form submit to php?
EDIT:
this is the code for adding fields.
intiial loop for the variable "ct"
function new_link()
{
ct++;
<?php $ct = $ct + 1; ?>
document.getElementById("sec4_lender").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_balance").setAttribute('name', 'sec4_balance_<?php echo $ct;?>');
document.getElementById("sec4_termdate").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_security").setAttribute('name', 'sec4_security_<?php echo $ct;?>');
document.getElementById("sec4_description").setAttribute('name', 'sec4_description_<?php echo $ct;?>');
document.getElementById("sec4_status").setAttribute('name', 'sec4_status_<?php echo $ct;?>');
document.getElementById("sec4_repayment").setAttribute('name', 'sec4_repayment_<?php echo $ct;?>');
document.getElementById("sec4_repayment2").setAttribute('name', 'sec4_repayment_2_<?php echo $ct;?>');
var div1 = document.createElement('tr');
div1.id = 'sect4busloan_div_'+ct+'';
// link to delete extended form elements
var delLink = '<tr style="text-align:right;margin-right:65px">Del</tr>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(parentEle.childNodes[eleId]);
var newct = ct - 1;
ct = newct;
<?php $ct = $ct - 1;?>
}

You're taking the input's value and always setting it to ct -
document.getElementById('ct_count').value = ct;
You should get a warning or error about ct in the console if you do it this. What you should do is set a variable to the value of the input -
var ct = document.getElementById('ct_count').value;
It also appears that you never set the value of the hidden field, so in the example I post here ct's value will always be blank.

It turned out that while bug testing i had moved that single session out of the conditionals for my script. So for every page other than the first i was moving on to, it was requesting a blank variable.
Idiocy at its finest. Thank you very much for everyone helping in this matter.

Related

Strings with double quotes in html input field displaying as &quot

Im getting data from sql and using php to generate javascript for an edit button for each entry. The edit interface uses a text input in a form. When the generated edit button is clicked, the text within this field is set to equal the name of the entry from sql.
This works fine in all cases expect when the name contains double quotes ("), in which case the quotes are replaced with &quot in the text field.
The php genertaed javascript is below:
function editButton($suffix,$name)
{
echo "<button class=\"edit\" onclick=\"editMode$suffix()\">Edit</button>";
echo "<script>
<!--
function editMode$suffix(){
document.getElementById(\"title\").innerHTML = \"Edit Artist\"
var main = document.getElementById(\"main\");
main.style.display = 'none';
var edit = document.getElementById(\"edit\");
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById(\"editInput\").value = \"$name\";
document.getElementById(\"artEdit\").value = \"$name\";
}
-->
</script>";
}
The $name variable is sanitized via htmlentities() before being passed to the function. Without doing so, the edit interface for entries with quotes will not even display.
I found this which sounds like the same issue but no solutions (https://code.google.com/archive/p/embeddedjavascript/issues/19) :/
IF anyone has a solution or can point out some stupid thing im doing thats causing this it would be very appreciated. At this point im going to have to just disable database entry for double quotes and limit to singles.
Just change all the double-quotes in the JavaScript portion to single-quotes, then use addslashes() on the $name variable:
function editButton($suffix, $name)
{
$name = addslashes( html_entity_decode($name) );
echo "<button class='edit' onclick='editMode$suffix()'>Edit</button>";
echo "<script>
<!--
function editMode$suffix() {
document.getElementById('title').innerHTML = 'Edit Artist'
var main = document.getElementById('main');
main.style.display = 'none';
var edit = document.getElementById('edit');
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById('editInput').value = '$name';
document.getElementById('artEdit').value = '$name';
}
-->
</script>";
}
*Also added html_entity_decode() to converts the entities back to their initial state. Consider removing the htmlentities() altogether, in which case, you can remove the html_entity_decode() from the above script.

passing primary key instead of attribute on submit

I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander

Issue passing PHP variables through Javascript and back

so this function seems to be confusing me.
echo"
<td style='font-size:12px;width:150px;'><div style=\"overflow-y:auto; max-height:250px; width:200px;\">
{$row['Notes']} </div><br /><center><br />
<button onclick=\"myFunction('{$row['ID']}','$rowID')\">Add Note</button>
<form action=\"http://calls.fantomworks.com/functions/notes.php\" id='notesForm' name='notesForm' method='post'>
<input type='hidden' id='notesID' name='notesID' />
<input type='hidden' id='rowID' name='rowID'/>
<input type='hidden' id='notes' name='notes' />
</form>
</center>";
Calls this javascript
<script language="JavaScript" type="text/javascript">
function myFunction(ID,rowID)
{
var x;
var ID = ID;
var rowID = rowID;
var note = prompt("Customer Note","Write your customer note here...");
if (note != null) {
document.getElementById("notes").value = note;
document.getElementById("notesID").value = ID;
document.getElementById("rowID").value = rowID;
document.getElementById("notesForm").submit();
}
else{
return false;
}
}
</script>
and ends up at this php page
$notesID = $_POST['notesID'];
$rowID = $_POST['rowID'];
$note = $_POST['notes'];
//Redirect to browser
header("Location: ./index.php#row_$rowID");
The only problem is that the rowID does not seem to be making it through and generates links ending like "index.php#row_"
I can't make sense of why rowID isn't coming through but NotesID and notes are.
As you can see from the debug the value is there.
Thanks for any thoughts or suggestions!!
The script at "http://calls.fantomworks.com/index.php" is being POSTed to by your javascript function - thus the variable that you seek ought to be available through the $_POST global.
Try changing
header("Location: ./index.php#row_$rowID");
To
header("Location: ./index.php#row_{$_POST['rowID']}");
Incidentally, the three variables you define in the javascript function seem redundant and could be removed by the looks of things, namely:-
var x;
var ID = ID;
var rowID = rowID;
Have had a closer look since posting original ( and hadn't noticed the assignment of posted vars by the #OP ) - there are hundreds of forms on the page in question - same IDS used from row to row to row. IMHO - this is definitely NOT the way forward - You could have just one form for "Add Note" as you dynamcally set the value by clicking the button. It does appear that the relevant vars ( rowID etc ) are being set and assigned to the button that calls the javascript so theoretically you could have just one form that is used to post to "notes.php" but have this button on each row.
In terms of a general critique / suggestions
The page is very slow to load - due in part to there being hundreds of complex table row layouts, and by the looks of things a form for every button - then there are the images which themselves are fullsize but could really be ( and should be ) thumbnails. The number of forms could be drastically reduced if each button were to dynamically assign the variables like the one in the question above.

changing data output with onchange event

I have an option box which lists the users of something in my site. I then have two input boxes. One for wins and another for losses. I am trying to create an onchange event, so that whenever a certain user is selected from the option box, the php will output that users info. As of now the output is not changing. What am I doing wrong with my onchange event?
function myFunction() {
var wins_var = document.getElementById('wins');
var losses_var = document.getElementById('losses');
}
PHP that outputs the data and html with inputs
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE user_id=user_id")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
echo "<select name = 'member' onchange='myFunction()'>";
while ($row = $stmt->fetch()) {
echo "<option value = '{$ranking_user_id}' data-wins = '{$ranking_wins}' data-losses = '{$ranking_losses}'";
echo ">{$ranking_firstname}</option>";
}
echo "</select>";
} else {
echo "<p>There are not any team players yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}?><br><br>
<label>Wins
<input type="text" value="<?php echo $ranking_wins; ?>" id="win">
</label>
<label>Loss
<input type="text" value="<?php echo $ranking_losses; ?>" id="losse">
</label>
You're on the right lines, and you don't need to do any Ajax just to achieve what you asked in your question.
The main problem is that in your Javascript, you get a reference to the two inputs for wins and losses, but you don't actually assign any value to them.
Assuming you're using jQuery (as you tagged it), then it's much easier to use this for the onchange binding and value assignments.
Firstly, you just need to make sure your "member" select has an ID instead (or as well) as a name, and you don't need the "onchange" as we'll bind that with jQuery:
echo "<select id = 'member'>";
Then, your Javascript just needs to look like this:
$(document).ready(function() {
$("#member").change(function() {
myFunction();
});
myFunction();
});
function myFunction() {
$selectedOption = $("#member option:selected");
$("#wins").val($selectedOption.data("wins"));
$("#losses").val($selectedOption.data("losses"));
}
The initial $(document).ready() function sets up the onchange binding to call myFunction(), and the second myFunction() call just ensures the wins and losses inputs are populated for the default selected option on the initial page load.
JS Fiddle here: http://jsfiddle.net/fa0kdox7/
Oh yes, and finally, your wins and losses inputs just need to look like this:
<label>Wins
<input type="text" value="" id="wins">
</label>
<label>Loss
<input type="text" value="" id="losses">
</label>
Note that I corrected a couple of typos in their IDs.

onClick value + restartCode

<input type="button" onclick="restartBattle('Battle=Trainer&BattleID=294','nFOgYlQGjn')" value="Restart Battle" style="width:160px;">
That is the coding of the button. Unless the restart code is entered as well (it's dynamic, changes every refresh), I can't click the button with the methods of Javascript or jQuery that I've tried.
'nFOgYlQGjn' is the restartCode. I've tried this coding to click the button, but it won't work.
var btn = document.querySelector('input[value="Restart Battle"]');
if (btn) {
var x = Math.round((Math.random() * 90) + 663);
var y = Math.round((Math.random() * 15) + 589);
function restartBattle(url, restartCode) {
$('#battleContent').html('Loading...<br /><br />');
$('#battle').load('http://tpkrpg.net/core/battles/battle.php?'+url+'&RestartCode='+restartCode);
}
//btn.click();
}
This should work, since I took the function restartBattle part out of the source code, but it still won't work. Any ideas?
Pass the data as an object to the script. You could use on('click', method here) or click(method here) on the id of the input tag. Make sure jquery is included too.
button:
<input type="button" value="Restart Battle" id="restart" />
css:
#restart
{
width:160px;
}
jQuery:
/* sample how to get the values as variables
method one, static hard coded
var battleType = "Training";
var battleId = 294;
var restartCode = "nFOgYlQGjn";
method 2, php set via echo, requires page to be created by php, example uses theoretical data returned from a database stored as an associative array but could be changed for variables
var battleType = <?php echo $battle['training']; ?>;
var battleId = <?php echo $battle['id']; ?>;
var restartCode = <?php echo $battle['restart_code']; ?>;
*/
function restartBattle( varz )
{
$("#battleContent").html("Loading...<br /><br />");
$("#battle").load("http://tpkrpg.net/core/battles/battle.php", {Battle : varz.data.type, BattleId : varz.data.id, RestartCode : varz.data.code});
}
// handle the click of the button and execute functon with passed data.
$("#restart").on("click", { type : "Training", id : 294, code : "nFOgYlQGjn" }, restartBattle);
Your php code needs to check for this data being passed to it so it can return the data either some json, html, or plain text using echo.
battle.php:
$restartCode = ( ( isset( $_REQUEST['RestartCode'] ) ) ? $_REQUEST['RestartCode'] : false );
if( !$restartCode ) echo "Error : No restart code!";
That is a start, but you need to create variables that hold the data being sent to the php script or else it's hard coded to those values.
See method API

Categories

Resources