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
Related
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
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.
I've got a simple jQuery script that isn't behaving correctly. What am I doing wrong? The idea is that the user enters a value into a textbox and then clicks a button. The jQuery then uses POST to send the value to a PHP file. The PHP file then runs a simple SQL query and gives a response. jQuery .load is then used to refresh the div containing the original php.
Using Chrome's tools, I've noticed that the response for POST is perfect. However, it then gets overwritten by a GET with no data.
jQuery:
$("#GOtest").click(function() {
var customer = $("#customer").val();
if (customer == '') {
$('#alert_formula_save_failed').show();
}
else {
$.post("../assets/forms/formulations/set_session.php", {
customer: customer,
}, function(data) {
$('#alert_formula_save_success').show();
$('#dynamic').load('../assets/forms/formulations/set_session.php');
$('#alert_formula_save_failed').hide();
setTimeout(function() { $('#alert_formula_save_success').fadeOut('fast'); }, 3000);
});
}
});
PHP:
<?php
$customer = null;
$customer = 'Test' ;
$customer2 = $_POST['customer'] ;
.. db connection bits ;
try
{
$PDO = new PDO( "mysql:host=".$host.";"."dbname=".$dbname, $user, $pass);
}
catch(PDOException $e)
{
die($e->getMessage());
}
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM db_customers where customer = '$customer' ";
$stmt = $PDO->prepare($sql);
$stmt->execute(array($id));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$PDO = null;
$iscurrent = $data['iscurrent'];
echo '<br>' ;
echo 'Response 1-' ;
echo $iscurrent;
echo '<br>' ;
echo 'Response 2-' ;
echo $customer2 ;
?>
HTML:
<form id="testform" name="testform" method="POST">
<button type="button" name="GOtest" id="GOtest" class="btn btn-info">
<i class="fa fa-frown-o"></i>
SET SESSION
</button>
The idea being that 'response 1' just echoes a predefined value. Response 2 should just echo out whatever is typed into the text input box.. but the GET overwrites everything.
The "issue" is this line:
$('#dynamic').load('../assets/forms/formulations/set_session.php');
It uses GET by default.
Try using this in its place:
$('#dynamic').html(data);
I have an HTML form starting with an input field, where the user have the option to write a promo code to get some discount ....
What I am trying to do here. I need to create a keyup functionto check if the typed code is found in the MySql Promo Codes table.
If found, write something in the placeholder ...., else, write something else ....
Also if the form is submitted in need the PHP to write 'Yes' in the code corresponding MySql Used column...
<form id="form" class="form" name="RevitForm" action="form_revit_architecture_submitted" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
<div class="field" style="background-color:#f3f3f3;">
<span id="promo-msg" style="color:#093; position:relative; bottom:3px; font-style:italic; font-size:13px">[HTML is replaced when successful.]</span>
<center><input style="font-family:Lato; text-align:center; max-width:200px;" type="text" id="PromoCode" name="PromoCode" maxlength="5" size="15px" placeholder="Promo Code"></center>
</div>
//other input fields
</form>
<!-- Promotion Code Match -->
<script>
$("#PromoCode").keyup(function() {
if ($(this).val().length == 5) {
//post the code and check the it in the MySql table thru the PHP file "request.php"
//if code found {write something in $(#promo-msg) } else {do something else}
}
});
</script>
And in the PHP in need to excute something like
<?PHP
$code = ucwords($_POST['PromoCode']);
$con=mysqli_connect("localhost","x","y","academy_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
// if $code is found and the corresponding `Used` column does not == 'Yes' return as found
//else return as not found
?>
To do that, we need 2 files.
HTML, form + jQuery AJAX keyup event and check DB
PHP connect to DB to check the promo code
1.HTML
<html>
<head>
<title>Promo check</title>
<!-- load jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 10;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' is already used correct.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<input type='text' id='code'>
<div id='Promo_code_status'></div>
</body>
</html>
2.PHP: check_code.php
You will need to use your connection data ($host, $user, $pass, $dbdb) and maybe change the table & field names.
<?php
//connect to database
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select promoCode, used from testtable where promoCode = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
Do it like this:
"SELECT * FROM Promo Codes WHERE Code LIKE '$code' AND Used='yes' "
Also,To update parameter 'used':
UPDATE Promo Codes SET used='Yes' WHERE Code= '$code'
For the keyup function, you need to learn about AJAX requests. Since it's the medium for communicating with the server through the client
jQuery AJAX: http://api.jquery.com/jquery.ajax/
I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.