im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.
Related
I am trying to create a while loop that echoes a button for each $version value. shell_exec() returns a value from a Python file and is responsive to a unique $version value. To that end, the basic goal is to create a page where the quantity of buttons is dependent on the version value.
Then, the user can click any specific button and access data for that one specific button(version). To do this, I tried to mix variables with IDs but it did not seem to work. What can I do to fix this? None of the buttons are responsive right now.
Code:
<?php
while ($version != 0) {
echo '
<br>
<br>
<button id="toggle-' . $version . '">TOGGLE</button>
<div style= "display:none;" id="content-' . $version . '">
';
$command = escapeshellcmd("C:/Python38/python.exe C:/xampp/htdocs/Ensemble/login/test.py $email $version");
$output = shell_exec("$command 2>&1");
echo($output);
echo '
</div>
<script>
var toggle = document.getElementById("toggle-' . $version . '");
var content = document.getElementById("content-' . $version . '");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
</script>
'
;
$version--;
}
?>
Edit
A new issue arose. Only one of the buttons work. Both buttons when clicked output the same thing instead of different versions. In SQL all versions are different so this is an error most likely with the html/JS.
Perhaps the following might help - though it is not tested as far as the Python call is concerned but I think the other code should work OK if I understood correctly.
Every ID must be unique in the DOM which I guess is why you tried to make them so by adding the $version number to each. This is not really necessary if you utilise querySelectorAll with a suitable expression. Doing this in conjunction with one or more of the parent/sibling selectors that exists in vanilla javascript allow fairly easy DOM navigation and manipulation. It also means you can use the same piece of code for all the buttons... hope it helps.
<?php
while( $version > 0 ) {
$command = escapeshellcmd( "C:/Python38/python.exe C:/xampp/htdocs/Ensemble/login/test.py $email $version" );
$output = shell_exec("$command 2>&1");
printf('
<br />
<br />
<button data-version="%d">Toggle</button>
<div style="display:none">%s</div>',
$version,
$output
);
$version--;
}
echo "
<script>
Array.from( document.querySelectorAll('button') ).forEach( bttn=>{
bttn.addEventListener('click', function(e){
let version=this.dataset.version;
let div=this.nextElementSibling;
div.style.display=div.style.display=='block' ? 'none' : 'block';
});
})
</script>";
?>
Replace
<div style= "display:none;" "id="content-' . $version . '">
to
<div style= "display:none;" id="content-' . $version . '">
and try.
In a drop down select field I pull several options based on a mysqli query
Once I select them, I use javascript to pick up the variables and infill form fields
Once I select the desired option, a form field infills with a reference number
I want to use that reference number for another select field to query the DB for a separate list
Here is the select to get the ref #
<select id="cdetail" name="cdetail"><option value="">Select</option>
<?
$mlo="SELECT * from client WHERE loan_originator ='$uname'";
$mlo_res = mysqli_query($dbc, $mlo);
while ($row = $mlo_res->fetch_assoc()){
echo "<option value=" . $row['filename'] . ">Filename: " . $row['filename'] . "</option>";
?>
</select>
Once I make the choice from the client table, I will see the filename in the 'cdetail' form field
I want to add another select field to pull from another table based on the selection in the above select option
<select id="ndetail" name="ndetail"><option value="">Select</option>
<?
$filename = $row['filename'];
$quote1="SELECT * from nclient WHERE filename ='$filename'";
$quote_res = mysqli_query($dbc, $quote1);
while ($row1 = $quote_res->fetch_assoc()){
echo "<option value=". $row1['ln_amt'] . ">Loan Amt: " . $row1['filename'] . "</option>";
?>
</select>
Trying to pull the filename from the 1st query and creating a global variable did not work the way I coded it.
I was able to use javascript to push the value into a separate field:
<script>
$('#cdetail').on('change', function () {
var x = $('#cdetail option:selected').val()
$('#flnm').val(x);
});
</script>
This will populate (on change) the flnm field with the filename, but I have not been able to grab that input and convert it into a php variable
i.e.
<? $filename = $('#flnm').val(x); ?>
or
<? $filename = ('#flnm').val(x); ?>
or
<? $filename = val(x); ?>
or
<? $filename = flnm; ?>
Short answer: No, you can't pass variables from javascript to php like that.
But you can do it the other way around (passing php variable to javascript in a php file):
<script>
var variable = '<?= $phpVariable ?>';
</script>
What you can do, is to use AJAX requests to pass the javascript (client side) variables to php (server side).
I'm avoiding using a database for my latest project and so I am using files and folders. I list folders of a directory as buttons and each one loads a screen with a list of files within it. I'm now trying to load in the file's contents dynamically without refresh to avoid loosing the menu (list of files shown on screen as buttons). I'm trying to use ajax but because the file buttons are created using a foreach php loop, the value I pass to javascript/ajax when I click one of the file buttons is incorrect as it always wants to pass the first button's value in the list!
Here is the PHP code:
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' ID='selectBtn' value='$filePathTrimmed' onclick='return displayData();'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And this is the JS:
<script>
function displayData()
{
var btnData = document.getElementByID('selectBtn').value;
alert("The currently selected button is "+btnData);
});
}
</script>
As you can see the PHP loops and creates a form for each button plus hidden fields. The JS just tries to grap the value of the button clicked and alert it. Problem is that the value is always the first file in the list.
What am I doing wrong please? If I use a class on the button instead of an ID then I will need to state the number in the array:
var btnData = document.getElementsByClassName('selectBtn')[0].value;
But this means I'd need to know the place within the array and make using the value pretty pointless.
I'm pretty stuck - or thick!
Thanks.
You need to use this inside onclick='return displayData(); and then use it in your function like below:-
Working snippet:-
function displayData(ele){
var btnData = ele.value;
alert("The currently selected button is "+btnData);
return false;
}
<form method='POST'>
<input type='submit' value='hi' onclick='return displayData(this);'/>
<input type='hidden' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>
You are setting the same id value for each separate form. You should ensure that all the id attribute values are unique for all html elements as a rule of thumb to avoid unpredictable behaviours in the dom.
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $idx => $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' id='selectBtn-{$idx}' value='$filePathTrimmed' onclick='return displayData(this.id);'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And javascript:
<script>
function displayData(clicked_id)
{
var btnData = document.getElementByID(clicked_id).value;
alert("The currently selected button is "+btnData);
return false;
}
</script>
Solution: I used 'return false' at the end of the javascript/ajax code block, and 'this' in the php code to pass current data held in 'value' - thanks Alive to Die.
I also I made use of the 'name' attribute to store and access further data data.
PHP:
echo "<form method='POST'>
<input type='submit' id='selectBtn' name='$file' value='$filePathTrimmed' onclick='return displayData(this);'/>
</form>";
JS:
<script>
function displayData(fileName)
{
var btnData =fileName.name;
var name = fileName.value;
$.ajax({
type : "POST",
url : "DisplayFileContents.php",
data : {"data": btnData, "name": name},
success : function(result) {
$('.page-content').html(result);
$('body').animate({scrollTop: 0}, 200);
}
});
return false;
};
DisplayFileContents.php:
<?php
$filename=$_POST['data'];
$title = $_POST['name'];
echo "<h2>".$title."</h2>";
echo "<pre>";
Include $filename;
echo "</pre>";
?>
I'm trying to add a script element to the HTML from the PHP code and instantly remove it so it won't be visible in the HTML. The script only contains things to execute at the same moment and not functions. Generally, I'm trying to replicate ASP.NETs runat property, so I'll be able to set values of elements (inputs for now) right from the PHP code.
This is what I tried so far (which I found in a different question, with some changes of mine) and it adds the script properly, but won't remove it.
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script>
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '"
</script>';
$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
foreach($script as $item)
{
$item->parentNode->removeChild($item);
break;
}
$html = $dom->saveHTML();
}
Thanks for everyone who were trying to help. Anyway, I found a solution to my question, which is this:
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script id="phpjs">
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '";
document.getElementById("phpjs").remove();
</script>';
}
It adds the script and removes it, so it won't be visible when inspecting elements anymore.
I don't know much about Javascript and Jquery, but I do have to use it on a HTML select tags. I have two database tables, grouptypes and groups. A grouptype can have multiple groups, but a group only belongs to one grouptype. I have two select tags, one is grouptypes and another one is groups. What I want to do is that whenever a user select a grouptype in the grouptypes dropdown menu, it triggers a handler to retrieve the corresponding groups that belong to that grouptype. I need javascript or Jquery to get it done, but I am not able to write it myself. So anyone can help me? I would so appreciate it.
GroupType: <select name="groupType">
<?php foreach($grouptypes as $type) : ?>
<?php echo "<option value='" . $type['name'] . "'>" .$type['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
Group: <select name="groups">
<?php foreach($groups as $group) : ?>
<?php echo "<option value='" . $group['name'] . "'>" .$group['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
<?php
$query = "SELECT id, name FROM group_type";
$grouptypes = $_db->getResultsForquery($query);
$query = "SELECT id, name FROM groups";
$groups = $_db->getResultsForquery($query);
?>
Here's what I would do. It uses jquery to send a get to a page called groups.php which will return some html you can parse. Then you parse it :)
$('#grouptype-select').change(function(){ //.change will detect when the select has been changed (an -option- has been chosen)
var grouptype = $(this).val(); //create a variable from the -option- chosen
$.get('groups.php', 'grouptype=' + grouptype, function(response){ //use jquery to send -get- to groups.php
$('#list-of-groups').html(response); //insert response into ur doc
}
});
Something like http://www.yoursite.com?grouptype=abc will be sent using get asynchronously (ajax) Good luck!
PS Here is a jsfiddle to get you tinkering: http://jsfiddle.net/yLyTw/1/