Radio/Checkboxes not saving to db - php

I have this form in a foreach loop, so it shows multiple times on the same page.
Everything submits fine in each form EXCEPT the radio buttons and checkboxes. They don't save the values to the db.
EDIT: I've narrowed it down to the ajax causing the error but can't figure out how to correct it.
<form action="process.php" method="post" name="editInvoice'.$invoice_id.'" id="editInvoiceForm'.$invoice_id.'" class="editInvoiceForm edit_invoice_container" enctype="multipart/form-data">
<div class="form_item_row">
<input type="radio" value="Unsent" '.$unsent.' name="status"/><span class="choice">Unsent</span>
<input type="radio" value="Sent" '.$sent.' name="status"/><span class="choice">Sent</span>
<input type="radio" value="Paid" '.$paid.' name="status"/><span class="choice">Paid</span>
</div>
<div class="form_item_row">
<label for="include_timelog'.$invoice_id.'">Include Time Log</label>
<input type="checkbox" value="true" '.$include_timelog.' name="include_timelog" id="include_timelog'.$invoice_id.'" />
</div>
<div class="clear"></div>
<div class="form_item_row_btns">
<input type="hidden" value="'.$invoice_id.'" name="hiddenInvoiceID"/>
<input type="submit" class="btn" value="Update Invoice" name="action"/>
</div>
</form>
$query = "UPDATE invoices SET status = ".$db->prep($_POST['status']).", include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);
$(document).ready(function()
{
var action = '';
$(".due_date").datepicker();
$('input[name=action]').click(function(){
action = $(this).val();
});
$(".editInvoiceForm").submit(function() {
$('.editInvoiceForm .form_message').html('<img src="images/loadingAnimation.gif" alt="loadingAnimation" width="30" height="8"/>');
var dataToSend = {};
$(this).find(':input').each(function (i,el) {
dataToSend[el.name] = $(el).val();
});
dataToSend.action = action;
$.ajax({
type: "POST",
url: "process.php",
data: dataToSend,
dataType: "json",
cache: false,
success: function(data){
//console.log(data.status);
if(data.status == 'error'){
$('.editInvoiceForm .form_message').removeClass('status_green').addClass('status_red').html(data.message).append(data.script);
}else{
$('.editInvoiceForm .form_message').removeClass('status_red').addClass('status_green').html(data.message).append(data.script);
}
}
});
return false;
});
});

You need quotes around the value for status in your SQL since the value is a string. Your include_timelog and invoice_id values are integers and do not need quotes.
$query = "UPDATE invoices SET status = '".$db->prep($_POST['status'])."', include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);

Related

How to Send Text and Image File Data at The Same Time to MySQL Database Without Refreshing The Page

I don't know how to send text, checkbox, radio data and also image file at the same time using ajax jquery post (in order not to refresh the page).
Here are the codes I have.
index.php
<form action="save.php" method="POST">
Your Name : <input type="text" name="username" id="username">
<BR>
Your Sex :
<input type="radio" class="get_gender" name="gender" id="genderM" value="Male">Male
<input type="radio" class="get_gender" name="gender" id="genderF" value="Female">Female
<BR>
Your Hobbies :
<input type="checkbox" class="get_hobby" name="basket" id="basket" value="Basketball">Basketball
<input type="checkbox" class="get_hobby" name="foot" id="foot" value="Football">Football
<input type="checkbox" class="get_hobby" name="volley" id="volley" value="Volleyball">Volleyball
<BR>
Your Grade :
<select name="grade" id="grade">
<option value="1>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<BR>
Upload Photo : <input type="file" name="image" id="image">
<BR>
<input type="button" name="save" id="save" value="Save" onclick="save()">
</form>
save.php
<?php
include "connection.php";
$usename = $_POST['username'];
$gender = $_POST['gender'];
$hobby = $_POST['hobby'];
$grade = $_POST['grade'];
$photo = $_FILES['image']['name'];
$sql = "insert into user
(username, gender, hobby, grade, photo)
values('$username','$gender','$hobby','$grade','$photo')";
$query = mysqli_query($con,$sql);
header("location: index.php");
?>
index.js
function save(){
var username = document.getElementById("username").value;
var grade = document.getElementById("grade").value;
var hobby = [];
$('.get_hobby').each(function(){
if($(this).is(":checked"))
{
hobby.push($(this).val());
}
});
hobby = hobby.toString();
var gender = [];
$('.get_gender').each(function(){
if($(this).is(":checked"))
{
gender.push($(this).val());
}
});
gender = gender.toString();
$.ajax({
type: "POST",
url: 'save.php',
data: {
username: username,
hobby: hobby,
hobby: hobby,
grade: grade
},
success: function(result){
}
});
}
Please help
You can simplify your save function - and send both form data and an image at the same time by using a FormData object:
function save_data() {
var formData = new FormData($('#userform')[0]);
$.ajax({
url: '/test13.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
alert(response);
}
});
}
Note you need a couple of other changes. The form needs an id attribute e.g.
<form id="userform">
You should change the name attributes of the hobbies to hobby[] i.e.
<input type="checkbox" class="get_hobby" name="hobby[]" id="basket" value="Basketball">Basketball
<input type="checkbox" class="get_hobby" name="hobby[]" id="foot" value="Football">Football
<input type="checkbox" class="get_hobby" name="hobby[]" id="volley" value="Volleyball">Volleyball
And you need to add
processData: false,
contentType: false,
To your ajax object.
In your PHP code, you would need to assemble $hobby from the raw form values:
$hobby = implode(',', $_POST['hobby']);
and you should include a check for $_POST['gender'] being set:
$gender = $_POST['gender'] ?? '';
I needed to change the name of your function as save was causing conflicts. I renamed it to save_data. You may not find this is an issue.

Populating form fields in ajax

I am trying to populate my form fields with AJAX when a request is being made. I was able to successfully made the request and fetched data, but the issue I am facing is that the input fields are not being populated.
If I populate the return data into a div it will display but not displaying in a form fields.
My HTML code
<form id="fm" method="post" novalidate>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="descr" id="descr" multiline="true" data-options="label:'Description:'" style="width:100%;">
</div>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="unit" id="unti" style="width:100%" data-options="label:'Unit:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="rate" id="rate" style="width:100%" data-options="label:'Rate:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="fixing" id="fixing" style="width:100%" data-options="label:'Fixing:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="quantity" id="quantity" style="width:100%" data-options="label:'Quantity:'">
</div>
</form>
jQuery Code
function load_click(param)
{
var resp = $("#loadstatus");
$.ajax({
type: "POST",
url: "boqs/load.php",
data: {},
dataType: 'json',
beforeSend: function(){
resp.html(' <img src="../assets/img/rot_small.gif" />');
},
success: function (data) {
if (Array.isArray(data) && data.length) {
for (var i = 0; i < data.length; i++) {
//for each value in the json response
$(".descr").val(data[i].descr);
$(".unit").val(data[i].unit);
$(".rate").val(data[i].rate);
$(".fixing").val(data[i].fixing);
$(".quantity").val(data[i].quantity);
//alert(data[i].descr);
} // for
resp.html('');
}
});
}
PHP source code
$sql = "SELECT * FROM bill_preparation ORDER BY id DESC LIMIT 1";
$ret2 = $db->query($sql);
$json_resp = array();
while($row = $ret2->fetchArray(SQLITE3_ASSOC)){
$json_array['descr'] = $row['descr'];
$json_array['unit'] = $row['unit'];
$json_array['rate'] = $row['rate'];
$json_array['fixing'] = $row['fixing'];
$json_array['quantity'] = $row['quantity'];
//$json_array['amount'] = $row['amount'];
array_push($json_resp, $json_array);
}
//$result["rows"] = $items;
echo json_encode($json_resp, true);
Thanks to very one for your support. #Patrick suggestion pointed me to the right direction.
I discovered using $(".descr").val(data[i].descr); doesn't work in easyui form so I used $(".descr").textbox('setValue',data[i].descr); which worked.
I hope this help someone working with easyui.

AJAX POST - infrequent XHR Failed loading - data missing in PHP post

Likely a duplicate in theme/name, but no previous solutions will work either because I'm missing something or there is something else going on.
The form - seemingly at random - fails (not altering data in any field, just the defaults set in html) and when it does succeed the PHP file logs only two of the values, the second one and the fourth (both pure numbers/ints). The two it doesn't echo are 1: a text field and 3: a float.
This is the result the .php picks up -
Connected
'' + '8080' + '' + '1'
Here is the .html and .js, what on earth am I missing here?
<form id="form_0" name="form_0" method="post" action="">
<input type="text" id="coinname" name="coinname" value="litecoin"><br>
<input type="number" id="coins" name="coins" value="8080"><br>
<input type="number" id="cost" name="cost" value="0.0808"><br>
<input type="number" id="show" name="show" value="1"><br>
<input type="submit" id="submit" name="submit" value="Save">
</form>
<script>
$("#form_0").submit(function() {
var selectedcoin = $("#coinname").val();
var coins = $("#coins").val();
var buyprice = $("#cost").val();
var show = $("#show").val();
$.ajax({
type: "POST",
url: "write-database.php",
data: "selectedcoin=" + selectedcoin + "&coins=" + coins + "&buyprice=" + buyprice + "&show=" + show,
success: function(data) {
alert(data);
}
});
});
</script>
and here is the .php
<?php
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo "Connected <br>";
}
$selectedcoin=$_POST['selectedcoin'];
$coins=$_POST['coins'];
$buyprice=$_POST['buyprice'];
$show=$_POST['show'];
$sql= mysqli_query($conn,"INSERT INTO coin_price (coin_name, coin, price, display) VALUES ('".$selectedcoin."','".$coins."','".$buyprice."','".$show."')");
echo "'$selectedcoin' + '$coins' + '$buyprice' + '$show'";
mysqli_close($con);
?>
Just use serialize method to get all data from form values, as inputs names in $_POST global variable.
<form id="form_0" name="form_0" method="post" action="">
<input type="text" id="coinname" name="coinname" value="litecoin"><br>
<input type="number" id="coins" name="coins" value="8080"><br>
<input type="number" id="cost" name="cost" val="0.0808"><br>
<input type="number" id="show" name="show" value="1"><br>
<input type="submit" id="submit" name="submit" value="Save">
</form>
<script>
$("#form_0").submit(function() {
e.preventDefault();
$.ajax({
type: "POST",
url: "write-database.php",
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<?php
$selectedcoin=$_POST['coinname'];
$coins=$_POST['coins'];
$buyprice=$_POST['cost'];
$show=$_POST['show'];
$sql= mysqli_query($conn,"INSERT INTO coin_price (coin_name, coin, price, display) VALUES ('".$selectedcoin."','".$coins."','".$buyprice."','".$show."')");
echo "'$selectedcoin' + '$coins' + '$buyprice' + '$show'";
?>
I hadn't disabled the default submit behaviour that refreshes the page...
$("#form_0").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "write-database.php",
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});

Ajax stopped working after executing a query

I am trying to load comments from a php file using ajax.
index.php
<div id="commentsonpost" value="<?php echo $_GET['post'];?>">
</div>
<script type="text/javascript">
$(document).ready(function() {
var postid = $('#commentsonpost').attr("value");
alert(postid);
var dataString = 'getpostcomm=1&postid='+ postid;
$.ajax({
type: "get",
url: "getcomments.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
alert("re");
$("#commentsonpost").append(html);
}
});
return false;
});
</script>
getcomments.php
if(isset($_GET['getpostcomm'])){
$var=$_GET['postid']; // Adding this line causing problems
$querycomm = "select U.fname,U.lname,U.usernick,C.bcommentid,C.comment,C.date,C.visible from blogcomments as C natural join users as U where C.visible=1 and U.visible=1 and C.bpostid='{$var}' ORDER BY C.date ASC";
$resultcomm = mysql_query ( $querycomm, $connection );
echo "<div id='pcomments'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$_POST['post'].'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
}
Whenever i add that $var=$_GET['postid']; line in getcomments.php ajax script stop working. As soon as i remove $var=$_GET['postid']; from getcomments.php, excluding query part(obviously) form is displaying correctly.
Any ideas?
At ajax better set data fields as array values as:
$.ajax({
type: "get",
url: "getcomments.php",
data: {'getpostcomm':1,'postid':postid},
And at your PHP you have to sanitize your Id.. (if its int you may at least cast (int) )...
$var = (int) $_GET['postid'];
Also at your PHP add check if isset($_GET['postid'])...
if(isset($_GET['getpostcomm']) && isset($_GET['postid'])){
var dataString = 'getpostcomm=1&postid='+ toString(postid);

Get the textbox Text using ajax on button click

I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});​
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});​
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()

Categories