How to get variables from js and use them in php - javascript

Hi all i was making a website were you can add excel file and choose a person and when you choose a person then it the web would only print those rows were only is a person that you chosen from select box.
Does anyone know how i could get result variable from js function (function getSelectedPerson()) and that resul insert in php for statement.
<script>
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["dla_dei_mat"]="Deividas Matulis";
filling_prices["dla_tom_ver"]="Tomas Veršinskas";
filling_prices["dla_dar_ser"]="Darius Sereika";
filling_prices["dla_dov_pra"]="Dovydas Prakapas";
function getSelectedPerson()
{
var theForm = document.forms["dla_darbuotojo_pasirinkimas_form"];
var selectedPerson = theForm.elements["dla_darbuotojo_pasirinkimas"];
fillSelectedPerson=filling_prices[selectedPerson.value];
return fillSelectedPerson;
}
</script>
<?php
require_once "Classes/PHPExcel.php";
$chosenPerson = $_GET["getSelectedPerson()"];
$tmpfname = "visi.xls";
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
echo "<table>";
for ($row = 1; $row <= $lastRow; $row++) {
if ($chosenPerson == ($worksheet->getCell('D'.$row)->getValue()) ) {
echo "<tr><td>";
echo $worksheet->getCell('D'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('F'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('G'.$row)->getValue();
echo "</td><tr>";
}
}
echo "</table>";
?>
<form name="dla_darbuotojo_pasirinkimas_form">
<div class="Choose_people">
<select name="dla_darbuotojo_pasirinkimas">
<option value="None">Darbuotojai</option>
<option value="dla_dei_mat">Deividas Matulis</option>
<option value="dla_tom_ver">Tomas Versinskas</option>
<option value="dla_dar_ser">Darius Sereika</option>
<option value="dla_dov_pra">Dovydas Prakapas</option>
</select>
</div>
</form>

I think this is what you are looking for. You can not use Javascript variables in PHP, you have to pass the values via GET or POST requests. You don't need the script portion of your example.
<form name="dla_darbuotojo_pasirinkimas_form" action="yourscript.php" method="get">
<div class="Choose_people">
<select name="dla_darbuotojo_pasirinkimas" onchange="this.form.submit()>
<option value="None">Darbuotojai</option>
<option value="dla_dei_mat">Deividas Matulis</option>
<option value="dla_tom_ver">Tomas Versinskas</option>
<option value="dla_dar_ser">Darius Sereika</option>
<option value="dla_dov_pra">Dovydas Prakapas</option>
</select>
</div>
</form>
Change
$chosenPerson = $_GET["getSelectedPerson()"];
to
$chosenPerson = $_GET["dla_darbuotojo_pasirinkimas"];
You may also need a condition in your PHP script
if(isset($_GET["dla_darbuotojo_pasirinkimas"])) {
// do the get person stuff
$chosenPerson = $_GET["getSelectedPerson()"];
$tmpfname = "visi.xls";
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
echo "<table>";
for ($row = 1; $row <= $lastRow; $row++) {
if ($chosenPerson == ($worksheet->getCell('D'.$row)->getValue()) ) {
echo "<tr><td>";
echo $worksheet->getCell('D'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('F'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('G'.$row)->getValue();
echo "</td><tr>";
}
}
echo "</table>";
}
So if the script has been called with no person it won't try to run that code.

Related

Ajax request with PHP in ASP.NET

I am trying to connect with my database and get some data with Ajax and PHP. I have created a Web App in ASP.NET, i am using Azure Data Studio for database. I do not know how to execute all of this. How can i run the php script, how can i get data from database without reloading the page on changing value in a dropdown.
My connection string is:
"ConnectionStrings": {"ConnectionString":"Server=(localdb)\\mssqllocaldb;Database=DatabaseName; Trusted_Connection=True;"}
My HTML Code is:
<form action="">
<select name="customers" onchange="showValue(this.value)">
<option value="">Select a customer:</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
<br>
<div id="txt">Here is info..</div>
My Ajax request, function in JS:
function showValue(str) {
var xhttp;
if (str == "") {
document.getElementById("txt").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txt").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getValue.php?q="+str, true);
xhttp.send();
}
And finally my PHP script:
<?php
$servername = "(localdb)\mssqllocaldb";
$username = "";
$password = "";
$dbname = "DatabaseName";
$mysqli = new mysqli($servername,$username,$password,$dbname);
if($mysqli->connect_error) {
exit('Could not connect');
}
$sql = "SELECT Id, Name, Number
FROM Table1 WHERE Id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name, $number);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>ID</th>";
echo "<td>" . $id . "</td>";
echo "<th>Name</th>";
echo "<td>" . $name . "</td>";
echo "<th>Number</th>";
echo "<td>" . $number . "</td>";
echo "</tr>";
echo "</table>";
?>

Select onchange update other input fields

I have a form with one Select option and 3 input text box. I fetch the value of select option from database. I want to change data of the 3 input field based on what i select. I try many ways but faild.
<Select onchange="update(this)">
<?php
$query = "SELECT * FROM wheel1 ORDER BY chair_no ASC";
$run = mysqli_query($connect, $query);
$i = 0;
while ($chair = mysqli_fetch_assoc($start)) {
$i++;
?>
<option value="<?php echo $chair['chair_no'];?>"><?php echo $i ?></option>
<?php
$name = $chair['name'];
$phone = $chair['phone'];
$detail = $chair['detail'];
}
?>
It fetch data perfectly for Select menu, But only store the last value for name phone and detail variable. Here is javascript code.
function update( elem ) {
var name = "<?php echo $name; ?>";
var phone= "<?php echo $phone; ?>";
var detail = "<?php echo $detail; ?>";
document.getElementById("name").innerHTML = name;
document.getElementById("phone").innerHTML = phone;
document.getElementById("detail").innerHTML = detail;
}
Any help is appricated. Thanks in advance.
Set diffirent attribute in options for name, phone and detail
Demo: https://jsfiddle.net/sjhhv4pw/
<select onchange="update(this)">
<?php
$query = "SELECT * FROM wheel1 ORDER BY chair_no ASC";
$run = mysqli_query($connect, $query);
$i = 0;
while ($chair = mysqli_fetch_assoc($start)) {
$i++;
?>
<option data-name="<?php echo $chair['name']; ?>" data-phone="<?php echo $chair['phone']; ?>" data-detail="<?php echo $chair['detail']; ?>" value="<?php echo $chair['chair_no'];?>"><?php echo $i ?></option>
<?php
}
?>
</select>
jQuery:
function update( elem ) {
var name = $(elem).find("option:selected").attr("data-name");
var phone= $(elem).find("option:selected").attr("data-phone");
var detail = $(elem).find("option:selected").attr("data-detail");
}
Try below code
<Select onchange="update(this)">
" data-phone="" data-chair-detail="" value="">
javascript code, considering you are using jQuery
function update( elem ) {
var name = ele.data('chair-name');
var phone= ele.data('phone');
var detail = ele.data('chair-detail');
}

How to Auto Select Drop Down Box With Session value

<select>
<?php foreach($result as $city) { ?>
<option value="<?php echo $city->city_name; ?>" <?php if( strtolower($this->session->city) == strtolower($city->city_name) ) { echo "selected"; } ?>
> <?php echo $city->city_name; ?> </option>
<?php } ?>
</select>
Hi i am trying to auto select drop down box with the help of session but i am not able to select please some one help me out how could i auto select drop down box.
First of all. You should always provide the whole code, eg. in format of PHPFiddle.
Secondly, you should not mix HTML and PHP.
Also your problem cannot be deciphered from your question, because there might be several reasons. Like the city name could be in uppercase or capitalized in your session variable.
Your session variable might not be initialized with your session in the class constructor.
Also you might even not have a class at all, so the reference to $this would be obsolete.
But those aside, here's a code that might help you:
<?php
class MockSession {
function __construct() {
}
}
class Foo {
function __construct() {
$this->session = new MockSession();
$this->session->city = "Helsinki";
}
function printSelect() {
$result = array("London","New York","Helsinki");
echo '<select>';
foreach ($result as $city) {
$sel = '';
echo $city." ".$this->session->city;
if (strtolower($city)==strtolower($this->session->city)) {
$sel = ' selected="selected" ';
}
echo '<option value="'.$city.'" '.$sel.'>'.$city.'</option>';
}
echo '</select>';
}
}
$foo = new Foo();
$foo->printSelect();
?>
If you got value of your session on the page then you have to just modify your code as selected="selected". See updated code:
<select>
<?php
foreach ($result as $city) {
?>
<option
value="<?php echo $city->city_name; ?>"
<?php if (strtolower($this->session->city) == strtolower($city->city_name)) {
echo 'selected="selected"';
}
?>>
<?php echo $city->city_name; ?>
</option>
<?php
}
?>
</select>
But you should have to confirm first that you got value of $this->session->city.

Only getting last record from mysql database

I am stuck on a code where I want to fetch data from MySQL into an array.. I have a form containing color and size select boxes, an onclick javascript function is triggered and it created two more select boxes like above, I have managed to get data into the javascript code where the code for creating new select boxes is written.
But I am only getting the last inserted record from both the tables. Although I have used a while loop.
Can someone help me out and I am also getting name of all select boxes likes name="color[]" , I want to insert records into a bridge table containing ids of color and size. below is my code please help ..
I will clear it up , each time I click add more button it should create 2 new dropdown lists, one for color and 2nd for size, both dropdowns should have the distinct data from database. so the ids for each record would be same in every dropdown list, I want to add more than 1 records in bridge table which contains product_id,color_id and size_id, so if I go for 3 dropwdown boxes , and i select blue color and small size in the first, then for second dropdown i again select blue color and size medium, as for the last dropdown which was also generated by the javascript function . i choose black color and large size. so from the dropdown it will get ids of size,color and it would be inserted accordingly.. so when i display the product and color blue is selected i would only see the sizes which were added to the color blue at the time of adding the product.. i hope this clears everything :)
$result=mysql_query("SELECT * FROM color,size");
while($row=mysql_fetch_array($result)) {
?>
<script>
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="label">Room ' + room + ':</div><div class="content"><span>Color: <select name="color[]"><option value="<?php echo $row['color_id']; ?>"><?php echo $row['color']; ?></option></select></span><span>Size: <select><option value="<?php echo $row['size_id']; ?>"><?php echo $row['size']; ?></option></select></span></div>';
objTo.appendChild(divtest)
}
</script>
<?php
}
HTML code
<div id="room_fileds">
<div>
<div class='label'></div>
<div class="content">
<input type="button" class="btn btn-success" id="more_fields" onclick="add_fields();" value="Add More" /> <br /><br />
<select name="color[]" class="form-control">
<option value="0">Select Color</option>
<?php
$result=mysql_query("SELECT * FROM color");
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['color_id'] ?>"><?php echo $row['color']; ?></option>
<?php } ?>
</select>
<select name="size[]" class="form-control">
<option value="0">Select Size</option>
<?php
$result=mysql_query("SELECT * FROM size");
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['size_id'] ?>"><?php echo $row['size']; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
Replace your first code with the following:
<script>
var colors = [];
var sizes = [];
var room = 1;
<?php
$result = mysql_query("SELECT * FROM color");
while ($row = mysql_fetch_array($result)) { ?>
colors.push(['<?php echo $row['color_id'] ?>', '<?php echo $row['color'] ?>']);
<?php }
$result = mysql_query("SELECT * FROM size");
while ($row = mysql_fetch_array($result)) { ?>
sizes.push(['<?php echo $row['size_id'] ?>', '<?php echo $row['size'] ?>']);
<?php } ?>
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds');
var divtest = document.createElement("div");
var html = '<div class="label">Room ' + room + ':</div><div class="content"><span>Color: <select name="color[]" class="form-control">';
for (i = 0; i < colors.length; i++) {
html += '<option value="' + colors[i][0] + '">' + colors[i][1] + '</option>';
}
html += '</select></span><span>Size: <select name="size[]" class="form-control">';
for (i = 0; i < sizes.length; i++) {
html += '<option value="' + sizes[i][0] + '">' + sizes[i][1] + '</option>';
}
html += '</select></span></div>';
divtest.innerHTML = html;
objTo.appendChild(divtest);
room++;
}
</script>
$divs='';
$result=mysql_query("SELECT * FROM color,size");
$room=1;
while($row=mysql_fetch_array($result)) {
$divs.='<div><div class="label">Room ' . $room . ':</div><div class="content"><span>Color: <select name="color[]"><option value="'.$row['color_id'].'">'.$row['color'].'</option></select></span><span>Size: <select><option value="'.$row['size_id'].'">'.$row['size'].'</option></select></span></div></div>';
$room++;
} ?>
<script>
function add_fields() {
var objTo = document.getElementById('room_fileds');
objTo.appendChild(<?php echo $divs; ?>);
}
</script>
Try this code hope it works for you
<script>
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds');
var divtest = document.createElement("div");
<?php
$div_start='<div class="label">Room '."'+ room +'".' :</div><div class="content">';
$color='<span>Color: <select name="color[]">';
$size='<span>Size: <select>'
$result=mysql_query("SELECT * FROM color,size");
while($row=mysql_fetch_array($result)) {
$color.='<option value="'.$row['color_id'].'">'.$row['color'].'</option>';
$size.='<option value="'.$row['size_id'].'">'.$row['size']'.</option>';
}
$color.='</select> </span>';
$size.='</select> </span>';
$div_close='</div>';
$innerHTML=$div_start.$color.$size.$div_close;
?>
divtest.innerHTML ='<?php echo $innerHTML; ?>';
objTo.appendChild(divtest);
}
</script>
This is the final code , it would help if anyone wants to code a similar thing.. just change values and it would work as per your need... and i would like to thank all people who replied to the thread and specially Mohammad Anini .. it wouldnt have been possible without his help !!!
$query = mysql_query("INSERT INTO products (product_name,product_description, product_pic1, product_pic2, product_pic3,product_price,category_id,subcategory_id,product_status,color,size,product_slug, meta_keywords,entrydate)
VALUES ('$product', '$description' , '$image', '$image2', '$image3', '$product_price', '$category', '$subcategory', '$product_status', '$capture_field_vals', '$size', '$product_slug1', '$meta_keywords', Now() )") or die(mysql_error());
if ($query === TRUE) {
$lastid = mysql_insert_id();
$color["color"]=array();
$size["size"]=array();
foreach ($_POST['color'] as $key => $colorvalue) {
}
foreach ($_POST['size'] as $key => $sizevalue) {
}
$cid=array();
foreach($color as $rec){
$cid[]=$rec;
}
$sz=array();
foreach($size as $rec){
$sz[]=$rec;
}
$length=sizeof($color);
for($i=0;$i<$length-1;$i++){
$query2 = mysql_query("INSERT INTO bridge (product_id,color_id, size_id)
VALUES ('$lastid', '$cid[$i]' , '$sz[$i]')") or die(mysql_error());
// echo "<script>alert('New Product successfully Addedd');windows.location.replace('addedit_product.php');</script>";
}

checking dynamically created textboxes for values

I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };

Categories

Resources