I'm relatively new to PHP and need some help checking to see 1. If an image has been uploaded for submission and complete one set of submission ELSE IF an image has not been uploaded, submit a different set of sql information.
I've previously tried isset(), is_uploaded_file(), and file_exists(), and cannot seem to get anything to send.
HTML FORM
<form method="POST" action="php/editInv.php" enctype="multipart/form-data" id="editInv">
<table>
<tbody>
<?php
$productId = $_GET['productId'];
require ('php/dbcon.php');
$con=mysqli_connect(HOST,USER,PASS,DB);
$sqlId = "SELECT * FROM products WHERE productId='".$productId."'";
$sqlIdResult = mysqli_query($con,$sqlId);
while($rowId=mysqli_fetch_array($sqlIdResult)) {
?>
<tr>
<td>
<label for="productName">Product Name: </label>
</td>
<td>
<input name="productName" id="productName" type="text" value="<?php echo $rowId['productName']; ?>"/>
<input name="prodId" id="prodId" type="hidden" value="<?php echo $rowId['productId']; ?>" />
</td>
<td>
<label for="productDesc">Product Description: </label>
</td>
<td rowspan="4">
<textarea name="productDesc" id="productDesc" cols="55" rows="10"><?php echo $rowId['productDesc']; ?></textarea>
</td>
</tr>
<tr>
<td>
<label for="gender">Gender: </label>
</td>
<td>
<select name="gender" id="gender">
<option id="1" value="1">Male</option>
<option id="2" value="2">Female</option>
<option id="3" value="3">Unisex</option>
</select>
<input type="hidden" value="<?php echo $rowId['genderId']; ?>" id="genderHid"/>
<script>
var gender=$('#genderHid').val();
var selected=$('#gender').find('#'+gender);
$(selected).attr('selected','selected');
</script>
</td>
</tr>
<tr>
<td>
<label for="inventory">Inventory: </label>
</td>
<td>
<input type="number" name="inventory" id="inventory" value="<?php echo $rowId['inventory']; ?>"/>
</td>
</tr>
<tr>
<td>
<label for="price">Price: </label>
</td>
<td>
$<input type="text" name="price" id="price" value="<?php echo $rowId['price']; ?>" />
</td>
</tr>
<tr>
<td>
<label for="productImage">Upload Image: </label>
</td>
<td>
<input type="file" name="productImage" id="productImage" />
</td>
<td colspan="2">
<div id="progress" style="width:100%;">
<div id="bar" style="height:50px;background-color:blue;width:0%;">
</div>
<p id="percent"></p>
</div>
</td>
</tr>
<tr>
<td colspan="2" rowspan="2">
<img id="prevImage" style="" src="<?php echo $rowId['productImage']; ?>" />
</td>
<td id="response">
</td>
<td>
<button type="submit" id="editInv">Edit Item</button>
</td>
</tr>
<tr>
</tr>
<?php
};
?>
</tbody>
</table>
</form>
AJAX
var options = {
beforeSubmit: function() {
// pre submit callback
$("#progress").show();
$("#percent").html("0%");
},
data: {
productName : $('#productName').val(),
productDesc : $('#productDesc').val(),
inventory : $('#inventory').val(),
price : $('#price').val(),
gender : $('#gender').val(),
image : $('#prevImage').attr('src'),
prodId : $('#prodId').val()
},
uploadProgress: function(event, position, total, percentComplete) {
//during submission
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function(msg) {
//post submit call back
$(".bar").css("width","100%");
$(".percent").html('100%');
$("#response").html(response.responseText);
},
complete: function(response) {
if(response.responseText=="Invalid File"){
} else {
$("#response").html(response.responseText);
//$("#addNew")[0].reset();
//$("#prevImage").attr('src','').hide();
$(".bar").css("width","0%");
$(".percent").html('0%');
}
},
error: function(response) {
alert(response.responseText);
}
};
$("#editInv").ajaxForm(options);
PHP
//If a file has been uploaded
if (!empty($_FILES["productImage"]["name"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/images/inventory/";
$target_file = $target_dir . basename($_FILES["productImage"]["name"]);
$fileName = str_replace(' ', '', $productName);
$target_file_insert = "/images/inventory/" . $fileName . ".jpg";
$targetFileUpload = $target_dir . $fileName . ".jpg";
$sql1 = "UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$targetFileUpload."' WHERE productId='".$prodId."'";
mysqli_query($con,$sql1);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["productImage"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG") {
echo "Sorry, only JPG, and JPEG files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["productImage"]["tmp_name"], $targetFileUpload)) {
mysqli_close($con);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else
//If a file has not been uploaded
/*if (empty($_FILES["productImage"]["name"])) */{
$sql2="UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$image."' WHERE productId='".$prodId."'";
mysqli_query($con,$sql2);
}
The path you need to check is $targetFileUpload not $upload.
Once uploaded check:
if (!file_exists($targetFileUpload)){...}
Ok, it was actually being caused by two different issues, one in the PHP and one in the order in which the variables were called in the JavaScript. I had to call everything except for the generated image using jQuery at the top of the page as global variables, then put the jQuery AJAX at the bottom of the page with the form action call.
Apparently, using the jQuery to call the values of the fields at the bottom of the page caused them to send the information that the page populated with from the back end, while placing them at the top of the page causes them to relay the changed input data to the AJAX call.
Any explinations why this worked this way?
<script>
var productName = $('#productName').val();
var productDesc = $('#productDesc').val();
var inventory = $('#inventory').val();
var price = $('#price').val();
var gender = $('#gender').val();
var prodId = $('#prodId').val();
</script>
//All your HTML Content
<script>
var options = {
beforeSubmit: function() {
// pre submit callback
$("#progress").show();
$("#percent").html("0%");
},
data: {
productName : productName,
productDesc : productDesc,
inventory : inventory,
price : price,
gender : gender,
image : $('#prevImage').attr('src'),
prodId : prodId
},
uploadProgress: function(event, position, total, percentComplete) {
//during submission
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function(msg) {
//post submit call back
$(".bar").css("width","100%");
$(".percent").html('100%');
$("#response").html(response.responseText);
},
complete: function(response) {
if(response.responseText=="Invalid File"){
} else {
$("#response").html(response.responseText);
//$("#addNew")[0].reset();
//$("#prevImage").attr('src','').hide();
$(".bar").css("width","0%");
$(".percent").html('0%');
}
},
error: function(response) {
alert(response.responseText);
}
};
$("#editInv").ajaxForm(options);
</script>
PHP if statement statement essentially looks like this:
if (!empty($_FILES["productImage"]["name"])) {
} else
//If a file has not been uploaded
if (empty($_FILES["productImage"]["name"])) {
}
Thank you #fred-ii- for the error catcher.
Related
Query is If I select 'Select a New Parent category' from dropdown, a new textbox gets appear. I wants to insert that value into database. That textbox is hidden bydefault.
HTML FILE
<head>
<script type="text/javascript">
$(document).ready(function() {
$('#parentcat').change(function(){
if($('#parentcat').val() === 'Create a New Parent Category')
{
$('#other').show();
$('#catname').hide();
}
else
{
$('#other').hide();
$('#catname').show();
}
});
});
</script> </head>
<table>
<body>
<form method="POST" action="" name="form1" enctype="multipart/form-data" >
<tr>
<td><h4>Add category</h4></td>
</tr>
<tr>
<td>Select parent Category:</td><td><select name="parentcat" id="parentcat">
<?php
include "../storescripts/connect_to_mysql.php";
$result=mysql_query("SELECT parent from category"); while($row=mysql_fetch_array($result)){
echo "<option>".$row['parent'];"</option>";
} ?>
<option value="Create a New Parent Category">Create a New Parent Category</option>
</select><br/></td>
<tr><td><input type="text" id="other" name="other" placeholder="New Parent Category Name:" style="display: none;"/></td></tr>
</tr>
<tr>
<td></td><td><input type="text" name="catname" placeholder="SubCategory name" id="catname"><br/></td>
</tr>
<tr>
<td>Status:
</td>
<td><select name="status" >
<option selected="Active">Active</option>
<option>Inactive</option>
</select></td>
</tr>
<tr><td>Category Image :</td><td><input type="file" name="imageUpload" id="imageUpload"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Insert"></td>
</tr>
</form>
</table>
Here is my complete HTML file,bydefault 'other' dropdown is hidden. Now Here I'm providing my php code that inserts values into database, issue is how can I insert value of hidden filed into database. My database fields includes : cat_id(Auto-increment),cat_name,parent,cat_status,cat_image.
Here Is my php code for inserting values into database.
<?php
if(isset($_POST['submit']))
{
$parentcat=$_POST['parentcat'];
$catname=$_POST['catname'];
$status=$_POST['status'];
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
$sql = mysql_query("SELECT cat_id FROM category WHERE cat_name='$catname' LIMIT 1");
$CatMatch = mysql_num_rows($sql); // count the output amount
if ($CatMatch > 0) {
echo 'Sorry you tried to place a duplicate "Category Name" into the system, click here';
exit();
}
else{
$sql=mysql_query("INSERT INTO `category` (`cat_name`, `parent`, `cat_status`,`cat_image`) VALUES ('$catname', '$parentcat', '$status','$image') ");
echo $sql;
}
}
?>
For an eg. If I Select A new parent category then Subcategory named textbox appears and I want to insert that value into database. How Can i do that.
Change your jquery code like this
<script type="text/javascript">
$(document).ready(function () {
$('#parentcat').change(function () {
if ($('#parentcat').val() === 'Create a New Parent Category'){
$('#other').prop('type', 'text');
$('#catname').prop('type', 'hidden');
}
else{
$('#other').prop('type', 'hidden');
$('#catname').prop('type', 'text');
}
});
});
</script>
Also change your HTML code for #other input box like this
<input type="hidden" id="other" name="other" placeholder="New Parent Category Name:"/>
Let me know if it works for you.
Edit
In your PHP file, Instead of $catname=$_POST['catname']; add this
$catname = ( $parentcat == "Create a New Parent Category") ? $_POST['other'] : $_POST['catname'];
I want to display info and disable a process button if a certain condition is not met at the point of entering the value(onblur or onkeyup event). I have tried many example but none has given me result. Can someone help me out
The Ajax code:
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select.custid").change(function () {
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url: "process-loan.php",
data: {
custQual: selectedCustomer,
custid: selectedCustId
}
}).done(function (data) {
$("#qualify").html(data);
});
});
});
</script>
Below is the php page
<th>Customer No:</th>
<td>
<select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php while ($rw = mysqli_fetch_array($get)) { ?>
<option value="<?php echo $rw['custid'] ?>"><?php echo $rw['custid'] ?></option>
<?php } ?>
</select>
</td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td id="qualify"> </td>
<td id="qualify"> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
The process-loan.php script that will respond to the ajax call:
<?php
if (isset($_POST["amt"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
$amt = $_GET["amt"];
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if ($amt !== NULL) {
$gets = "SELECT * FROM tab_customer_dailycontribution WHERE custid='" . $custid . "' AND transactionDate BETWEEN '2015-09-01' AND '2015-09-30'";
$get = mysqli_query($connection, $gets);
$sum = 0.00;
while ($row = mysqli_fetch_array($get)) {
$sum += $row['amountContribute'];
}
if ($sum >= $amt) {
//qualify for loan $ enable the Process Button to save
echo "You are Qualify to Apply";
} else {
//disqualify for loan $ disable the process button until condition is meant.
echo "Insufficient Fund: Unqualify to Apply";
}
//end if condition
}
}
?>
this is for demo so i have commented tour mysql related things:first change your keys in process-loan.php.
your view page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#pButton").hide();
$("#amt").on("blur",function(){
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url:"process-loan.php",
data:{custQual:selectedCustomer,custid:selectedCustId},
success:function(data){
var data=JSON.parse(data);
$("#qualify").html(data.msg);//your message
if(data.status == 0){
$("#pButton").show();//showing button if qualified
}else{
$("#pButton").hide();
}
}
});
});
});
</script>
<th>Customer No:</th>
<td><select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php $i =0; while($i <4){?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php $i++;}?></select></td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td ><div id="qualify"></div></td><!-- added div in td to show message it can be outside of your table !-->
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
process-loan.php
<?php
if(isset($_POST["custQual"])){
// include 'includes/session.php';
// include 'includes/db_connection.php';
$amt = $_POST["custQual"];//here use $_POST not $_GET
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if($amt !== NULL){
$sum=100000;//static value for demo
if($sum >= $amt){
//qualify for loan $ enable the Process Button to save
$res["status"]=0;
$res["msg"]="You are Qualify to Apply";
}else{
//disqualify for loan $ disable the process button until condition is meant.
$res["status"]=1;
$res["msg"]= "Insufficient Fund: Unqualify to Apply";
}//end if condition
}else{
$res["status"]=1;
$res["msg"]= "put some amount first";
}
echo json_encode($res);
}
<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.
Here is my problem:
I want to make a database search using PHP form. I have my form and I want it to work even if there are some empty fields (as like more fields u fill, the more specific answer u get). I am using Jquery to first get values from my form and then send it by $.post to my actual php file which connects with database and do the search. I am simply giving empty fields some specific value which is recognized in my php file as 'empty' field so i can make a proper sql query. The problem is I find my $_post variables empty, even though variables in Jquesry script are set properly. I am using this method in other cases and it works fine. I have no idea if this matter but I am loading my form inside my main div using Jquery as well. The alert(data) function does its job: in prompt window i can see my results of search but reloading profile.php gives me nothing. Here is my code:
form:
<script type="text/javascript" src="scripts/admin.js"></script>
<form id="form_admin">
<table cellpadding="0" cellspacing="0" width="180">
<p style="line-height: 2cm; ">
<tr>
<td width="50" class="label1">Imię:</td>
<td>
<input id="imie" type="text" value="">
</td>
</tr>
<tr>
<td width="50" class="label1">Nazwisko:</td>
<td>
<input id="nazwisko" type="text" value="">
</td>
</tr>
<tr>
<td width="50" class="label1">Numer telefonu:</td>
<td>
<input id="telefon" type="text" value="">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="button" id="register" value="Pokaż!">
<br>
</td>
</tr>
</p>
</table>
</form>
admin.js
$(document).ready(function () {
$("#register").click(function () {
if ($("#imie").val() != "") {
var imie = $("#imie").val();
} else {
var imie = 'nic';
}
if ($("#nazwisko").val() != "") {
var nazwisko = $("#nazwisko").val();
} else {
var nazwisko = 'nic';
}
if ($("#telefon").val() != "") {
var telefon = $("#telefon").val();
} else {
var telefon = 'nic';
}
$.post("profile.php", {
name: imie,
surname: nazwisko,
telephone: telefon
}, function (data) {
alert(data);
});
$("#main").load('profile.php');
});
});
profile.php
<? php
include('config.php');#logging into database
if (isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['telephone'])) {
$IMIE = $_POST['name'];
$NAZWISKO = $_POST['surname'];
$TELEFON = $_POST['telephone'];#then my sql queries go...
while ($user = mysql_fetch_assoc($select)) {
echo 'ORDER_ID zamówienia: '.$user['ORDERINFO_ID'];
echo 'DATA zamówienia: '.$user['DATE_PLACED'];
}
while ($user = mysql_fetch_assoc($select2)) {
echo 'SUBORDER_ID: '.$user['SUBITEM_ID'];
echo 'Ilość: '.$user['QUANTITY'];
echo 'Koszt zamówienia: '.$user['COST'];
}
} else {
echo "$_POST variables aren't set";
}
?>
Edit:
I have installed Firebug and checked POST profile.php after submitted data and it contains all variables as expected.
Try changing your $.post function to:
$.post("profile.php", {
data: "&name=" + imie + "&surname=" + nazwisko + "&telephone=" + telefon
}, function (data) {
alert(data);
});
Your inputs do not have any name
for example:
<input id="imie" type="text" value="" name="imie">
I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.