How to take textbox value in php if created by js - php

I am using following code to generate multiple textbox on label click, it works correctly and multiple textbox created with different name. I want to take the value of textbox at php side and run insert query for each textbox. But i don't know how to use it in php. Here is my code plz help.
<html>
<head>
<title>
</title>
<script>
var index = 1;
function insertRow(){
var table=document.getElementById("rep1");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
t1.name = "txtName"+index;
cell1.appendChild(t1);
index++;
}
</script>
</head>
<body>
<label id="btnAdd" style=" width: 10px;" class="button-add" onclick="insertRow();">add</label>
<table id="rep1">
</table>
</body>
</html>
SQL Schema :
T_no(AI) Text_value
PHP CODE:
<?php
if(isset($_POST["submit"]))
{
$t1=$_POST['name'];// i am confused here how to take value and run query for all
?>

Client side Code
You must use Array for multiple name field
<script>
var index = 1;
function insertRow(){
var table=document.getElementById("rep1");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
t1.name = "txtName[]"; //Use array of names not id
cell1.appendChild(t1);
index++;
}
</script>
Please check How to get form input array into PHP array
And You can fetch those array server side using $_POST['txtName']; or any other request method
Server side coding for inserting array into database
<?php
if(isset($_POST["submit"]))
{
$t2=$_POST['txtName'];
$query_parts = array();
$qu = "INSERT INTO try VALUES";
foreach($t2 as $val)
{
$query_parts[] = "('', '" . $val . "')";
}
$qu .= implode(',', $query_parts);
$res=mysqli_query($con,$qu);
if(!$res) { echo("Error description: " . mysqli_error($con)); }
}
?>
The above code will not prevent data from SQl injection.You can use prepared statement for prevent SQL injection in PHP. Link

Use this code. It will helps you.
<?php
print_r($_POST['txtName']); // Here you can get you all values.
?>
<html>
<head>
<title>
</title>
<script>
var index = 1;
function insertRow(){
var table=document.getElementById("rep1");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
t1.name = "txtName[]"; // Use array in textbox name..
cell1.appendChild(t1);
index++;
}
</script>
</head>
<body>
<form method="POST" action="" >
<label id="btnAdd" style=" width: 10px;" class="button-add" onclick="insertRow();">add</label>
<table id="rep1">
</table>
<input type="submit">
</form>
</body>
</html>

For this you have to store total index value also(that should specify how many time you created input field).After that your php code should be like below..
PHP CODE:
<?php
if(isset($_POST["submit"]))
{
$t1=$_POST['txtName'.$index];
?>
Where index variable will your current index value from your loop for length of total input fields

Related

create random number and store in database table

im try to store random number after click on button and store in database table field name 'f_id'. when i click on button, the new random number is generated but its not store in database table field name 'f_id'.. my code is..
my jquery code ////
<script language="javascript" type="text/javascript">
jQuery(document).ready(function($){
$(".random").click(function(){
var number =Math.floor(Math.random() * 100000);
console.log(number);
});
});
</script>
and my html code ////
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<a class="random action btn btn-success btn-sm" href="#" >random number</a>
</body>
</html>
plzz tell me i have created database already but not store this value number on database table..
php code...
<?php
function mytable($number){
$result = mysqli_query( $this->conn,"INSERT INTO school(f_id) VALUES ('$number')");
return $result;
}
?>
mytable($number);
how to connect jquery var number in php code mytable under variable number... plzz solved
You need to call your PHP function using ajax (https://api.jquery.com/jquery.post/) and send your random number.
You can then access it via $_POST['number'] on the server side.
$.post( "mytable.php", function({number: number}) {
});
Php:
function mytable($number)
$result = mysqli_query( $this->conn,"INSERT INTO school(f_id) VALUES ('$number')");
return $result;
}
mytable($_POST['number']);
You need to call your php backend script. This could be done like this:
<script language="javascript" type="text/javascript">
jQuery(document).ready(function($){
$(".random").click(function(){
var number =Math.floor(Math.random() * 100000);
console.log(number);
window.location.href='http://path.to/your_script.php?rnd=' + number
});
});
</script>
And in your_script.php:
<?php
function mytable($number){
$number=intval($number);
$result = mysqli_query( $this->conn,"INSERT INTO school(f_id) VALUES ('$number')");
return $result;
}
if(mytable($_GET['rnd'])) {
echo "It works";
}
else echo "Something went wrong";
I but putting a random number as id is "probably not" recommended...

need help on php with javascript

I need help on some update like function:
<html>
$result = mysql_query("SELECT *FROM tbl_a LEFT JOIN tbl_b lass ON tbl_b.b_id=a.class_id LEFT JOIN category ON category.category_id=tbl_a.category_id WHERE list ='{$id}'"); </br>
while($row = mysql_fetch_array($result)){
$id_list = $row['id'];
$name = $row['name'];
....
}
}
echo "<script type='text/javascript'>
var id = document.getElementById('list').value = '.$id_list;'
var name = document.getElementById('fname').value ='.$name;'
</script> ";
</html>
my problem is that i can retrieve data but it not displaying on my input elements it should be like an update function
Quotes, quotes...
echo
"<script type='text/javascript'>
var id = '".$id_list."',
name = '".$name."';
document.getElementById('list').value = id;
document.getElementById('fname').value = name;
</script> ";
Working example: http://codepad.viper-7.com/3eI3Od
You need to call your input elements and then give them the new values instead of setting variables like you are doing. Remove the "var something =" and just do document.get.......
If what you posted is the complete code, then there is no list and fname elements. Better open the page and view the source code to see if you have the right value written into your Javascript.
NOTE:
Remember that if you put your Javascript after the element HTML, Javascript cannot retrieve the element. For example:
<script>
document.getElementById('test').value = 'Hello World';
</script>
<input type='text' id='test' value=''>
As you can see, it does not assign value to test element. Solution,
<input type='text' id='test' value=''>
<script>
document.getElementById('test').value = 'Hello World';
</script>
Put the input before the Javascript.

get sql query displayed rather than query result using AJAX

Hello I have been trying to figure out why my code aimed at listing a query result in a table does not work. I took code found on the web and tired to adapt it. My data is stored in pgsql. The html page has a drop down menu that allows selecting an institution name. When I click the submit button to know who belongs to this institution in my database, the php page is loaded and displays the SQL query I want to send to pgsql. I should get the result of the query displayed in a table displayed on the html page instead. The drop down menu works correctly so I do not provide the php code for this one (listinstitutions.php)
A person told me I should use ajaxsubmit() but I do not know where to put this function.
There may be an error in the php file also since the query is displayed rather than being sent to pgsql. Is the json correctly sent?
Your guidance would be very much appreciated.
Thank you.
The html side:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
//////////////////////////////////////
// Displays insitution names in Drop Down Menu
//Getting the selector and running the code when clicked
$('#selinstit').click(function(e){
//Getting the JSON object, after it arrives the code inside
//function(dataI) is run, dataI is the recieved object
$.getJSON('http://localhost/listinstitutions.php',function(dataI){
//loop row by row in the json, key is an index and val the row
var items = []; //array
$.each(dataI, function(key, val) {
//add institution name to <option>
items.push('<option>' + val['Iname'] + '</option>');
});//end each
//concatenate all html
htmlStr=items.join('');
console.log(htmlStr);
//append code
$('option#in').after(htmlStr);
});//end getJSON
});//end cluck
///////////////////////////////
// Displays persons form an institution in a table
$( "$subinst" ).button().click(function( event ) {
console.log($(this)); // for Firebug
$.getJSON('http://localhost/SelectPersonsBasedOnInstitution.php',function(data){ // I make an AJAX call here
console.log($(this)[0].url); // for Firebug check what url I get here
//loop row by row in the json, key is an index and val the row
var items = []; //array
$.each(data, function(key, val) {
//add table rows
items.push('<tr border=1><td>' + val['Pfirstname'] + '</td><td>' + val['Plastname'] + '</td><td><a mailto:=" ' + val['Pemail'] + ' " >' + val['Pemail'] + '</a></td></tr>');
});//end each
//concatenate all html
htmlStr=items.join('');
//append code
$('#instito').after(htmlStr);
});//end getJSON
event.preventDefault();
});
}); //end ready
</script>
</head>
<body>
<form id="myForm" action="SelectPersonsBasedOnInstitution.php" method="post">
Select persons from an institution:
<br>
<tr>
<td>
<select id="selinstit" name="instit">
<option id="in">Select</option>
</select>
</td>
<td>
<input type="submit" id="subinst" value="Submit" />
</td>
</tr>
</form>
<table frame="border" id="instito">
</table>
</body>
</html>
Here is the php code for SelectPersonsBasedOnInstitution.php
<?php
//////////
// part 1: get information from the html form
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
foreach ($_REQUEST as $key => $value){
$$key=$value;
}
// part2: prepare SQL query from input
$sqlquery= sprintf('SELECT "Pfirstname", "Plastname", "Pemail" FROM "PERSON"
LEFT JOIN "INSTITUTION" ON
"PERSON"."Pinstitution"="INSTITUTION"."Iinstitution"
WHERE "Iname" = \'%s\'',$instit);
echo $sqlquery;
/////////
// part3: send query
$dbh = pg_connect("host=localhost dbname=mydb user=**** password=*****");
$sql= $sqlquery;
$result = pg_query($dbh,$sql);
$myarray = pg_fetch_all($result);
$jsontext = json_encode($myarray);
echo($jsontext);
?>
The following line is likely to be the problem (it shouldn't be there):
echo $sqlquery;
Rewrite your code without that line and it should work.
$sqlquery= sprintf('SELECT "Pfirstname", "Plastname", "Pemail" FROM "PERSON" LEFT JOIN "INSTITUTION" ON "PERSON"."Pinstitution"="INSTITUTION"."Iinstitution" WHERE "Iname" = \'%s\'', $instit);
$dbh = pg_connect("host=localhost dbname=mydb user=**** password=*****");
$result = pg_query($dbh, $sqlquery);
$myarray = pg_fetch_all($result);
$jsontext = json_encode($myarray);
echo($jsontext);

Can I create values with PHP and expected them to be readable by JS?

I'm making a site for myself, and I'm trying to implement some javascript for instant calculations, but I'm having some issues:
Is there any way I can avoid typing
level_prices["3"]=3;
level_prices["4"]=4;
... etc. up to 90: in other words, is there any way I can do like I did in the PHP code and make it create this value until 90, which looks a lot cleaner?
Why is this returning $Undefined? I suspect that it's not getting the value from the HTML form, but the code looks correct ...
Here is my code:
relevant HTML/PHP:
<form action="" id="priceCalcForm" onsubmit="return false;">
<table class="table">
<tbody>
<tr> <!-- first row, with css -->
<td style="width:50%;">
<select name="fromlevel" id="fromlevel" onchange="calculateTotal()" style="width:100%; text-align:center; font-weight:bold;">
<option value="none" name="none">0</option>
<?php
$i = 1;
while ($i < 91) {
echo '
<option value=' . $i . ' name=' . $i . '>' . $i . '</option>';
$i++;
}
?>
</select>
</td>
</tr>
</tbody>
</table>
</form>
Included JS:
var level_prices= new Array();
level_prices["None"]=0;
level_prices["1"]=1;
level_prices["2"]=2;
function getLevelPrice()
{
var levelSetPrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["priceCalcForm"];
//Get a reference to the select id="filling"
var selectedLevel = theForm.elements["fromlevel"];
//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
levelSetPrice = level_prices[selectedLevel.value];
//finally we return cakeFillingPrice
return levelSetPrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var LevelPrice = getLevelPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Leveling $"+LevelPrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display='none';
}
I consider myself decent with PHP, but its first time I am using JS.
1) use a loop:
var level_prices = {}; // object literal not array!
level_prices['none'] = 0;
for(var i = 1; i <= 90; i++ ) {
level_prices[i] = i;
}
the first to lines could also be written like this (already define the none-property):
var level_prices = {'none': 0};
2) level_prices is not an array it is an object-literal (see part 1 of my answer)
see a working fiddle here: http://jsfiddle.net/BkGxq/
(also notice that i deleteted the inline onchange handler from your markup and put it to the javascript (at the bottom)
Yes. Any variable in PHP (except Resource-type variables) can be dumped directly into JavaScript with json_encode.

How to insert PHP values into Javascript?

Javascript:
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option><option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
PHP/HTML:
<script type = "text/javascript" src="js/addinput.js"></script>
<form name="form1" method="POST" action="services.php" onsubmit="return valid()">
<br><br><br><center>
<table class="form" border=1>
<tr>
<td class="head" colspan="2" >Select Vehicle:</td>
</tr>
<tr ></tr>
<tr>
<td colspan="2" class="info">
<div id="dynamicInput">
<br><select name = "vehicle[]" id = "vehicle1">
<option value = "">Vehicle 1</option>';
include_once "vehicledbconnect.php";
$queryveh = mysql_query("SELECT * FROM vehicletbl");
while($fetch_2 = mysql_fetch_array($queryveh)) {
$brand = $fetch_2['vehbrand'];
$name = $fetch_2['vehname'];
echo '<option value = "'.$brand.' '.$name.'">'.$brand.' '.$name.'</option>';
}
echo '</select>';
echo '<input type="button" value="Add another vehicle" onClick="addInput(\'dynamicInput\');"></div>';
Hi. Is it possible to insert PHP values in a javascript? I have a program here that if the customer click the submit button (echo '), a new drop-down form will appear. And I want the drop down form to contain all of the values of the query ($queryveh = mysql_query("SELECT * FROM vehicletbl");). In my default drop-down form, all values of the query are shown. Please help me guys. I am desperate for an answer. Javascript is my weakness. Thanks a lot.
edit:
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option>" + "<?php include 'vehicledbconnect.php'; $queryveh = mysql_query('SELECT * FROM vehicletbl'); while($fetch_2 = mysql_fetch_array($queryveh)) { $brand = $fetch_2['vehbrand']; $name = $fetch_2['vehname']; <option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option> }?>";
Can this be the solution? I've tried but it's not working, if this can be the solution, maybe there's only something wrong with my code here.
The only way to retrieve values from a server from javascript is to use AJAX.
Well you can do it without AJAX if you don't mind a page refresh, but I don't think that is what you want.
I would use a jQuery load function. This is the simplest example I can muster up for you.
You will need to download jQuery (http://docs.jquery.com/Downloading_jQuery) and include it in your html header:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Then you can make a simple function to call; either as a onclick or onchange depending on your preference.
function reloadDropDown()
{
document.getElementById('dynamicInput').innerHTML = 'Loading ...';
var v_name = document.formname.elementname.value;
$('#dynamicInput').load("dropdownload.php", { vehicle_name : v_name });
}
Let me go through this. dropdownload.php would have your '$queryveh' made drop down code. Javascript basically plonks whatever happens in dropdownload.php on to a div with the id 'dynamicInput' When javascript loads dropdownload.php it sends via POST a variable by the name vehicle_name which you can use as $_POST['vehicle_name'] within dropdownload.php.
So, dropdownload.php may look something like this.
<?php
$queryveh = mysql_query("SELECT * FROM vehicletbl WHERE vehname = '{$_POST['vehicle_name']}'");
// collect the data and put it in to an Array I like to do this so I can check the array to make sure it has something in it if not return an error message but I will skip that for the purpose of this explanation.
while($ucRow = mysql_fetch_array($queryveh, MYSQL_ASSOC)) array_push($resultsArray, $ucRow);
?>
<select name = "vehicle[]" id = "vehicle1">
<?php
foreach ($resultsArray as $fetch_row){
?>
<option value = "<?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname'].'; ?>"><?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname']; ?></option>
<?php } ?>
</select>
?>
I'm not entirely certain on the end result you are after but that is a basic jQuery ajax call. If you can grasp that, you are half way to a truly dynamic web page / app with some further practice with this area. Hope that gives you a direction to go in :)
JavaScript gets evaluated on the client ..so like Html ..so it is to be used the same way.
-> yes, you just use php in your javascript as long as its defined to be evaluated by php first (usually within a .php file)
edit:
just to clarify, if you want to get values within javascript from the server by php.. you need to have a look at what danishgoel said: Ajax (Asynchronous JavaScript) ..see - since Rikudo Sennin disrespected the link, another http://en.wikipedia.org/wiki/XMLHttpRequest ..or even better have a look at a javascript framework that does most of the stuff for you (f.e. jQuery)

Categories