Making PhP code executes first before Javascript - php

<?PHP
//$errorMessage = "";
//$check = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//===================================================
// GET THE QUESTION AND ANSWERS FROM THE FORM
//===================================================
$sID = $_POST['studentID'];
$sID = htmlspecialchars($sID);
$firstName = $_POST['firstName'];
$firstName = htmlspecialchars($firstName);
$lastName = $_POST['lastName'];
$lastName = htmlspecialchars($lastName);
$grade = $_POST['grade'];
$grade = htmlspecialchars($grade);
//var_dump($grade);
//============================================
// OPEN A CONNECTION TO THE DATABASE
//============================================
$user_name = "root";
$password = "";
$database = "surveyTest";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
//============================================
// GET THE LAST QUESTION NUMBER
//============================================
$SQL = "Select * FROM students WHERE SID='$sID'";
$result = mysql_query($SQL);
$db_field = mysql_fetch_assoc($result);
$studentID = $db_field['SID'];
var_dump($studentID);
//=========================================================
// Add a student to the students TABLE
//=========================================================
$SQL = "INSERT INTO students (SID, fName, lName, Grade) VALUES ('$sID', '$firstName', '$lastName', '$grade')";
$result = mysql_query($SQL);
//=============================================================
// SET Multiple rows IN THE answers TABLE for each question for a given student.
//=============================================================
/*$SQL = "Select * FROM tblquestions";
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
for ($i = 1; $i <= $numRows; $i++){
$qNum = 'q1';
$SQL = "INSERT INTO answers (QID, A, B, C, D, E, SID) VALUES ('$qNum', 0, 0, 0, 0, 0, '$sID')";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
$result = mysql_query($SQL);
}*/
mysql_close($db_handle);
print "The student with the following ID ".$sID. " has been added to the database";
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
<html>
<head>
<title>Survey Admin Page</title>
</head>
<body>
<FORM NAME ="setQuestionForm" METHOD ="POST" ACTION ="setStudent.php" id="sStudent">
<p>Enter student ID: <INPUT TYPE = 'TEXT' Name ='studentID' size="4"></p>
<p>Enter First Name: <input type="text" name="firstName" size="20"></p>
<p>Enter Last Name: <input type="text" name="lastName" size="20"></p>
<p>Select Grade: <select name = "grade">
<option value = "1">First Grade</option>
<option value = "2">Second Grade</option>
<option value = "3">Third Grade</option>
<option value = "4">Fourth Grade</option>
<option value = "5">Fifth Grade</option>
<option value = "6">Sixth Grade</option>
<option value = "7">Seventh Grade</option>
<option value = "8">Eighth Grade</option>
</select></p>
<INPUT TYPE = "submit" Name = "Submit1" VALUE = "Add Student">
</FORM>
<P>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var check = "<?php echo $studentID; ?>";
alert(check);
if (check != "")
{
alert ("This user already exists");
return false;
}
else
{
return true;
}
});
}
})
</script>
</body>
</html>
The above code is used to add students to a database, and I'm trying to do some form validation to avoid duplicated records. My problem is that I set a php variable $studentID that verifies whether the database contain the a student with the same ID.
However, when I try to add a duplicated record, it seems like my javascript code executes first and this can be observed by the alert message in the JQuery code that it shows a box of an empty string. Executing the code once more, do the correct thing.
Any help of how I can fix this?

On initial page load:
The process flow looks like this:
Server Side code -> sends data to client -> browser begins rendering and executing JS
On form Submit:
Client Executes code (javascript) -> Sends data to server -> Server gets data and processes
to change the way this works you would want to do an ajax or post form submit and on "success" then execute the above JavaScript. You can post to the same page or change it to a RESTful service.
Here are examples of AJAX and POST functions from jQuery:
AJAX
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
POST (JS)
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
Here is the result specifically for you, taking the two snippets above.
JavaScript/jQuery
$(function () {
if ($('form').length > 0) {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "YOUR-URL",
data: YOUR - FORM - DATA,
success: function (result) {
//result will contain the xml or JSON result of calling the FORM
var check = "<?php echo $studentID; ?>";
alert(check);
if (check != "") {
alert("This user already exists");
return false;
} else {
return true;
}
},
dataType: "XML-OR-JSON"
});
});
}
})

Related

How to check whether a text variable is equal to an Array

My requirement is to check whether a text variable is equal or not to an mysql output array.
The mysql output array I have taken as follows,
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
Now I need to check whether user have entered any book from which included in above array.So I have implemented as below.
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$('#book_name').val()=$book_required;
if(in_array($book_required,$avail_books))
{
alert("Not Available");
}
else{
$.ajax({
url:"books.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
}
}
But this is not working. Can someone show where I have messed this?
There can be other ways to accomplish what you want.
For example, use the following query:
SELECT count(*) FROM takenbooks where book_name = ?
But for How to check whether a text variable is equal to an Array and based on your original code, the normal way will be to pass the user input data (I believe is $('#book_name').val()) thru ajax to a PHP file to check whether this data is in the array , then return the result back (or do further processing)
For the HTML
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<form id=insert_form>
<input type=text id="book_name">
<input type=submit>
</form>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: 'checkdata.php',
data: {data1: $('#book_name').val()},
success: function(data){
alert(data);
},
error: function(xhr, status, error){
console.error(xhr);
}
});
})
})
</script>
For the PHP (checkdata.php)
<?php
if (isset($_POST["data1"])){
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
if(in_array($_POST["data1"],$avail_books)) {
echo "Not Available";
} else {
// Place insert query here
echo "New Record inserted";
}
}
?>
You can first get the list of books once, then write a Javascript array from which to search for the entered book name. (This may not be practical if the list of books changes quite often, or the list is extremely long.)
<?php
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
$avail_books = [];
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
?>
<!DOCTYPE html>
<html>
<body>
<form id="insert_form">
Book name: <input type="text" name="book_name">
<input type="submit" value="Check for availability">
</form>
<div id="available"></div>
<script>
const avail_books = <?php json_encode($avail_books); ?>;
document.querySelector('#insert_form').addEventListener(function (evt) {
evt.preventDefault();
let book_name = evt.target.book_name.value;
let not_available = (-1 === avail_books.indexOf(book_name))? 'not': '';
document.querySelector('#available').innerHTML = book_name + " is " + not_available + " available.";
});
</script>
</body>
</html>
PHP, on the server, gets the books and stores the list in a PHP array. And when writing out HTML and Javascript use PHP to write out a Javascript avail_books array containing the book names retrieved from the database.
Now the server can send the client the HTML/Javascript code for rendering. Once loaded in the browser, and if you "View Source", the Javascript code will look something like this:
const avail_books = ["To Kill a Mockingbird", "Animal Farm", "Atlas Shrugged"];
With that the user can check the list of books without having to send a query to the server with every inquiry. It's faster and uses less resources.
It might have some Syntax error but thats the basic concept of what you are trying to achieve. Someones enters text, script searches the database and returns the results.
<html>
<body>
<form action="" method="POST">
<input type="text" name"book" required placeholder="Type the name of the Book" />
<input type="submit" value="Search Book" />
</form>
<div><h2>Results:</h2>
<?php
if(isset($_POST['book'] && !empty($_POST['book'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli("localhost", "root", "", "newbooks");
$stmt = $mysqli->prepare("SELECT ID, book_name FROM takenbooks WHERE book_name LIKE ? ORDER BY ID DESC;");
$stmt->bind_param("s", "%" + $_POST['book'] + "%");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<p>Book \"' . $row['book_name'] . '\" was found.<br/></p>';
}
}
?>
</div>
</body>
</html>

Getting value from database using jquery on change event

I have a list of rooms in a table along with their rent cost. Rooms are listed in a drop down menu, and I want to get rent in "input" field value, "on page load" as well as on "dropdown value change". I wrote following code, but somehow it is not working as expected. Can someone help me with this please?
<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");
$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
$dbValue = intval($_GET['dd']);
$ajax = true;
$res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
$dataTable = '';
while ($data = mysqli_fetch_assoc($res)) {
$dataTable = $data['rent'];
}
}
// if ($ajax) return $dataTable;
?>
<html>
<head>
<title>jQuery Validation for select option</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select class="form-control" id= "roomid" name="roomid" required="">
<?php
$troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
$troom_rs = mysqli_query($conn, $troom_sql);
while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
?>
<option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
<?php
} ?>
</select>
<input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>
<br>
</body>
<script>
$('#roomid').change(function()
{
var first = $('#roomid').val();
var req = $.get('getDB.php', {dd: first, action: 'ajax'});
req.done(function(data)
{
console.log("asdasd");
$('#rent').val("<?php echo $dataTable; ?>");
});
});
</script>
</html>
Though you've written both PHP and JS in the same file, you still need to return the data from PHP side and handle it in JS.
if ($ajax) return json_encode($dataTable)
from PHP side
dat = JSON.parse(data)
in JS
Crate a JQuery AJAX Function that takes the parameter for POST/GET Request and call that Ajax function on JQuery Event. The Ajax Function Should be like,
function LoadComponentPage( param ){
$.ajax({
type: "POST",
url: "./controller/ajax/component_paginate.php",
data: "page="+param,
dataType: "text",
success: function(resultData){
let section = $('#ComponentsListing');
section.empty();
section.html(resultData);
},
error : function(e){
console.log(e);
}
});
}
and call that function upon event as onclick="LoadComponentPage(param)". you can post process the result of call to show result or error something as shown in example function.

MySQLI how to insert a form into database by language select

Im having an issue with form method.
How can I insert a form value in the database in different table by language select.
I have in my database the tables called article_en / articles_ro ,and when I chose with select english I want the values to be inserted in the article_en
Also when I select the language its not staying selected.
And if I write something in the inputs and chose a language the inputs are being cleared.
PS:Im a newby , I am still learning.
This is the language select code
<?php
define("LANG",$_GET['lang']);
include('../db.php');
function select_langs(){
global $conn;
echo'<h2 class="box-title">Select the language where you want to the article</h2>
<select id="select_language">
<option selected disabled hidden value=""></option>';
$get_languages = mysqli_query($conn, "SELECT lang,title from `languages`") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($get_languages)){
if($row['title'] == $_GET['lang']){
echo'<option value="insert_article.php?lang='.$row['lang'].'" selected>'.$row['title'].'</option>';
}
else{
echo'<option value="insert_article.php?lang='.$row['lang'].'">'.$row['title'].'</option>';
}
}
echo'</select>';
}
?>
And this is the insert code.
<?php
include('./lang.php');
include('../db.php');
define("LANG",$_GET['lang']);
select_langs();
// extract data from form; store in variable
$title = $_GET['title'];
$link = $_GET['link'];
if (!empty($title) and !empty($link ) and !empty($_GET['lang'])) {
// Define the query to inser the song request
$sql = "INSERT INTO `articles_".LANG."`(title , link)VALUES (".$title.", ".$link.")";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#select_language").bind("change",function(){var n=$(this).val();return""!=n&&(window.location=n),!1});
</script>
<form action="insert_article.php" method="get">
<label id="first">title:</label><br/>
<input type="text" name="title"><br/>
<label id="first">link:</label><br/>
<input type="text" name="link"><br/>
<input type="submit" value="submit">
</form>
Thank You.
I think you need to use ajax to send the details to the php to insert it in your database. It's just easier.
var select_language= document.getElementById("select_language").value;
var title= document.getElementById("title").value;
var link= document.getElementById("link").value;
var data= {select_language: select_language,title: title,link:link};
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function(html)
{
console.log (html);
alert("Success");
},
error: function (html)
{
console.log (html);
alert("Failure");
}
});
insert.php
include '../dbconfig.php';
$select_language= mysqli_real_escape_string($db,$_POST['select_language']);
$title = mysqli_real_escape_string($db,$_POST['title']);
$link= mysqli_real_escape_string($db,$_POST['link']);
$query = "your insert query";
mysqli_query($db, $query) or die(mysqli_error($db));
Hope this helps.

Updating table values using dropdown without using a submit button

I'm trying to update the database using a dropdown list without using a submit button.
Here's my dropdown:
<td>
<label for=""></label>
<select style="font-family: Questrial;" name="status" required>
<option disabled selected hidden>Select Status</option>
<option value="In Progress">In Progress</option>
<option value="Closed: Cancelled">Closed: Cancelled</option>
<option value="Closed: Solved">Closed: Solved</option>
</select>
</td>
Here's the script:
<script>
$(document).ready(function() {
$('option[name="status"]').click(function() {
var status = $(this).val();
$.ajax({
url: "update2.php",
method: "POST",
data: {
status: status
},
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
And here's update2.php:
<?php
//Insert Data
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "INSERT INTO tickets(status) VALUES (:status)";
$statement = $conn->prepare($query);
$statement->execute(
array('status' => $_POST["status"])
);
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
Basically what I want to happen is to update the table values when I make a selection from the dropdown list.
Currently, nothing happens when I make a selection. (No page reload, No error message, just nothing)
Am I doing something wrong here?
Also here's my table schema:
table schema
You are targeting the wrong element
$('option[name="status"]') should be $('select[name="status"] option'
I suggest you to use id, they are more clear and faster.
In addition you will also be interested with the change event
https://api.jquery.com/change/
The selector should be select and the event should be change(). Try this :
$('select[name="status"]').change(function() {
instead of :
$('option[name="status"]').click(function() {
1) change $('option[name="status"]').click( to $('select[name="status"]').change(
the name "status" is an attribute of the select, not the options.
2) make sure you have an element with the id "result", or else the ajax success handler will not insert the received data/string anywhere.
These changes should make your code work.
I recommend adding an error handler to every ajax call you do. Also try to prevent your php files that are called by ajax methods to have cases where nothing is returned / echoed.
if(isset($_POST["status"]))
{
$query = "INSERT INTO tickets(status) VALUES (:status)";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
// ! add else statement
else
{
echo "unknown index: 'status'";
}
Also an interesting read about ajax error handling: setting response codes in PHP

Anyone know why I'm getting an undefined index error with PHP?

So, I'm new to using PHP but want to add whatever a user enters into this form into a database.
However, I'm getting an error for each index of name, role, and wage. It seems that it isn't picking that up.
HTML:
<form id="input" name="input" action="employees.php" method="post">
<div id="boxes">
<input type="text" name="name" placeholder="Input" class="name" required><br/>
<input type="text" name="role" placeholder="Role" class="role" required><br/>
<input type="number" step="any" name="wage" placeholder="Wage" class="wage" required>
<br />
<br />
</div>
<button type="submit" onsubmit="return ajaxFunction()" class="button">Submit</button>
<button type="reset" class="button">Reset</button>
</form>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employees";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br/>";
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
if (mysql_query("INSERT INTO employees VALUES ('$name2', '$role2', '$wage2')"))
echo "Successfully inserted";
else
echo "Insertion failed";
$conn->close();
?>
I also have some javascript set up to catch the values of each field and to send them to the PHP file. I'm probably doing something very wrong... but anyway here's the JS:
function ajaxFunction() {
var name = $('.name').val();
var role = $('.role').val();
var wage = $('.wage').val();
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
$.post('employees.php', {name1:name, role1:role, wage1:wage}, function(data){
$('#main').html(data);
});
if (name == '' || role == '' || wage == '') {
alert("Please fill in all fields.");
} else {
$.ajax({
type: "POST",
url: "employees.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
In your Ajax dataString is
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
But in your PHP
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
Should be
$name2 = $_POST['name1'];
$role2 = $_POST['role1'];
$wage2 = $_POST['wage1'];
The undefined error means that your data is not found, this is happening because your php is looking for a POST index of "name" whereas javascript is sending "name1".
There are a few issues with the setup that can be greatly improved here.
Firstly the onsubmit needs moved into the form tag.
<form onsubmit="return isFormValid()" id="input" name="input" action="employees.php" method="post">
Secondly you don't actually need to actually make an ajax request from Javascript because the return on submit is saying if the returned value of the js function is true submit the form otherwise don't. Therefore we just need to return a true or false based on form validation.
Here is the updated JS function.
function isFormValid(){
var name = $('.name').val(),
role = $('.role').val(),
wage = $('.wage').val(),
data = [name, role, wage],
isValid = true;
data.forEach(function(el){
if( isValid && !el.trim() ){
alert("Please fill in all fields.");
isValid = false;
}
});
return isValid;
}
There are also some security concerns regarding MySQL injection from how the form data is being entered into the database without being escaped.
A quick solution is to add a basic PHP method to escape the strings before hitting the database.
// add at the top of your php file
function escape($value){
return mysql_real_escape_string($value);
}
// then update your variables
$name2 = escape($_POST['name']);
$role2 = escape($_POST['role']);
$wage2 = escape($_POST['wage']);
You can read more about mysql injection and how to prevent it here:
http://php.net/manual/en/function.mysql-real-escape-string.php
EDIT ---------------------------
I've simplified the JS and removed the token issue you were having. If you add more input fields you can simply add a new variable to store it's value and add that variable name to the data array.
I've also updated the function name in both the JS and the html as it relates more to the purpose of the task.
Here is a working example:
http://codepen.io/davidbattersby/pen/LVabQe
obviously the php file doesn't exist so will point to a blank page if submission passes validation, it will alert and not send if invalid.

Categories