I am trying to accomplish live checkbox result with checked/unchecked checkbox. My logic for checkbox works but now I want to store this live checkbox result in MYSQL. So when I click on checkbox, result should be stored in database same as when I uncheck checkbox result should be stored in database. I don't want to use any button in this example.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" >
function writeTo(object) {
var container = document.getElementById("container");
if (object.checked) {
container.innerHTML = "Added " + object.value + " <br />";
} else {
container.innerHTML = "Removed " + object.value + " <br />";
}
}
</script>
</head>
<body>
<div id="container"></div>
<input type="checkbox" onclick="return writeTo(this)" name="check_list" value="Appel">Apple<br>
<input type="checkbox" onclick="return writeTo(this)" name="check_list" value="Grape">Grape<br>
<input type="checkbox" onclick="return writeTo(this)" name="check_list" value="Orange">Orange<br>
<?php
echo $dd= "<script>document.writeln(container.innerHTML);</script>";
require 'Database.php';
echo $sql="Update scott123.rahul_tbl_users set group1='$dd' where Dingoid=70001501";
//$sql1=mysql_query($sql);
?>
</body>
</html>
Have your writeTo function initiate an ajax request to your server that performs the mysql insert/update query.
You can check the current state of a checkbox by reading its "checked" attribute.
If you have experience with jQuery, it makes a lot of this easier to implement.
In your writeTo function, you'll have to perform an Ajax call to a script that will then update the database.
In most basic form, it would look like: (using jQuery - http://jquery.com/)
function writeTo(object) {
// .. your other code ..
$.ajax( {
url: 'update.php',
method: 'POST',
data: { chkvalue: object.value }
} );
}
And update.php could then look like:
<?php
$value = $_POST['chkvalue'];
// $value now contains the checkbox value, which can now be updated in DB
Related
I have been reviewing a lot of the AJAX / PHP documentation and have a quick question for the community to help me understand the fundamentals. Here is a simple form, where a user submits a value. It is sent to a php calculator that squares the value and creates a little echo of the result.
I would like to learn how to simply include the php file into the div "target" after you click submit. Rather than pass back a value, I would like to include the php file in the div instead.
The forums have gotten me this far. Thanks to those who can look over and provide guidance.
square.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title> AJAX Insert test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form id="calculator" method="post">
What Number would you like to square?
<input type="text" name="input_value">
<input type="submit" value="Go">
</form>
<div id="target"></div>
<script>
$(function() {
$('#calculator').live('submit', function(e) {
e.preventDefault(); // stops form from submitting naturally
$.ajax({
data: $(this).serialize(),
type: 'POST', //'GET' is default, set to 'POST' if you want.
url: 'square.php',
success: function(response) {
$("#target").load("square.php");
}
});
});
</script>
square.php:
<html>
<p>Results:<br><br></p>
</html>
<?php
$input = htmlspecialchars($_POST['input_value']);
$sum = $input * $input;
echo "You wrote " . $input ." <br>";
echo $input . " squared = " .$sum . "<br><br>";
?>
You would want to display the echo of the square.php, which means you have to do the following: $("#target").load(response);
I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');
I am trying to accomplish live checkbox result with checked/unchecked checkbox.
My logic for checkbox works but now I want to store this live checkbox result in MYSQL So when I click on checkbox, result should be stored in database same as when I unchecked checkbox result should be stored in database.
I don't want to use any button in this example. I am very close to result just want doing something small mistake. Please help me out. Thank you.
Here is my complete small code:
### Check.php
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" >
function writeTo(object) {
var container = document.getElementById("container");
if (object.checked) {
container.innerHTML = "Added " + object.value + " <br />";
} else {
container.innerHTML = "Removed " + object.value + " <br />";
}
$.ajax( {
url: 'check1.php',
method: 'POST',
data: { chkvalue: object.value }
});
}
</script>
</head>
<body>
<div id="container"></div>
<input type="checkbox" onclick="return writeTo(this)" name="check_list" value="Appel">Apple<br>
<input type="checkbox" onclick="return writeTo(this)" name="check_list" value="Grape">Grape<br>
<input type="checkbox" onclick="return writeTo(this)" name="check_list" value="Orange">Orange<br>
<?php
echo $dd= "<script>document.writeln(container.innerHTML);</script>";
require 'Database.php';
echo $sql="Update scott123.rahul_tbl_users set group1='$dd' where Dingoid=70001501";
//$sql1=mysql_query($sql);
?>
</body>
</html>
###check1.php
<?php
$value = $_POST['chkvalue'];
echo $sql="Update scott123.rahul_tbl_users set group1='$value' where Dingoid=70001501";
$sql1=mysql_query($sql);
?>
Looks like you are trying to put alias on rahul_tbl_users like this scott123.rahul_tbl_users
This is wrong you cannot do that way.
i can get the $amount to show up on the page, but after I get a error telling me i need to add in an amount for it to run through the script
i just need the $amount to be added by the $payment, $donation, and post the $amount
<label>Payment:</label>
<input name="payment" id="payment" class="small-field" value="<?php echo $payment;?>" />
*
<div class="clr"></div>
<label>Donation:</label>
<input type="checkbox" id="donation" name="donation" value="1.00" />
<div class="clr"></div>
<?php echo $amount;?>
I think you mean JavaScript ( or jQuery package might be easier for you ).
Set up an event for checkbox;
Catch the value of the checkbox;
Add +1 to the value;
Replace the original value with the newly created one;
If I understand you correctly. Here is an example on how to do it.
<html>
<head>
<title>Test page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Dainis Abols" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input id="check2" type="checkbox" name="test" value="1">
<div id="check1" style="float: left;">1.00</div>
<!-- The event for checkbox with id 'check2' -->
<script>
$("#check2").click(function() {
var value = $(this).val(); /* Catching value of checkbox */
value++; /* Increasing value by one */
$(this).val(value); /* Replacing original value */
$(this).attr('checked', false); /* Removing CHECKED ( if needed ) */
$('#check1').html(value + '.00'); /* Just for visual aid */
});
</script>
<!-- End of event -->
</body>
</html>
If you wan't to change some php value with html script you'll need a form to post information to server, or use ajax to do this.
Php works just on server side, your HTML page are on client side. Both don't interact each other.
I recomend use ajax to do that in "real time". Something like that:
http://api.jquery.com/jQuery.ajax/
$(function () {
$("#payment").bind('change',function () {
if($(this).checked){
$.ajax({
type: "GET",
url: "test.php",
success: function(){
alert('value as incremented by 1');
}
});
}
});
});
I'm trying to display data from mysql on the same page that i've got my form with checkboxes. The question is how to write js script that gonna display it.
The code is:
<form id="myForm" action="pdoakcja.php" method="post">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<div id='name-data'>Instruktorzy o podanych uprawnieniach:</div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
............??????
</script>
You could solve your problem by using jquery form plugin, which will help you to submit the form without having to reload the page and show you the return from your target page in the same page. Just follow the instructions:
Download this jquery form plugin first and save it.
Then
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- This jquery.form.js is for Submitting form data using jquery and Ajax -->
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
if(responseText==1){
$("#error").html('No Result Found');
} else{
$("#result").html(responseText);
}
}
</script>
<form id="myForm" enctype="multipart/form-data" action="pdoakcja.php"
method="post" name="myForm">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<span id="error"></span>
<span id="result"></span>
YOUR pdoakcja.php file: (I have got the following code from your another post here, haven't checked it though)
<?php
$query = mysql_query("SELECT * FROM permissions WHERE m LIKE '".$_POST['M1']."' OR m LIKE '".$_POST['M2']."' OR mn LIKE '".$_POST['MN1']."' ");
if($query) {
while($permissions = mysql_fetch_assoc($query)){
$query2 = mysql_query("SELECT name_surname FROM instruktorzy WHERE instruktor_id='".$permissions['instruktor_id']."'");
while($Mdwa = mysql_fetch_assoc($query2)){
echo "<p style=\"font-size: 14px; font-family: Helvetica; background-color: #FFFFFF\"> ".$Mdwa['name_surname']."<br />" ; "</p>" ;
}
}
} else {echo "1";}
?>
I hope this will work for you. For detail information you could study the jquery form plugin's website.
Heres a pseudo example showing how you can do it with jQuery, this will also update as you click the check box so you could remove the submit altogether;
You say you already have a database doing the job so I wont include that. Just copy and paste.
<?php
//Some pseudo data kinda as your receive it from a query
$datafromSql = array(
array('id'=>1,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>2,'permission'=>'M2','theData'=>'User has M2 permission'),
array('id'=>3,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>4,'permission'=>'M1','theData'=>'User has M1 permission'),
);
//Access the data
if($_SERVER['REQUEST_METHOD']=='POST'){
$is_ajax = false;
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
$is_ajax = true;
}
//pseudo code, really you would put your query here
// SELECT theData FROM your_table WHERE permission=POST_VALUE ... ...
//And then format your output
$result=array();
foreach($datafromSql as $row){
if($is_ajax == true){
foreach($_POST as $key=>$value){
if($_POST[$key] == 'true' && $row['permission']==$key){
$result[]=$row['theData'].'<br />';
}
}
}else{
foreach($_POST as $key=>$value){
if($_POST[$key] == $row['permission']){
$result[]=$row['theData'].'<br />';
}
}
}
}
$result = implode('<hr />',$result);
//AJAX Response, echo and then die.
if($is_ajax === true){
header('Content-Type: text/html');
//example output sent back to the jQuery callback
echo $result;
//echo '<pre>'.print_r($_POST,true).'</pre>';
die;
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
$.post('./<?php echo basename(__FILE__)?>',
{
M1: $("#M1").is(':checked'),
M2: $("#M2").is(':checked')
},
function(data) {
$('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
});
}
</script>
</head>
<body>
<form method="POST" action="<?php echo basename(__FILE__)?>">
Permissions:
<input type="checkbox" id="M1" name="M1" value="M1" onChange="update()"/>M1
<input type="checkbox" id="M2" name="M2" value="M2" onChange="update()"/>M2
<input type="submit" value="Szukaj" />
</form>
<p id='result'><?php echo isset($result)?$result:null;?></p>
</body>
</html>
You should use the PHP MySQL functions to retrieve the data you want from your database and then display them via PHP, not javascript.
Especially have a look at this: mysql_fetch_assoc - there is a fully working example.