document.getElementById() as PHP SQL Query parameter - php

I have a question, is it possible to use the value stored in document.getElementById().value, getElementsByName().value, getElementsByClassName().value as a parameter for SQL Query via PHP?
Example.
I have this line <input type="text" class="myinput" id="myinput" name="myinput" value="999-AAA-000">
Then I'll store the data in this element.
<script>
function myFunction() {
var foroutput = document.getElementsByClassName("myinput");
}
</script>
Is there a way for document.getElementsByClassName("myinput"), or var foroutput to be used as a parameter for SQL Query via PHP?
SCENARIO: The SQL Query is within the same page as the document.getElementsByClassName("myinput"), will this work without using <form>?
This is my code
<input type="text" class="decid" id="decid" name="decid">
// the data passed into this input box will be used as a parameter for SQL Query $id
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
<?php
$id=$_POST['id'];
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
";
}
?>
</tbody>
</table>
A sample would be extremely great. Thank you.
EDIT:
Why won't this work?
<input type="text" class="decid" id="decid" name="decid">
<script type="text/javascript">
var abc = document.getElementById("decid").value;
<?php $abc = "<script>document.write(abc)</script>"?>
</script>
<?php echo $abc;?>

It looks as if you think <?php $abc = "<script>document.write(abc)</script>"?> might store the result of running JavaScript in a PHP variable. This is impossible. PHP runs on the server and builds the HTML to send to the client's browser. The JavaScript does not get run until it is received by the browser.
Server-side:
- PHP and MySQL can be run
- JavaScript cannot be run
Client-side:
- JavaScript can be run
- PHP cannot
In your example
<input type="text" class="decid" id="decid" name="decid">
<script type="text/javascript">
var abc = document.getElementById("decid").value;
<?php $abc = "<script>document.write(abc)</script>"?>
</script>
<?php echo $abc;?>
Is actually the same as
<input type="text" class="decid" id="decid" name="decid">
<script type="text/javascript">
var abc = document.getElementById("decid").value;
</script>
<script>document.write(abc)</script>
Because you stored a string with script tags in it inside of the variable $abc, and then echoed that variable back out a couple of lines later.
There are a few ways of getting JavaScript to communicate with the server.
1)
The old fashioned way is just to refresh the page with a query parameter that tells PHP what myinput is.
window.location.href = 'http://example.com/mypage?myinput=' + abc
And then in PHP you can get the input and use it in your SQL Query like so.
$abc = $_GET['myinput'] ?? false;
if ($abc){
...
}
2)
A better way is to use Ajax. Ajax allows you to send a request to the server for some data without having to refresh the entire page. If you're using jQuery then you can do this with the jQuery.get or jQuery.load functions. You would then have PHP return you your results which you would add to the page. There are a lot of tutorials out there on how to do this.
3)
If you're not using jQuery, then there are 2 additional options for sending requests to the server. If you don't care about supporting IE 11, then you can use the new Fetch API. The other option is to use the axios library which is a little bit easier to use, but requires installing a third party library. They are both pretty similar in their use.

Related

How to ajaxify a PHP function that does SQL in the backend?

I have broken down my problem to provide a concise example with no overhead.
Yet enough to give you an idea.
I have a simple index.php
<?php
include 'myClass.php';
?>
<html>
<head></head>
<body>
<div> <?php myClass->printTable(); ?> </div>
</body>
</html>
The function returns an entire table filled with data that is being prepared in the backend.
<?php
function printTable()
{
// printing static table header
echo ' <table class="table" style="zoom: 0.75;">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th> // current date
<th scope="col">Order Number</th> // an int
<th scope="col">Current Value</th> // an int
</tr>
</thead>
<tbody>
';
$result = mysqli_query($this->link, "SELECT * FROM `someData`");
while ($row = mysqli_fetch_assoc($result))
{
$orderNumber = $row['orderNumber'];
$currentValue = $row['currentValue'];
$date = $this->getDate($orderNumber); // member function that returns a timestamp from the database
//printing actual table
echo ' <tr>
<td>'. $date .'</td>
<td>'. $orderNumber .'</td>
<td>'. $currentValue .'</td>
</tr>
';
}
echo ' </tbody>
</table>
';
}
?>
The data I'm querying from my database is constantly changing. I want a "live" view on the frontend. I know this is done by using Ajax. But I don't understand how to do it. I looked up different resources, although none of them were actually specific enough in this approach.
On a high level: You need a PHP file ("endpoint", e.g. 'localhost/data.php') returning only the HTML code from printTable. You then use JavaScript (e.g. jQuery - $.ajax, you can lookup how it works in detail) to fetch the contents of this page each n seconds and insert into your page.
I was looking for broad or unspecific way to get some data from the backend and display it within a div on my page.
The solution was to create a separate PHP (fetch.php) file that echoes only the data I need to display within my div
from my page which contains my div I'd do the following:
<div id="result"></div>
<script>
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data()
</script>
Inside fetch.php I can do whatever I want, including querying my database and store the values in a variable which will be echoed at the end. This response (echo) from fetch.php will then be displayed inside my div.
Similarly, I could also specify a .txt inside the ajax function (url:"sometext.txt")
The contents of the .txt could also be displayed inside my div this way. My lack of understanding of how this works made it really difficult to understand.
Additionally, I have added a function to refresh the contents (or response) every second.
If I would echo time() from fetch.php it would automatically increment without page reload inside my div
setInterval(function(){
load_data()
}, 1000);

Hello i'm trying to do multiple sorting using php mysql where i'm searching and then sorting the data

i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);

No output in Autocomplete

I use autocomplete to achieve a Google like search where the search suggestions are in a dropdown while i type what i'm searching for.
The Output of my code
HTML
<td width="155" bgcolor="#999999">Client Name</td>
<td width="218" bgcolor="#999999"><input type="text" name="clientname" id="clientname" class="forinput" /></td>
script
<script type="text/javascript">
$(document).ready(function() {
$( "#clientname" ).autocomplete(
{
source:"getautocomplete.php",
minLength:1
})
});
</script>
getautocomplete.php
..databaseconnection
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT clientname FROM client WHERE clientname LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
What i want to achieve
I check my database connection and its correct. Can anybody explain to me what I'm doing wrong? did i missed something?
I don't think the result you are sending back is valid according to what jQueryUI is expecting.
Now you are building an array of arrays and you should only send the values back (assuming that the label and the value are the same, the name of the client):
// $row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = htmlentities(stripslashes($row['clientname'])); //build an array
Also note the comments about the deprecated mysql_* functions and sql injection.

How to use php and mysql functions inside javascripts

Here is my javascript code which is added in the tag of my php/html page:
<script type="text/javascript">
$(document).ready(function() {
$('#status').change(function(){
var status = $('#status').val();
var html = ''; //string variable for html code for fields
if( status=="closed"){
html += '<th>Close By :</th><td align="left"><select name="close_by">'+<?php $user=mysql_query("SELECT * FROM user");
while($data=mysql_fetch_array($user)){?>+'<option value="'+<?php echo $data['username'] ?>+'">'+<?php echo $data['username']; ?>+'</option>'+<?php } ?>+'</select></td>';
}
$('#close_by').html(html);
});
});
</script>
The code is for that, if Status=="closed" then a select tag will be appeared and the option values will be fetched from the database using mysql functions.But its not working. Please help to sort out this problem.
Thanks in advance.
You can't. PHP/MySQL reside on your server, while JS is executed in the browser.
Of course you may let the browser interact with your server by proper HTTP requests, after setting proper routes on your server.
You can mix PHP into Javascript. The PHP will execute on the server, and then the JS on the client. It's horrible though, extremely bad practice, and a nightmare to debug. Much better to seperate them out and use jQuery ajax to load the data.
Or use PHP to put the data into a JSON object at the start of the javascript, and process that with Javascript, rather than using PHP code to concatenate strings inside Javascript.
But in your example, what exactly is the problem? What is the end result of the PHP (in the HTML source) of the html variable? I suspect there's a bracket or quote wrong somewhere.
You can do it with ajax
$(document).ready(function() {
$('#status').change(function(){
var status = $('#status').val();
if( status=="closed"){
$.ajax({
url: 'ajax.php?',//if you have parameters
success:function (response) {
$('#close_by').html(response);
}
});
}
});
});
And you create a new php file for the ajax request
ajax.php
<th>Close By :</th>
<td align="left">
<select name="close_by">
<?php $user=mysql_query("SELECT * FROM user");
while($data=mysql_fetch_array($user)){?>
<option value="<?php echo $data['username'] ?>"><?php echo $data['username']; ?>
</option>
<?php } ?>
</select>
</td>

How do I show an error without refreshing the page?

I'm creating a registration form.
The user enters the username and password, and presses submit, and the form is submitted using POST.
HTML :
<link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" />
<form id="frmRegister" method="post" action="register.php">
<h1>Register</h1>
<table width="100%">
<tr>
<td width="16%"><label class="alignRight"> Username: </label></td>
<td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td>
</tr>
<tr>
<td width="16%"><label class="alignRight"> Password: </label></td>
<td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td>
</tr>
<tr>
<td width="16%"> </td>
<td width="84%"><input name="Submit" class="submitButton" type="submit" /></td>
</tr>
</table>
</form>
</html>
PHP:
$username = $_POST["txtUsername"];
$password = $_POST["txtPassword"];
//Code to connect to database
function doesUsernameExist($username)
{
//return true if username exists or false otherwise
}
Now, in PHP, I run a query to check if the username exists in the database.
If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank?
Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
I use jQuery to do something like this.
in the html
<input type="text" name="username" onBlur="checkUsername(this)">
in the javascript something like this
function checkUsername(v){
$.post("phppage.php",{
valToBeChecked:v
},function(d){
if($.trim(d)==true){
// php page returned true
}else{
// php page returned false
}
});
}
do note this is only an example, I think I got the syntax right tho.
This will do an AJAX check on blur of the input without jQuery.
Edit: I want to clarify that I don't suggest this approach, and much prefer the use of jQuery (or other similar JS framework) for AJAX. However, I understand that not everyone has the luxury of specifying the technologies they use, and so here's the answer to your request! :)
<input id="txtUsername" name="txtUsername" />
<script type="text/javascript">
window.onload = function() {
document.getElementById('txtUsername').onblur = function(e) {
// Get the username entered
var el = e.target;
var username = el.value;
// Create an XHR
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// AJAX call to the server
request.open('GET', '/check_username.php?username=' + username, false);
xhr.onload = function(e) {
var json = eval(xhr.responseText);
if (json.exists) {
window.alert('That username exists already.');
}
}
xhr.send();
}
}
</script>
user_exists.php
$username = isset($_GET['username']) ? $_GET['username'] : '';
$username = mysqli_real_escape_string($username);
$sql = "SELECT COUNT(*) > 0 AS user_found
FROM users
WHERE username = '{$username}'";
$result = mysqli_query($sql);
$exists = false;
if ($row = mysqli_fetch_assoc($result)) {
$exists = $row['user_found'] ? true : false;
}
echo json_encode(array('exists' => $exists));
My solution to this would be to utilize AJAX.
On submission of your form, make an AJAX call to a page that will evaluate the data that has been input into the form, and return information regarding whether or not it was validated.
After you get back some information from that AJAX call, determine whether or not to submit the form again, but this time to a page that will absorb the data into the database.
It's one solution; and as an AJAX newbie I'd say there are probably better ones, but it might work for you.
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You don't want to pass a blank value, this is where you would put your username and password to deliver to FILE2.php. In your case, the line would look like this:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 1;
This would deliver a 1 to the success function in FILE1.php, and it would be stored in the variable called "data". Therefore, the alert(data) line in the success function would alert the number one.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file returns a response (whatever you choose to send) and that appears in the Success: section of your AJAX call.
The jQuery/AJAX is JavaScript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document.

Categories