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.
Related
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>
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.
Im trying to clone a div's content with jquery. After it is cloned i am sending it to a php page to be processed with Jquery Ajax. The php page saves it to a mysql database table. Then i need to retrieve it from the table on a different page and load it in another div. The mysql table cell is a blob that i save this html too. When i retrieve the table it echo's [object Object]. So i not usre if i am sending it to the save_invoice.php correctly or im not saving it to database correctly or last im not retrieving it correctly.
Html div: invoice.php
<div id="invoice_content">
<table>
<tr><td>Html Example</td></tr>
</table>
</div>
Jquery Code:
$(document).on('click', "#clone", function () {
var printContents = $("#invoice_content").clone(true, true);
//var $data = 'invoice=' + escape(printContents);
var $data = $(printContents).serialize();
$.ajax({ url: "functions/insert_html.php",
type: "POST",
dataType:"html",
data:$data,
success:function(obj){
alert(obj);
}
});
});
php: save_invoice.php
if (isset($_POST['invoice'])) {
$html = $_POST['invoice'];
$sql = "INSERT INTO `html table` (html)
VALUES ('" . mysql_real_escape_string($html) . "')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
php: view_invoice.php
if(isset($_GET)){
$id = $_GET['id'];
$sql = "SELECT html FROM `html table` WHERE id = '".$id."'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$html_id = $row["html"];
}
mysqli_close($conn);
}
<div id="invoice_content">
<?php echo $html_id; ?>
</div>
<?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"
});
});
}
})
So basically I have a intranet for a business where the employees can login and do various tasks. In order to inprove efficency I have implemented what I am calling the "QuickTask" feature where the employees can select a task via a drop down menubefore they log in so it can go straight to it. Due to there being various departments, I have made a script where the employees can type in their username and press the submit button it populates the list of tasks relevant to their department, this is only temporary as the submit button needs to be used to actually login. However, I would like to change this so the list would populate as they type their username. How could I do this?
I have 3 files.
1. index.php (Log in page)
2. quickTask.js (jQuery function)
3. determine_department.php (The file quickTask.js is communicating with)
Here is the code:
index.php:
<form action="javascript:void(0);" method="post">
Username: <input type="text" id="username" name="username" /><br />
Password: <input type="password" name="password" /><br />
<i>QuickTask:</i><div id="quickTask"></div>
<br />
Forgot Password?<br />
<input class="test" type="submit" id="thing" value="Log In" />
</form>
quickTask.js
$(document).ready(function() {
$('input#thing').on('click', function() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('../inc/determine_department.php', {
username: username
}, function(data) {
$('div#quickTask').html(data);
});
}
});
});
determine_department.php:
<?php
$username = $_POST['username'];
if(isset($username) === true && empty($username) === false) {
mysql_connect("localhost", "root", "24Bottlesofgin24");
mysql_select_db("intranet");
$sql = "SELECT DEPARTMENT FROM `employees` WHERE USERNAME='$username'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$depID = $row['DEPARTMENT'];
}
$sql2 = "SELECT * FROM `quicktask` WHERE DEP_ID='$depID'";
$result2 = mysql_query($sql2);
echo "<select name=\"QT\">";
echo "<option value=\"\" selected=\"selected\" disabled>-- Please Pick One --</option>";
while($row2 = mysql_fetch_array($result2)){
echo "<option value=\"" . $row2['DEP_ID'] . "\">" . $row2['TASK'] . "</option>";
}
echo "</select>";
}
?>
Here is a live example:
Here is what you want, converted from How to delay the .keyup() handler until the user stops typing? to your needs. It will run the query if/when the user stops typing for 200 ms, the time is set by the second parameter to delay, you can have it for any amount of time you like. However, I am really with those who suggest using an autofill plugin - why reinvent the wheel?
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function() {
$('input#username').on('keyup', function() {
delay(function(){
var username = $('input#username').val();
if($.trim(username) != '') {
$.post('../inc/determine_department.php', {username: username}, function(data){
$('div#quickTask').html(data);
});
}
},200)
});
});
$('input#username').on('keyup', function() {...});
but better be sure to only run a single ajax request at a time.
Change
$('input#thing').on('click', function() {
to
$('input#username').on('keyup', function() {
Should do it, you want the keyup event on the #username input instead of the click event of #thing
Basically, the click function will still them same. You just need to affect it to the keyup event of your username input :
$('#username').keyup( function() {
var username = $('input#username').val();
if($.trim(username) != '') {
$.post('../inc/determine_department.php', {username: username}, function(data){
$('div#quickTask').html(data);
});
}
});
javascript:
$('input#thing').keyup(function()
mysql:
$sql = "SELECT * FROM `quicktask` WHERE DEP_ID IN (SELECT DEPARTMENT FROM `employees` WHERE USERNAME like '".$username."%')";
$result = mysql_query($sql);
echo "<select name=\"QT\">";
echo "<option value=\"\" selected=\"selected\" disabled>-- Please Pick One --</option>";
while($row = mysql_fetch_array($result)){
echo "<option value=\"" . $row['DEP_ID'] . "\">" . $row['TASK'] . "</option>";
}
echo "</select>";