How to get inputs value using javascript - javascript

My script fetchs and insert some data from db and displays to the user then I decied to slightly change my code and add some functionality.For example what if any of textbox is empty so that I have added a java script file that controls this sitituation.Bu I cant get the value of textboxes values from index .php file
this is index.php file
<?php
$records = array();
$db = new mysqli("localhost", "root", "", "app");
if (!empty($_POST)) {
$first = $_POST["first"];
$last = $_POST["last"];
$bio = $_POST["bio"];
$insert = $db->prepare("Insert into people (first,last,bio,created) values(?,?,?,NOW())");
$insert->bind_param("sss", $first, $last, $bio);
if ($insert->execute()) {
header("location: index.php");
}
}
if ($result = $db->query("select * from people")) {
if ($result->num_rows) {
while ($row = $result->fetch_object()) {
$records[] = $row;
}
$result->free();
}
} else {
$db->error;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="sites.js"></script>
<title>Title</title>
</head>
<body>
<?php
if (!count($records)) {
echo "no";
} else {
?>
<table>
<tr>
<td>First</td>
<td>Last</td>
<td>Bio</td>
<td>Created</td>
</tr>
<?php
foreach ($records as $r) {
?>
<tr>
<td><?php echo $r->first; ?></td>
<td><?php echo $r->last; ?></td>
<td><?php echo $r->bio; ?></td>
<td><?php echo $r->created; ?></td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
and this is the html markup
<form action="" method="post">
First <input type="text" id="first"><br>
last <input type="text" id="last"><br>
Bio <input type="text" id="bio"><br>
<button id="submit" value="click me!!"></button>
</form>
</body>
</html>
I am trying to get inputs values from index file like this below But it doesnt work this way It returns object
$(document).ready(function () {
$('#submit').click(function () {
var name=$('#last');
alert(name);
});
});
thank in advance

When selecting an element with
$('#last')
you are getting the entire element in return. With that, you can use the val() method to retrieve the elements value:
var name = $('#last').val();

This will not return the value of name field:
var name=$('#last');
You can use like:
var name=$('#last').val();
Also note that, you are missing the name attribute in input fields. Without name attribute you can't get the value in $_POST.

You are referring to the object so you will get the object.
var name=$('#last');
If you need the value you have to ask for it:
var name=$('#last').val();

Related

Refresh sub php page onchange

I'd like to get an interactive block in my page that onchange of one of the 3 search fields only reloads the div 'mydata' and reruns the query with a new filter. I know it probably can be done with ajax but i'm stuck in finding the right piece of code.
Here's my testcode
Main php file users2.php:
<head>
<title>Test</title>
<script src="../jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="../jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script>
$.ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?id=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<?PHP
include '../conf/config.inc.php';
include 'users_functions2.php';
?>
</body>
And here the include file users_functions2.php:
<?php
echo "<div id='mydata'>";
echo "<table><tr><th>ID</th><th>Name</th><th>City</th></tr>";
echo "<tr>";
echo "<td><input type=text placeholder='search' name=search_id</td>";
echo "<td><input type=text placeholder='search' name=search_name</td>";
echo "<td><input type=text placeholder='search' name=search_city</td>";
echo "</tr>";
$sql="select id, name, city from users;";
if (isset($_GET['search_name'])) { $sql .= "WHERE vo_name LIKE \"%".$_GET['search_name']."%\""; }
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
echo "<tr><td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['city']."</td></tr>";
}
echo "</table>";
echo "</div>";
?>
Hope Chris is ok with this, i'd like my question being answered with a working example:
File 1:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?search_name=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th><th>Name</th><th>City</th>
</tr>
<tr>
<th><input type=text placeholder='search' name=search_id></th>
<th><input type=text placeholder='search' id='search_name' name=search_name></th>
<th><input type=text placeholder='search' name=search_city></th>
</tr>
</thead>
<tbody id="mydata">
<?PHP
include 'users_functions2.php';
?>
</tbody>
</table>
</div>
</body>
File 2:
<?php
include '../conf/config.inc.php';
$sql="SELECT id, `name`, city FROM users";
$search_name = filter_input(INPUT_GET, 'search_name');
if ($search_name) {
$sql .= " WHERE vo_name LIKE \"%$search_name%\"";
}
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
extract($row);
echo "<tr><td>$id</td><td>$name</td><td>$city</td></tr>";
}
?>

Updating html table with new php variable

I am trying to refresh my table when the user clicks the button. This is because when the user clicks the button that row will be moved to the next table. (Not in this code example to make it simpler). How the tables are created are with the php code which executes in index code.php. Indexcode.php creates the variable $waiting which is then fetched in index.php and used to populate the table. When the button is clicked a request is sent to indexcode.php which updates the mysql tables. This is why I want to refresh the tables to display the new updated information. I have tried quite a few ways but to no avail.
index.php
<html>
<style>
<?php include 'table.css'; ?>
</style>
<?php include 'indexcode.php'; ?>
<script src="js/jquery.js"></script>
<script>
function orderPacked(val) {
$.ajax({
type: "POST",
url: 'indexcode.php',
data: "packed=" + val,
success: function(){
var container = document.getElementById("yourDiv");
var content = container.innerHTML;
container.innerHTML= content;
}
});
}
</script>
<h1> <center> Warehouse </center></h1>
<p><center>This is for warehouse use</center></p>
<body>
<h2 class="text-waiting">These orders need to be packed</h2>
<body>
<table id="wtable" class="waiting-table" cellpadding="11"><tr>.
<th>Order ID</th><th>Customer</th><th>Vendor</th><th>Address</th>.
<th>Cart_ID</th><th>Cart</th><th>Checked</th></tr>
<?php while($row = mysqli_fetch_row($waiting)){
?>
<tr>
<?php
echo '<td>',$row[0],'</td>';
echo '<td>',$row[1],'</td>';
echo '<td>',$row[3],'</td>';
echo '<td>',$row[7],'</td>';
echo '<td>',$row[2],'</td>';
echo '<td>',"items",'</td>';
?>
<td>
<button onclick="orderPacked('<?php echo $row[0]; ?>')" id="button"
name="packed" >Packed</button>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
indexcode.php
...
$stmt = $conn->prepare("SELECT * FROM sale WHERE wh_state =
'waiting'");
$stmt->execute();
$waiting = $stmt->get_result();
$stmt = $conn->prepare("SELECT * FROM sale WHERE wh_state = 'packed'");
$stmt->execute();
$packed = $stmt->get_result();
$stmt->close();
// define variables and set to empty values
$orderErr = "";
$order = "";
if (empty($_POST["packed"])) {
$orderErr = "Error";
else {
$orderp = test_input($_POST["packed"]);
// update the state of the sale
$stmt = $conn->prepare("UPDATE sale SET wh_state = 'packed' WHERE id = '{$orderp}'");
$stmt->execute();
$waiting = $stmt->get_result();
$stmt->close();
}
}
...
when creating table in php.make a id for every row.
get the result from ajax response(update row).so you can update the row dynamically with the id with updated data with javascript.
`
<?php
echo "<tr id='id_".$row[0]."'>";
echo '<td>',$row[0],'</td>';
echo '<td>',$row[1],'</td>';
echo '<td>',$row[3],'</td>';
echo '<td>',$row[7],'</td>';
echo '<td>',$row[2],'</td>';
echo '<td>',"items",'</td>';
?>
<td>
<button onclick="orderPacked('<?php echo $row[0]; ?>')" id="button_<?php
echo $row[0]; ?> "
name="packed" >Packed</button>
</td>
</tr>
<?php } ?>`
and also make sure to use unique id's for html elements.

Updating SQL data without refreshing page

I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!
<?php
SESSION_START();
$output = NULL;
if(isset($_POST['btn_checkTelefon'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$fornavnoutput_Database = $rows['Fornavn'];
$etternavnoutput_Database = $rows['Etternavn'];
}
echo '<script type = "text/javascript">';
echo 'function sayHi() {';
echo 'val1 = document.getElementById("telefon_Input").value;';
echo 'if(val1 == "") {';
echo ' alert("Vennligst skriv inn ditt telefon nummer!");';
echo '}';
echo 'if(val1 !== "") { ';
echo ' document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
echo ' document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
echo '}';
echo '}';
echo '</script>';
} else {
$output = "No results";
}
}
$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
</script>
<script type = "text/javascript"></script>
<title></title>
</head>
<body>
<?php
include 'connectdb.php';
?>
<form name="form1" action="">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
if(isset($_POST["radios"])){
echo $_POST["radios"];
} else {
//header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
</form>
<?php echo $output; ?>
</body>
You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.
Please never mix JavaScript with php.
Use it in separate file.
Edit: So have you fixed it yet?
The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.
I will give a proper example how to code.
Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.
$(function() {
$('a').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).attr('href');
$('body').load(URL, 'form');
})
})
php example
prefered showsomethingfunction in separate file like showfunctions.php
function myLinks() {
echo "<a href='index.php?action=showsomething'>showsomething</a>"
}
index.php + included showfunctions.php
<?php
myLinks();
if(isset($_GET["action"]){
// do your ordinary thing like open connection with database.
switch($_GET["action"]))
{
case "showsomething":
//show showsomething() function with html
break;
//further you can add more action instead of showsomething if you have several links
}
//close database.
}
?>
You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.
Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.
You have to use jQuery $.post() for that.
first You have to create php file which will process Your data.
For example lets create file query.php with the following content:
<?php
if(isset($_POST['telefon_Search'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
$row = $resultSet->fetch_assoc();
echo json_encode($row);
}
}
next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
var user = $.parseJSON(data);
$('#check_Fornavn').val(user.Fornavn);
$('#check_Etternavn').val(user.Etternavn);
});
});
and complete html will looks like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title></title>
</head>
<body>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
$('#check_Fornavn').val(data.Fornavn);
$('#check_Etternavn').val(data.Etternavn);
});
});
</script>
</body>
</html>

PHP - pass hidden value into the jquery

<html>
<head>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
</script>
</head>
<body>
<?php
//db connection
$query = "SELECT *
FROM department
ORDER BY dept_ID ASC";
$result = mysqli_query($dbc, $query);
$total_department = mysqli_num_rows($result);
if($total_department > 0)
{
?>
<table width="600" border="1" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
<tr>
<td width="80" align="center">ID</td>
<td width="300" align="center">Department</td>
<td width="220" align="center">Action</td>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button class="buttonsPromptConfirmDeleteDepartment">Delete</button>
<input type="hidden" id="departmentID" value="<?php echo $row['dept_ID']; ?>" />
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
department table
dept_ID dept_name
1 Account
2 Finance
3 Marketing
Assume that my department table only have 3 records.
My requirement is the following:
- Click 1st delete button, show department ID = 1
- Click 2nd delete button, show department ID = 2
- Click 3rd delete button, show department ID = 3
However from my code, I can't meet my requirement. The department ID output that I get is 1 no matter what button I clicked.
Can someone help me?
No need to use a hidden input, you could just use the button tag instead:
<?php while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button type="submit" name="departmentID" class="buttonsPromptConfirmDeleteDepartment" value="<?php echo $row['dept_ID']; ?>">Delete</button>
</td>
</tr>
<?php } ?>
Of course, in the PHP script that does the form processing, access the POST index like you normally would:
$id = $_POST['departmentID'];
// some processes next to it
Note: Don't forget the <form> tag.
Additional Note: Don't forget to use prepared statements:
$sql = 'DELETE FROM department WHERE dept_ID = ?';
$stmt = $dbc->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
// some idea, use error checking when necessary
// $dbc->error
Change
id="departmentID"
to
class="departmentID" and
Change
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
to
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $(this).next('input.departmentID').val();
alert(departmentID);
});
});
first of all dept_id in while loop and you are using same id for all dept..
another thing you can get dept_id upon button click using jquery.. like this
$('.buttonsPromptConfirmDeleteDepartment').click(function(){
dept_id = $(this).next('input').val();
})

How to update an array table dynamically with ajax and jquery?

I have two files php (gettable.php and index.php) the index file display the result obtained by gettable.php every one seond, I want update the content of my table dynamically in the index (only new or changed value must be changed) using ajax, I am beginner in ajax.
Help me please
thank you
gettable.php
//
//
// I load data from the server(xml file)
$xml = simplexml_load_string($result);
foreach($xml as $node)
{
$name = "";
$value = -1;
foreach($node->attributes() as $a => $b) {
if($a == "name")
{
$name = (string)$b;
}
else if($a == "value")
{
$value = (string)$b;
}
}
$vars[$name] = $value;
}
?>
<table border="1">
<tr>
<th>id</th>
<th>abc</th>
<th>def</th>
</tr>
<tr>
<td><?php
echo "<p>x: ".$vars["x"]."</p>";
?>
</td>
<td><?php
echo "<p>y: ".$vars["y"]."</p>";
?>
</td>
<td><?php
echo "<p>z: ".$vars[z"]."</p>";
?>
</td>
</tr>
</table>
file index.php
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script language="JavaScript">
$('#data').load("gettable.php");
setInterval( "SANAjax();", 1000 );
$(function() {
SANAjax = function(){
$('#data').load("gettable.php");
}
});
</script>
</head>
<body>
<div id="data">
<?php include_once('gettable.php'); ?>
</div>
</body>
The script code should like this
$(function(){
function loadData(){
$('#data').load("gettable.php");
}
setInterval(function() { loadData(); }, 1000 );
});

Categories