POST form with JQuery using $.post() - php

I have the following form
<form id="colorTest" method="POST">
<input type="text" id='responseText' name="responseText" value="">
<input type="button" id='confirm' name="confirm" value="confirm">
<input type='text' id="idNum" name="idNum">
<input type='text' id='correct' id="correct">
</form>
Only the value for #responseText is actually typed in, #idNum is passed from another page, while the other fields are filled by this function:
<script type="text/javascript">
var arr = [2,5,6,7,10,16,29,42,57];
x = 0
/* idNum is passed from another page to this one */
$(document).ready(function() {
document.getElementById('idNum').value = localStorage.memberID;
/* when something is typed in the form */
$('#responseText').on('input', function() {
/* the value is stored */
var response = document.getElementById('responseText').value;
/* and compared with the vector arr that contains the correct answers*/
if( response == arr[x]){
$("#correct").attr('value', 'yes');
}else{
$("#correct").attr('value', 'no');
};
});
/* confirm is the button to send the asnwer */
$('#confirm').click(function(){
$.post("testColor.php", $("#colorTest").serialize());
x = x + 1;
});
});
</script>
And here is my php:
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$response = $_POST["responseText"];
$memberID = $_POST["idNum"];
$timeStmp = time();
$correct = $_POST["correct"];
$sql = "INSERT INTO colorBlind (memberID, response, correct, timeStmp)
VALUES ('$memberID', '$response' ,'".$correct."','".$timeStmp."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn -> close();
?>
Now, I am sure the php is called correctly when the click event occurs on #confirm, because the timestamp invoked in the php is recorded in my db. Nevertheless, none of the value in the fields is passed in the php. Namely if do somethin like:
echo $_POST["idNum"];
I get back an empty field.
Anybody has any idea what I am doing wrong or any suggestions on how to debug it? I have been spending days on this without any progress.

The first thing I noticed is that your
<input type='text' id='correct' id="correct">
contains id="correct" twice. I'm sure you meant to add name="correct".
When you use $("#colorTest").serialize(), that will return
responseText=foo&idNum=bar&correct=foobar
I can see how this would be used for a GET request. But seeing as you're using $.post(), you'll want to pass in an object of key/value pairs for your POST data.
For example, this should work:
var params = {
responseText: 'foo',
idNum: 'bar',
correct: 'foobar'
};
$.post("testColor.php", params);

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

Checkbox insert in mysql and check if checked

After i searched for this solution on this site, nothing i found. Here is basic php code, just for testing.
index.php
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data)
{
//alert(data);
window.location.reload();
}
});
});
});
</script>
qry.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if($_REQUEST['chk'] == true){
$stok = '1';
}
elseif ($_REQUEST['chk'] == false) {
$stok = '0';
}
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
How to set checkbox checked true or false into mysql and then echo if in html? It's always set to 0 in mysql boolen.
<input type="hidden" name="chk" id="chk" value="1" <?php if ($checked == '1') {echo 'checked';} else {} ?>/>
I tried everything from this site and nothing works.
Try this Jquery. This will get rid of the always value 1 problem you're having. What this code does is when you click on the "submit" button it check the status of your check box. If the check box is checked then the code will take the checked check box value and send that in the ajax function if it's not checked then the value 0 get assigned and that will be sent using the ajax.
Doing this will reduce the work has to be done by the back end PHP. I also made some changes to your PHP code as well.
$(document).ready(function() {
$(document).on('click', '#submit', function() {
if ($("#chk").is(":checked")) {
var chk = $('#chk').val();
}else{
chk = 0;
}
$.ajax({
url: "qry.php",
method: "POST",
data: {
check: chk
},
success: function(data) {
//alert(data);
window.location.reload();
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
You will see that the way I'm inserting the data is a bit different from the way you have done. I'm using mysqli_ prepared statements which makes SQL injection a hard to do.
$query = $connect -> prepare("INSERT INTO test(checked) VALUES (?)";
$query -> bind_param("i", $_REQUEST['check']);
if ($query -> execute()) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
jsFiddle if you want to test it.
You write the value into check, but read it back from $_REQUEST['chk']. That won't work. Change that to $_REQUEST['check'].
You are using val() to get the state of the checkbox, you should use checked.
Also, you are possibly open to SQL injection, start using prepared statements.
Add another line while sending the AJAX request.
While sending the value of checkbox, send 1 or 0.
It will reduce our work at PHP end.
So, the code should be:
var check = $('#chk').is(":checked");
check = (check) ? 1 : 0;
Final code should be:
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
check = (check) ? 1 : 0;
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data) {
//alert(data);
window.location.reload();
}
});
});
});
</script>
And PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$stok = $_REQUEST['chk'];
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
}
else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>

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.

jQuery GET overwiting POST

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);

Validate promo code from MySql table and mark as "used" when form is submitted

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/

Categories