PHP array determined with JavaScript? - javascript

I have a problem with complicated JS determination of exact item:
this PHP/SQL code:
$prod = array();
$vys = mysqli_query($db,"SELECT * FROM produkty ORDER BY nazev");
while ($arr = mysqli_fetch_assoc($vys)) {
$prod[$arr['id_typu']][] = "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
$polozky[$arr['id_typu']]= '<select name=idp[]>' . implode(' ', array_values($prod[$arr['id_typu']])) . '</select>';
}
this JS code:
<script type=\"text/javascript\">
function polozky(divName, typ){
var newdiv = document.createElement('div');
newdiv.innerHTML = \" $polozky[1] \"
document.getElementById(divName).appendChild(newdiv);
}
</script>
and this HTML code:
<form method='post'><fieldset>
<button type='button' name='typ' value='1' onclick=\"polozky('dynamicInput', '1');\">Add produkty from cathegory 1</button>
<button type='button' name='typ' value='2' onclick=\"polozky('dynamicInput', '2');\">Add produkty from cathegory 2</button>
<button type='button' name='typ' value='3' onclick=\"polozky('dynamicInput', '3');\">Add produkty from cathegory 3</button>
<div name='dynamicInput'></div>
</fieldset></form>
The problem is, that for each cathegory I want to generate (for every value of button) its own content. Using that $polozky[1-3] I'm querying the database for the right items of that cathegory (for items WHERE id_type=value in bracket). And I can't imagine that for 100 cathegories, I need to manually insert 100 times $polozky[1-100]. There must be some trick to do this. Somehow to store the value or some usage of that parameter (i was thinking of some $num=typ inside of the JS branch, but it's not possible due to the different processing type of JS and PHP).
Do you know, what to do please? ;) Thank you

Try this
<script type=\"text/javascript\">
document.getElementsByTagName("button").onclick = function() {
var newDiv = document.createElement('div');
newDiv.innerHTML = this.innerHTML; //Puts text from button inside new Div
document.getElementById('divId').appendChild(newDiv);
}
</script>
I think this is what you are looking for. When a button is clicked you want to have a function that executes that will take the current text enclosed by the button, add it to a newly created div and append that to the page. You also need to give your last div an ID of "divId".

Related

Passing values from a php generated table to modal

I got a table generated in PHP:
<tbody>
<?php
$results = DB::select()->from('users')->execute();
foreach ($results as $user) {
echo "<tr id='".$user['id']."'>
<input type=\"hidden\" id='userNameHidden' value='".$user['username']."'>
<input type=\"hidden\" id='userEmailHidden' value='".$user['email']."'>
<td class='username'>".$user['username']."</td><td class='email'>".$user['email']."</td><td class='lastlogin'>".date('d/m/Y',$user['last_login'])."</td><td class='logins'>".$user['logins']."</td><td><a class='editThis'><i class=\"small material-icons\">mode_edit</i></a> delete</i> </td></tr>";
}
?>
My question is, how to make the edit/delete buttons work on a modal that is opened on the same site? I just want to pass values from <td> to <input type="text"> on the modal.
You can send it with GET or POST method to another php file and than work with them there. If you want to work on the same page you can get it via JavaScript:
var value = document.getElementById ( "userNameHidden" ).innerText;
After that:
document.getElementById ( "inputid" ).value = value;
If you would like to create a login system definately use POST or GET (not recommended) to pass the values.
If you want it to happen with a button click. You can make a funcion and a button to go with it:
<button onclick="delete()">Delete</button>
And the js:
function delete(){
var value = document.getElementById ( "userNameHidden" ).innerText;
document.getElementById ( "inputid" ).value = value;
}

Want to call a javascript function with 2 parameters in innerhtml

I have a JSP containing JavaScript function.Within that I created an inner html code.That contain a button with onClick function.When clicking the button I want to pass 2 parameters to the the function of JavaScript. But I can't get the 2 values properly.Please help me
Thank you
<script type="text/javascript">
function find(){
var i=0;
var servicetypevalue="SERVICE";
var td7= document.createElement("td");
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
}
function getStatus(i,servicetypevalue){
alert("enter");
}
</script>
I want to show the enter alert.But the parameter values are not properly passed.
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus(' + i + ',' + servicetypevalue + ');">';
use string concatenation as given above.
If your'e going to generate your own elements in JS, it's different than jQuery. While in jQuery you can make strings into valid markup reliably, but JS is not as sophisticated. Yes you can make an element by innerHTML, but it's error prone. The procedure to accomplish what you want in plain JS is as follows:
#1. Create an element.
#2. Append element to a parent.
#3. Add attributes to element.
The way your code is, it wouldn't work because your'e skipping #2. .td7 is never appended on the DOM and if the innerHTML of .td7 was rendered, it might succeed that'd be wierd. Instead of using an inline event which limits you, addEventListener gives you much better control and is more manageable. Also your getStatus just alerts "enter" which doesn't prove that your 2 parameters actually were passed. I added another alert as proof that the parameters were passed.
var i = 0;
var servicetypevalue = "SERVICE";
var host = document.querySelector('body');
var td7 = document.createElement('td'); //#1
var ptBtn = document.createElement("button"); //#1
host.appendChild(td7); //#2
td7.appendChild(ptBtn); //#2
ptBtn.className = "button"; //#3
ptBtn.name = "ptBtn"; //#3
ptBtn.id = "ptBtn"; //#3
ptBtn.innerHTML = "View Status"; //#3
function getStatus(i, servicetypevalue) {
alert("enter");
alert("i: " + i + "\nservicetypevalue: " + servicetypevalue)
}
ptBtn.addEventListener('click', function(event) {
getStatus(i, servicetypevalue);
}, false);
window.load = find;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
Try to replace
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
to
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="' + "getStatus('i','servicetypevalue'" + ');">';

How to display multiple rows of variables through an html tag

I have 3 pages, an html, javascript and php file. When one button is pressed in the html page, the php page searches a database for rows with the button's name as key and brings back a number of rows. I want to display all those rows in the html page but when I send back the data, it doesn't get displayed. here is my code from the three pages.
Html page
<button name = 'science'> Science</button>
<button name = 'engineering'> Engineering</button>
<button name = 'math'> Math</button>
<button name = 'law'> Law</button>
<button name = 'arts'> Arts</button>
<button name = 'business'> Business</button>
<button name = 'fiction'> Fiction</button>
<button name = 'selfhelp'> Self Help</button>
<button name = 'labequipment'> Lab Equipment</button>
<p id = 'feedback'></p>
<script type ="text/javascript" src ="jquery.js"></script>
<script type ="text/javascript" src ="catselect.js"></script>
javascript page
$(":button").click(function(){
var cat = $(this).attr("name");
$.get("trier.php",{input: cat}, function(data){
$("#feedback").html(data);
});
});
php page
if(isset($_GET['input'])){
$catt = $_GET['input'];
$info = "SELECT * FROM books WHERE (Category = '$catt')";
while(mysqli_query($conn,$info)){
$information = mysqli_query($conn,$info);
$intel = mysqli_fetch_assoc($information);
echo $intel['Title'];
echo nl2br("\n");
echo $intel['Course'];
}
}
I want to display many rows including a 'title' column and a 'course' columnn in the tag in the php page with the id = "display". Any ideas as to how I can modify my code to do that?
$(":button") should be $("button")
u can use php echo html of table but i suggest use json or use angularjs
id should not change frequently, id = "display" better use class="display" instead
You can do the simple way like how #Yanjun Lin suggested using html table
on your php:
if(isset($_GET['input'])){
$catt = $_GET['input'];
$info = "SELECT * FROM books WHERE (Category = '$catt')";
$html='';
while(mysqli_query($conn,$info)){
$information = mysqli_query($conn,$info);
$intel = mysqli_fetch_assoc($information);
$html=$html.'<tr>';
//echo $intel['Title'];
//echo nl2br("\n");
//echo $intel['Course'];
$html=$html.'<td>'.$intel['Title'].'</td>';
$html=$html.'<td>'.$intel['Course'].'</td>';
$html=$html.'</tr>';
}
echo $html;
on your javascript:
$("button").click(function(){
var cat = $(this).attr("name");
$.get("trier.php",{input: cat}, function(data){
$("#feedback").html(data);
});
on your html (change <p> tag to <table> tag):
<button name = 'science'> Science</button>
<button name = 'engineering'> Engineering</button>
<button name = 'math'> Math</button>
<button name = 'law'> Law</button>
<button name = 'arts'> Arts</button>
<button name = 'business'> Business</button>
<button name = 'fiction'> Fiction</button>
<button name = 'selfhelp'> Self Help</button>
<button name = 'labequipment'> Lab Equipment</button>
<table id = 'feedback'></table>
<script type ="text/javascript" src ="jquery.js"></script>
<script type ="text/javascript" src ="catselect.js"></script>
I did not test on your php, but do hope it works... also JSFiddle it would look something like this in javascript and html only. Also do consider using use json for proper standard like how #Yanjun Lin suggest

Jquery 'find' not working with data tag

I'm struggling to get the Jquery 'find' to work in the following code. I've stripped it down to the very basics. In short, what I'm trying to achieve is, I have two lists containing the same names. When the name is clicked on the top list, I want a more detailed box to toggle open below. Then when either is clicked again, the lower box will toggle closed again.
I assume something is wrong in the Jquery with the 'find'. The other part, which collects the ID works fine when the ID is sent to an alert.
I've looked through other answers and that find section is from another answer but it doesn't work in this example, so presumably I'm doing something wrong on some other level.
Bear in mind that just finding the div or paragraph element won't work for my full code. I've just put them in those tags for this example. I basically need to find (in this example), the para inside the correct div (obviously there's only one div here but loads in my full code).
<html>
<body>
<?php
for ($x=0; $x<10; $x++) {
echo "<p class = 'player_name' data-playerid = $x>Player $x</p>";
}
echo "<div class = 'individual_player_reports'>";
for ($x=0; $x<10; $x++) {
echo "<p class = 'player_name' data-playerid = $x>Player $x</p>";
}
echo "</div>";
?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$('.player_name').on('click',
function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[playerid='" + id + "']").toggle();
});
</script>
</body>
playerid !== data-playerid
Data attributes are just like any other attributes. Use the full name of the attribute when using the attribute equals selector.
$('.player_name').on('click',function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[data-playerid='" + id + "']").toggle();
});
$('.player_name').on('click',function() {
var id = $(this).data().playerid;
$('.individual_player_reports').find("[data-playerid='" + id + "']").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="player_name" data-playerid='1'>1</p>
<p class="player_name" data-playerid='2'>2</p>
<p class="player_name" data-playerid='3'>3</p>
<div class="individual_player_reports">
<p data-playerid='1' style="display: none;">1</p>
<p data-playerid='2' style="display: none;">2</p>
<p data-playerid='3' style="display: none;">3</p>
</div>
As #T.J. Crowder suggests, you don't need to use .data() in this case, it would be more efficient to skip .data and just get the attribute value directly to avoid initializing the data cache unless you are using .data()'s features elsewhere too.
var id = $(this).attr('data-playerid');

Can I combine of submit ($_POST processing) and onClick (generate new element)?

i have a problem that I want to get the value of pressed button (which generates new input fields everytime it's clicked), and I don't know if I am able to do this..
I have this JS code:
<script type=\"text/javascript\">
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"<select name=idp[]>$options</select>;
</script>
and this php code with html button type
$t_prod = "";
$types = mysqli_query($db, "SELECT id_type, name_type FROM type_prod ORDER BY id_type");
while ($t = mysqli_fetch_assoc($types)) {
$t_prod .= "<button type='button' name='typ' value='".$t['id_type']."' onclick=\"addInput('dynamicInput');\">ADD ".$t['name_type']." </button>";
}
and the PHP code generates me four buttons, and I'd like to know which button was pressed (optimally by the id_type) – so the "special" generated content for each button would be generated. But I can't get the value.. I was thinking of some getting of ($_POST['typ']) and calling the function addInput in it according to the number of button pressed.
I believe it can be solved client side, just use this pointer:
<button ... value="btn1" onclick="addInput(this)">
<button ... value="btn2" onclick="addInput(this)">
then you can access it in your handler, i.e.:
function addInput(obj) {
if(obj.value=="btn1") // generate your innerHTML for the first button clicked
}
the obj is the element which was clicked

Categories

Resources