Updating table values using dropdown without using a submit button - php

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

Related

How to update more then one database column

I was following one guy's tutorial on how to update database with ajax but I had some other intentions, he wanted to make a new row each time he updates his form, where I wanted to update an existing row. I Successfully updated the code to my needs but I want to update more then one column in that same row.
My form has 2 values, Show Announcement and Announcement Content where In text field I update Show Announcement to either 0 or 1 (true, false) and in Announcement Content to some text I want.
Now, the problem is that when trying to add && isset($_POST['anncontent']) && $_POST['anncontent']!='' in if statement in line 19 (marked where it is) and adding another SET option in $sql (SET announcement=('".addslashes($_POST['anncontent'])."')), it gives me status code 500 and neither of these 2 content updates in a database.
.submit.php
<?php
$host = "localhost";
$database = "";
$username = "";
$password = "";
try
{
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$response = array('success' => false);
LINE 19 ---> if(isset($_POST['name']) && $_POST['name']!='' && isset($_POST['anncontent']) && $_POST['anncontent']!='' )
{
$sql = "UPDATE settings SET ann=('".addslashes($_POST['name'])."') AND SET announcement=('".addslashes($_POST['anncontent'])."')";
//$sql = "UPDATE settings SET announcement=('".addslashes($_POST['anncontent'])."')";
if($conn->query($sql))
{
$response['success'] = true;
}
}
echo json_encode($response);
?>
index.php
<form action="" method="post">
<div> Show Announcement <input type="text" name="name" value="" /></div>
<div> Announcement Content<input type="text" name="anncontent" value="" /></div>
<div><button type="button" onclick="submitForm();" name="save_announcement" value="Save"/>Update</button></div>
</form>
</body>
<script type="text/javascript">
function submitForm()
{
var name = $('input[name=name]').val();
var anncontent = $('input[name=anncontent]').val();
if(name != '')
{
var formData = {name: name, anncontent: anncontent};
$('#message').html('<span style="color: red">Updating...</span>');
$.ajax({url: "https://localhost/admin/api/submit.php", type: 'POST', data: formData, success: function(response)
{
var res = JSON.parse(response);
console.log(res);
if(res.success == true)
$('#message').html('<span style="color: green">Successfuly updated.</span>');
else
$('#message').html('<span style="color: red">Error while updating.</span>')
}
});
}
else
{
$('#message').html('<span style="color: red">Please fill all the fields</span>');
}
}
</script>
Maybe the problem is in my sql call? I am not sure if that's the right way to update 2 columns in the same line.
I tried adding additional $sql call with only SET announcement but that didn't work. Same error code.
When I try to write something only in Show Announcement text field and press Update, I get #Error While updating# message (The one I set for if success = false) but when I try to set some content in another text field as well, I get a message "Updating..." and I get stuck on that.
https://prnt.sc/_MexIxx6dSdJ
Please, let me know if I need to provide more information for this case for you to understand the problem.
I would advice using !empty() "not empty", which does both checks for you.
Except that, you can bind 2 parameters doing something like:
if (!empty($_POST['name']) && !empty($_POST['announcement'])) {
$stmt= $pdo->prepare("UPDATE settings SET name = :name, announcement = :announcement");
$stmt->execute([
'name' => $_POST['name'],
'announcement' => $_POST['announcement']
]);}
Here is more about PDO

Dynamic combobox doesn't update

I'm trying to make a combobox that when another combobox is changed it will dynamically update with information from a database. I'm finding a lot of solutions that do not seem to work with what I have and am lost on what to do next.
I've tried simplifying the code to figure out what part does not work, there are so many different versions of the code I tried I just know that some of the one I have right now works and some of it does not.
EDIT: better code (I hope)
Database connexion (root/config/config.php)
<?php
define("DB_HOST", "10.172.16.4");
define("DB_USER", "test2_user");
define("DB_PASS", "password");
define("DB_NAME", "test2");
$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
$options = [PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $error) {
echo "Connection error: " . $error->getMessage();
die();
}
?>
Header (root/online/templates/header.php)
<!DOCTYPE HTML>
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
</head>
<body>
The form (root/online/create.php)
<?php
require_once "templates/header.php";
require_once "../config/config.php";
?>
<form method="post" action="">
<label for="choose_type">Type</label>
<select name="choose_type_modele" id="choose_type" onchange="selectMarque()" required>
<option value="">Select Type</option>
<?php
$sql = "SELECT id, name FROM typeMateriel";
if($stmt = $pdo->prepare($sql)) {
if($stmt->execute()){
$typeMateriel = $stmt->fetchAll();
}
}
foreach($typeMateriel as $foundType){
$typeMateriel_id = $foundType['id'];
$typeMateriel_name = $foundType['name'];
?>
<option value="<?= $typeMateriel_id; ?>"><?= $typeMateriel_name; ?></option>
<?php } ?>
</select>
<label for="choose_marque">Marque</label>
<select name="choose_marque_modele" id="choose_marque" required>
<option value="">Select type first</option>
</select>
</form>
<p id="test"></p>
<?php require_once "templates/footer.php"; ?>
The function (root/online/js/javascript.php)
function selectMarque() {
var typeID = $('#choose_type').val();
var post_id = 'id='+ typeID;
document.getElementById("test").innerHTML = "You Selected " + typeID;
if(typeID){
$.ajax({
type:'POST',
url:'../ajax_marque.php',
data:post_id,
success:function(marque){
$('#choose_marque').html(marque);
}
});
}else{
document.getElementById("choose_marque").innerHTML = '<option value="">Select type first</option>';
}
};
the code for the dynamic stuff (root/online/ajax_marque.php)
<?php
include('../config/config.php');
if($_POST['id']){
$id=$_POST['id'];
if($id===0){
echo "<option>N/A</option>";
} else {
$sql = "SELECT marqueMateriel.id,marqueMateriel.name FROM type_marque, marqueMateriel WHERE marqueMateriel.id=type_marque.marqueMateriel_id AND type_marque.typeMateriel_id= :typeMateriel_id";
if($stmt = $pdo->prepare($sql)) {
$stmt->bindParam(':typeMateriel_id', $id, PDO::PARAM_INT);
if($stmt->execute()){
$marqueMateriel = $stmt->fetchAll();
}
}
echo "<option>Select Marque</option>";
foreach($marqueMateriel as $foundMarque) {
$marqueMateriel_id = $foundMarque['id'];
$marqueMateriel_name = $foundMarque['name'];
echo "<option value='<?php $marqueMateriel_id; ?>'><?php $marqueMateriel_name; ?></option>";
}
}
}
?>
Closing up (root/online/template/Footer.php)
</body>
</html>
The first combo box works, and that's pretty much it. Nothing changes and I'm sure I'm missing something somewhere. I can use the function to alert(typeID) and it does so , but not change the data :/
EDIT : Trying to make more sense ?
The combo box "choose_type_modele" works, it contains everything from the table "typeMateriel". When I select something it does not change the second box "choose_marque_modele". The onchange function is called, as the "test" is modified on selection with the appropriate ID. The code in "ajax_marque.php" works if I copy it inside "create.php" and manually tell it what "$id" is, but it won't do it automatically. I feel the problem is the $.ajax part of the code inside "javascript.js" but I cannot seem to figure out what part is wrong.
Any help would be greatly appreciated.
I don't think if you can add options to a select with html method. You have to create option objects to add select object. To archieve this, you'll change response of your ajax method to JSON object.
var selectMarque = function() {
// Remove current options from matque
$('#choose_marque').find("option").remove();
var typeID = $('#choose_type').val();
var post_id = 'id=' + typeID;
// There will be always value in post_id
// You have to check typeID to be sure if type picked
if (typeID) {
// sample ajax data
var testData = [{
"value": "1",
"text": "Option 1"
},
{
"value": "2",
"text": "Option 2"
},
];
// for each option data in testData
$.each(testData, function(offset, optionData) {
// append an option to select
$('#choose_marque').append($('<option>', {
value: optionData.value,
text: optionData.text
}));
});
} else {
// if empty value picked as type
// add sample option to marque
$('#choose_marque').append($('<option>', {
value: "",
text: "Select Type To Fill"
}));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="choose_type_modele" id="choose_type" onchange="selectMarque()" required>
<option value="">Select Type</option>
<option value="1">Fill Select</option>
</select>
<select id="choose_marque" required>
<option value="">Select Type To Fill</option>
</select>
I had two errors in my code that made it impossible to work, the url and success parts of the ajax code.
Working code :
$.ajax({
type:'POST',
url:'ajax_marque.php',
data:post_id,
success:function(data){
$('#choose_marque').html(data);
}
});
For some reason I had "marque" instead of data (I might have changed it thinking it was something else ? ) and the url was "../ajax_marque.php". I thought I had to add the url from wherever the javascript.php file was, not from where it was called (create.php).

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.

ajax error handling / show error if mysql result is false?

I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.

Making PhP code executes first before Javascript

<?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"
});
});
}
})

Categories