Using Ajax to store checkbox in database - php

Update: The code is working. I had an incorrectly named table in my php file.
I have the following that I've found from some snippets during my searches for help however I cannot get it to work. What I am trying to accomplish is clicking a check box and it automatically populate a row in my database that I can refer to on any other page. Right now when I click the checkbox, nothing happens.
HTML
<td><input type="checkbox" name="<?php echo $brow['WorkOrder']; ?>" value="<?php echo $brow['WorkOrder']; ?>"></td>
Ajax
<!-- Checkbox storage -->
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('functions/checkBox.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!');
}
});
}
});
});
</script>
functions/checkBox.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
include("../../db.php");
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO TemporaryCheckBoxID (WorkOrder) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>

To check whether checkbox is checked or not use as below and try
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).is(":checked");
if(checked){
var value = $(this).val();
$.post('functions/checkBox.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!');
}
});
}
});
});

Related

Select and Delete multiple rows by selecting checkboxes using PHP

Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
<input class='file' type="checkbox" class="form-control" name="hid" id="<?php $rs["carimgid"]; ?>" placeholder="Please choose your image">
this my ajax script where using this to delete multiple row without refresh
<script type="text/javascript">
$(document).ready(function(){
jQuery('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
jQuery('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
//alert(allVals.length); return false;
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
//$("#loading").show();
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
//for server side
var join_selected_values = allVals.join(",");
$.ajax({
type: "POST",
url: "delete.php",
cache:false,
data: 'ids='+join_selected_values,
success: function(response)
{
$("#loading").hide();
$("#msgdiv").html(response);
//referesh table
}
});
//for client side
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
jQuery('.remove-row').on('click', function(e) {
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
$('table tr').filter("[data-row-id='" + $(this).attr('data-id') + "']").remove();
}
});
});
</script>
and my php code is
<?php
include("config.php");
if(isset($_POST['ids'])){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid ='$id'");
}
?>
Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
You haven't got the ids from POST.
Look at the following
$ids = mysqli_real_escape_string($con, $_POST['ids']);
if(!empty($ids)){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid IN ({$ids})");
}

Form submission according to ajax condition is not working

I have a form submission page, call a function at the time of form submission.Include an ajax.Form submission occur or not according to the condition in ajax.Ajax msg have two values 1 and 0,one value at a time.My requirement is when msg==1 form not submit and msg==0 submit form.But now in both cases form is not submitting.
My code is given below.Anybody give any solution?
main page
<form action="addCustomer_basic.php" method="post"
name="adFrm" id="myform" >
<input name="name" type="text"
class="txtfld" id="name"
value=">" style="width:250px;"/>
<input name="email" type="text"
class="txtfld" id="email" value="" style="width:250px;"/>
<input name="submit" type="submit" value="Submit" />
</form>
<script language="JavaScript">
$(function() {
$("#myform").submit(function(e) {
var $form = $(this);
var cust_name = $form.find('[name="name"]').val();
e.preventDefault();// prevent submission
var email = $form.find('[name="email"]').val();
$.ajax({
type: "POST",
url: 'ajx_customer_mailid.php',
data:'cust_name='+cust_name + '&email=' + email,
success: function(msg)
{
alert(msg);
if(msg==1)
{
alert("Email Id already excist in database");
return false;
}
else
{
self.submit();
}
}
});
});
});
</script>
ajx_customer_mailid.php
<?php
require_once("codelibrary/inc/variables.php");
require_once("codelibrary/inc/functions.php");
$cust_id=$_POST['cust_name'];
$email=$_POST['email'];
$se="select * from customer where name='$cust_id' and email='$email'";
$se2=mysql_query($se);
if($num>0)
{
echo $status=1;
}
else
{
echo $status=0;
}
?>
I've checeked your code, without ajax, and just set directly the msg to 1 or to 2.
See my code, now you can simulate it:
$("#myform").submit(function(e) {
var $form = $(this);
e.preventDefault();// prevent submission
var msg = 2;
if (msg === 1) {
alert("Email Id already excist in database");
return false;
} else {
$form.submit(); //This causes Too much recursion
}
});
There are some errors in it.
So, self.submit(); is bad:
TypeError: self.submit is not a function
self.submit();
You need to rewrite it to $form.submit();
But in that case, if the form needs to submit, you will get an error in your console:
too much recursion
This is because, if it success, then it fires the submit again. But, because in the previous case it was succes, it will be success again, what is fires the submit again, and so on.
UPDATE:
Let's make it more clear what happens here. When you submit the form, after you call e.preventDefault() what prevents the form to submit. When ajax need to submit the form, it triggers the submit(), but you prevent it to submit, but ajax condition will true again, so you submit again, and prevent, and this is an inifinte loop, what causes the too much recursion.
NOTE:
if($num>0) Where the $num is come from? There are no $num anywhere in your php file. You also do not fetch your row of your sql query.
Use mysqli_* or PDO functions instead mysql_* since they are deprecated.
Avoid sql injection by escaping your variables.
So you need to use like this:
$se = "select * from customer where name='$cust_id' and email='$email'";
$se2 = mysql_query($se);
$num = mysql_num_rows($se2); //NEED THIS!
if ($num > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
But i am suggest to use this:
$se = "SELECT COUNT(*) AS cnt FROM customer WHERE name='".mysql_real_escape_string($cust_id)."' and email='".mysql_real_escape($email)."'";
$se2 = mysql_query($se);
$row = mysql_fetch_assoc($se2); //NEED THIS!
if ($row["cnt"] > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
By the time your ajax call finishes, submit handler already finished so the submit continues, it's async you know, so the function makes the ajax call and continues executing. You can do something like this http://jsfiddle.net/x7r5jtmx/1/ What the code does is it makes the ajax call, then waits until the ajax success updates the value of a variable, when the value is updated, if the value is 1, no need to do anything, as we already stopped the form from submittin. If the value is 0, then trigger a click on the button to re-submit the form. You can't call submit inside the submit handler, but you can trigger click on the button. You obviously need to change the ajax call, just set msg inside your success.
var data = {
json: JSON.stringify({
msg: 0 //change to 1 to not submit the form
}),
delay: 1
}
var msg = null;
var echo = function() {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: data,
cache: false,
success: function(json){
msg = json.msg;
}
});
};
$( "#myform" ).submit(function( event ) {
echo();
var inter = setInterval(function(){
console.log("waiting: " + msg);
if (msg != null){
clearInterval(inter);
}
if (msg == 0){
$( "#myform" ).off(); //unbind submit handler to avoid recursion
$( "#btnn" ).trigger("click"); //submit form
}
}, 200);
return false; //always return false, we'll submit inside the interval
});

Pass AJAX Variable to PHP

Hi so my over all aim is to click a table get its ID and then use its ID to load another table. So far I am able to get the ID, but when I try to load the second table I get the error
"Undefined index: Projec_ID in C:\xampp\htdocs\abac\ajaxupdate.php on
line 6 "
Here's my Code
AJAX Script(Console prints the rowID so it is getting, the variable I think something is going wrong when trying to pass it?)
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var log = $("#log");
$(".getRow").click(function() {
console.log("Clicked a row...");
rowID = $(this).find("td.idCell").text();
//Print the row ID in the log cell to make sure we got the right one.
log.text("You 1clicked row "+rowID);
console.log("You cl2icked row "+rowID);
//Send the row ID to ajaxupdate.php
$.post("/abac/ajaxupdate.php", { what: "updateRow", Projec_ID: rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log(rowID );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
PHP File (ajaxupdate.php) I think there is something wrong here im guessing
<?php
if( (isset($_POST['submit'])) || (isset($_POST['Projec_ID'])) )
{
$Projec_ID =($_POST['Projec_ID']);
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('CV_ID', 'Classifier', 'Value', 'TP_ID')))
->from($db->quoteName('sessionta'))
//also is the like part right?
->where($db->quoteName('TP_ID') . ' LIKE '. $db->quote($_POST['Projec_ID']));
$db->setQuery($query);
$results = $db->loadObjectList();
//echo $Classifier;
}
?>
$_POST['submit'] will be false unless you set it:
[...] { "what": "updateRow", "Projec_ID": rowID, "submit" : "true"}
Which is why you get the error message "Undefined Index" -!
Furthermore, you can always:
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
die("The data above was sent via POST");
to troubleshoot these sorts of things..
Your problem could be that you are using an || operator and not an && operator.
if( (isset($_POST['submit'])) || (isset($_POST['Projec_ID'])) )
What this means if at some point you pass $_POST['submit'] and not $_POST['Projec_ID'] it will still run this code. giving you the
"Undefined index: Projec_ID in C:\xampp\htdocs\abac\ajaxupdate.php on line 6 "
Try changing your code to:
if( (isset($_POST['submit'])) && (isset($_POST['Projec_ID'])) )
I think Project_ID isn't going as a string..
Try this code.
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var log = $("#log");
$(".getRow").click(function() {
console.log("Clicked a row...");
rowID = $(this).find("td.idCell").text();
//Print the row ID in the log cell to make sure we got the right one.
log.text("You 1clicked row "+rowID);
console.log("You cl2icked row "+rowID);
//Send the row ID to ajaxupdate.php
$.post("/abac/ajaxupdate.php", { what: "updateRow", "Projec_ID": rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log(rowID );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
i just enclosed Projec_ID with with " .

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

Jquery Form Validation and Checking the values with Mysql Database through PHP Script

I have a form which has a input textbox and submit button.
On submission of the form the textbox value should get pass to an php script and check the values whether it exists in the Mysql Database. If it exists then we need to show an alert box stating that "Entered Value is already exists, Try something new". If the value not exists the form can be submitted to the php script which is in the form action.
I tried with the jquery and the code is below:
$(document).ready(function() {
$("#form_add").submit(function () {
var pval = $("#name").val();
var datastring = 'pname'+pval;
$.post("unique_valid.php", {pname:pval }, function (data){
alert('duplicate');
});
return false;
});
});
Problem with this code is It shows alert box on every case but its not allowing to submit the form if the values is not exists in the database.
Php code :
$pname = $_POST['pname'];
if( $pname == $row['name']){
echo "success";
}else{
echo "failure";
}
Suggest the better solution for this problem.
That's because you're alerting 'duplicate' no matter what the PHP output is. Try checking the value of data before alerting, like this:
$(document).ready(function() {
$("#form_add").submit(function () {
var pval = $("#name").val();
var datastring = 'pname'+pval;
$.post("unique_valid.php", {pname:pval },
function (data){
if(data == 'failure'){
alert('duplicate');
}else{
alert('not a duplicate');
}
});
return false;
});
});
And I'm assuming your PHP code will actually be saving the record if it's not a duplicate (your code doesn't indicate as much, though)?

Categories