I have a couple of checkboxes to filter the results from database but I have two problems, the first is that I am using $_POST variable and when I hit refresh I am getting a confirm form submission dialog, which I don't want as the user may hit refresh many times.
The 2nd part of it is that, if I replace $_POSTwith $_GET I don't see the the confirm message but the checkboxes don't work. Anyone has any idea?
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
<form id="id" method="post" action="">
<input type="checkbox" name="new" class="checkbox" <?php if(isset($_POST['new'])) echo "checked"; ?>/> New<br>
<input type="checkbox" name="used" class="checkbox" <?=(isset($_POST['used'])?' checked':'')?>/> Used<br>
<input type="checkbox" name="ref" class="checkbox" <?=(isset($_POST['ref'])?' checked':'')?>/> Refurbished<br>
</form>
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$options = array(
'results_per_page' => 2,
'url' => 'products.php?search=' . urlencode($q) . '&page=*VAR*',
'db_handle' => $dbh
);
if (isset($_POST["ref"])) {
$arguments[] = " condition LIKE '%refur%' ";
}
if (isset($_POST["new"])) {
$arguments[] = " condition LIKE '%new%' ";
}
if (isset($_POST["used"])) {
$arguments[] = " condition LIKE '%use%' ";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT * FROM products where " . $str . " ORDER BY id desc";
$paginate = new pagination($page, $qry, $options);
echo $qry;
}
else {
$paginate = new pagination($page, "SELECT * FROM products order by id desc", $options);
}
This is just an idea, using the classical/modern ajax approach for submitting. Assume that this page is called jqpost.php:
<script>
$(document).ready(function () {
$('.checkbox').on('change',function(){
//$('#form').submit();
var formdata = $("#form").serialize();
$.post("jqpost.php", formdata, function(data) {
$("#result").html("Post OK: " + formdata);
});
});
});
</script>
<form id="form" method="post" action="">
<input type="checkbox" name="new" class="checkbox" <?php if(isset($_POST['new'])) echo "checked"; ?>/> New<br>
<input type="checkbox" name="used" class="checkbox" <?=(isset($_POST['used'])?' checked':'')?>/> Used<br>
<input type="checkbox" name="ref" class="checkbox" <?=(isset($_POST['ref'])?' checked':'')?>/> Refurbished<br>
</form>
<div id="result"></div>
<?php
//...
?>
If a user clicks on a checkbox, jQuery will post data to jqpost.php script. In return, #result div will give a status text.
As a result, if the user presses the refresh button on browser, the form is not submitted again and again.
Related
Hi i want insert javascript based genarated value into "input value attribute",
my code below like this when i scroll range slider its showing price in id="getdobtval" but when am going buynow its not inserting into database
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show"/>
<output id="getdobtcval" name="getdobtval"></output>
<input type="hidden" name="<?php $_SESSION['sess_user']; ?>">
<input type="submit" name="buynow" >
</form>
i changed value into input text now id="getdobtval" not showing generated value in form
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show"/>
<input type="text" id="getdobtcval" name="getdobtval">
<input type="hidden" name="<?php $_SESSION['sess_user']; ?>">
<input type="submit" name="buynow" >
</form>
my php form like this
<?php
if(isset($_POST['buynow'])){
$h_rate = $_POST['hrate'];
$hrate_price = $_POST['getdobtval'];
$in_username = $_SESSION['sess_user'];
$conn = mysqli_connect("localhost", "root", "", "buyrate");
$sql = "INSERT INTO buy_rate(hrate,hrate_price,in_username) VALUES('$h_rate','$hrate_price','$in_username')";
if (mysqli_query($conn, $sql)){
echo "Sucessfully Added";
}else{
echo "error";
}
mysqli_close($conn);
}
?>
my javascript like this
<script type="text/javascript">
jQuery(document).ready(function() {
$('#slider-bottom').slider().on('slide', function(ev){
var finalvalue='';
var finalbtvalue='';
var finalbtprice='';
var finalbitvalue='';
finalbtprice= 250;
var newVal = $('#slider-bottom').data('slider').getValue();
var textval = parseInt(newVal);
if( textval >= 600 && textval < 6000){
finalvalue= 0.075;
finalbitvalue = textval * finalvalue;
}else if(textval >=6000 && textval < 30000 ){
finalvalue= 0.070;
finalbitvalue = textval * finalvalue;
}else if(textval >= 30000 ){
finalvalue= 0.065;
finalbitvalue = textval * finalvalue;
}
finalbtvalue = finalbitvalue/finalbtprice;
if(finalbtvalue){
$("#getdobtcval").html("<strong>"+finalbtvalue.toFixed(8)+"</strong>");
}
});
$('#slider-bottom').sliderTextInput();
});
</script>
how to insert javascript based genarated value into "input value attribute", help me
i have update my answer
first you check that when you check amount then this field is empty or not <input type="hidden" id="getdobtval" name="getdobtval"> . type="hidden" change to type="text"
second change insert query
$sql = "INSERT INTO buy_rate(hrate,hrate_price,in_username)
VALUES('".$h_rate."','".$hrate_price."','".$in_username."')";
use concatenation in variables
I am new to Angular and am struggling to add a comment to a specific post that is being displayed from a database.
Under the post I have a hidden comment area that shows when pressing the button.
I then want to be able to add the comment to the post the comment area is attached too.
It seems like it is not getting the id but I can't find how to solve it.
It is doing the show/hide, and I am getting the "data inserted" in the console log so I'm guessing the problem is with the PHP?
Angular code
app.controller('meetings', function($scope, $http) {
$scope.meetings_insertdata = function() {
$http.post ("meetings_insert.php",{'meetings_commentdate':$scope.meetings_commentdate,'meetings_comment':$scope.meetings_comment})
window.location.reload();
console.log("data inserted");
};
});
app.controller('show_hide', function ($scope) {
$scope.Hidden = true;
$scope.ShowHide = function () {
$scope.Hidden = $scope.Hidden ? false : true;
}
});
meetings_insert.php
<?php
$data = json_decode(file_get_contents("php://input"));
$meetings_comment = $data->meetings_comment;
$meetings_commentdate = date('Y-m-d H:i:s');
$meetings_entry = $_GET['id'];
mysql_connect("localhost","user","password");
mysql_select_db("mdb_rh316");
mysql_query("UPDATE project_meetings SET (meetings_comment, meetings_commentdate) = ('$meetings_comment','$meetings_commentdate') WHERE meetings_entry = '$meetings_entry'");
?>
HTML code
<div class="entrybox" ng-controller="meetings">
<?php
mysql_connect("localhost","user","password");
mysql_select_db("mdb_rh316");
$result = mysql_query("SELECT * FROM project_meetings ORDER BY meetings_date DESC");
while ($row = mysql_fetch_array($result))
{
echo "<table>";
echo "<tr><td>" ?>Added: <? echo $row['meetings_date'] . $row['meetings_entry'] . "<br/>" . $row['meetings_content']."</td></tr>";
echo "<tr><td>" ?><br/><span class="emp">Comment: <?
echo $row['meetings_commentdate']."<br/>" . $row['meetings_comment']."</td></tr>";
echo "<tr><td>"?></span>
<div ng-controller="show_hide">
<input type="button" class="previous_add" value="Add comment" ng-click="ShowHide()" />
<br />
<br />
<div ng-hide = "Hidden">
<form method="post" action="meetings_insert.php?id=<? echo $row['$meetings_entry']?>">
<textarea class="textarea" placeholder="Add your comment here.." type="text" ng-model="meetings_comment" name="meetings_comment"></textarea><br/>
<input type="button" class="button" value= "Add" ng-click="meetings_insertdata()"/>
</form>
</div>
</div>
</td></tr><br/><?;
}
echo "</table>";
?>
</div>
Pass 'id' into the meetings_insertdata function:
<form method="post" action="">
<textarea class="textarea" placeholder="Add your comment here.." type="text" ng-model="meetings_comment" name="meetings_comment"></textarea>
<br/>
<input type="button" class="button" value="Add" ng-click="meetings_insertdata(<? echo $row['$meetings_entry']?>)" />
</form>
Receive it in the AngularJS function below:
app.controller('meetings', function($scope, $http) {
$scope.meetings_insertdata = function(id) {
$http.post("meetings_insert.php", {
'meetings_commentdate': $scope.meetings_commentdate,
'meetings_comment': $scope.meetings_comment,
'meetings_event': id
})
window.location.reload();
console.log("data inserted");
};
});
Then, pick up 'id' from the posted value ($data->meetings_event)
$data = json_decode(file_get_contents("php://input"));
$meetings_comment = $data->meetings_comment;
$meetings_commentdate = date('Y-m-d H:i:s');
$meetings_entry = $data->meetings_event;
<form action="" method="post">
<?php
$sql = "select * from tb_transport";
$query = mysql_query($sql);
$a=1;
while($row=mysql_fetch_array($query))
{
$sql_2="select * from transport_two where transport_id='$row[name]'";
$query_2=mysql_query($sql_2);
$row_2=mysql_fetch_array($query_2);
?>
<input type="checkbox" name="courses[<?php echo $a; ?>][crs]" value="<?php echo $row["name"]; ?>" <?php if($row_2["transport_id"]=="$row[name]") { ?> checked="checked" <?php } ?> />< ?php echo $row["name"]; ?>
<?php
$a=$a+1;
}
?>
<input type="submit" name="save" />
</form>
Here is my form and I'm having a number of checkboxes dependent on my database records.
Here, also I have applied code that if a checkbox value exists in database then it is shown checked.
If I have checked a checkbox, then a row gets inserted with the checkbox value.
Now what I am looking for is that if I uncheck the checked checbox then that database row gets deleted.
How can I do this?
Here is my insertion code:
<?php
if(isset($_POST["save"])) {
$arr = $_POST["courses"];
for ($i = 0; $i < 20; $i++) {
if (!empty($arr[$i]['crs'])) {
$a = $arr[$i]['crs'];
mysql_query("insert into transport_two set transport_id='$a'");
}
}
}
?>
If you want to delete from a database at the moment when a checkbox is marked/unmarked, you need to use JavaScript or jQuery.
If you want to delete from a database at the moment a user clicks on the submit button, you have to send the value to your php - script which updates/deletes from a database.
just give a simple class to checkbox.
<form action="" method="post">
<?php
$sql="select * from tb_transport";
$query=mysql_query($sql);
$a=1;
while($row=mysql_fetch_array($query))
{
$sql_2="select * from transport_two where transport_id='$row[name]'";
$query_2=mysql_query($sql_2);
$row_2=mysql_fetch_array($query_2);
?>
<input type="checkbox" class="deleteFromDb" name="courses[<?php echo $a; ?>][crs]" value="<?php echo $row["name"]; ?>" <?php if($row_2["transport_id"]=="$row[name]") { ?> checked="checked" <?php } ?> /><?php echo $row["name"]; ?>
<?php
$a=$a+1;
}
?>
<input type="submit" name="save" />
</form>
Here click on any check box and jquery check it is check or uncheck. if it uncheck then ajax send request to delete this record from db.
$(document).ready(function(){
$(".deleteFromDb").change(function(e){
if ($(this).prop('checked')==false){
$.ajax({type: "POST",
url: "deleterecord.php",
data: { id:$(this).val().trim() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
alert("record deleted");
}
}});
});
}
});
Delete.php
Here perform your delete action.
$id = $_POST['id'];
$strSQL = mysql_query("DELETE FROM `table` WHERE id = ".$id);
if($strSQL){
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
Now when you click any checkbox and if it ubcheck, the record will delete from db.
I have created a song database (mysql) where a user can enter data into the textfield, select "by artist" or a "by title" radio button and click submit. This all works fine. :)
However, I would like to add another submit button that bypasses the above query and simply lists all of the songs that have been added to the database with a year's time.
I believe that the query I need is:
select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
but I cannot figure out how to code the PHP to run the query for the songs within the past year.
Here are the two forms I have:
<p>
<form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="Submit" value="Search" />
</form></p>
<form name="form" method="post" action="">
<br />
<input type="submit" name="Newsongs" value="New Releases" />
</form></p>
and here is the current, working php for the 1st query:
<?php
$delimiter = "\t";
$newline = "\n";
$var = #$_GET['q'] ;
$field = #$_GET['field'];
$var = htmlentities($var);
$trimmed = trim($var); //trim whitespace from the stored variable
$search_words = explode(' ', $var);
if ($var != "") {
// rows to return
$limit=100;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
mysql_connect("DBLocation","DatabaseName","PASSWORD"); //(host, username, password)
//specify database
mysql_select_db("DatabaseName") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "SELECT * FROM Songs where $field like \"%$trimmed%\" order by $field ";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "<p style=\"color: #00ff00; font-size: 1.2em;\">Results</p>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$artist = $row["artist"];
echo "$title";
echo " - ";
echo "$artist";
echo "<br />";
echo $newline;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}
?>
You can add a hidden field and then check it on submit:
<input type="hidden" name="act" id="act" value="">
Then on your second submit button, use JavaScript to change the value:
<input type="submit" name="Newsongs" value="New Releases" onclick="document.getElementById('act').value = 'list_all'" />
If the value is "list_all", process that, else do your current processing.
if ($_POST['act'] == 'list_all') {
// process second submit button code
} else {
// all your current code
}
You'll want to check if the NewSongs submit button was on the form submitted, and use that in an if statement to do the query or not.
<?php
if (!isset($_POST['NewSongs'])){
//do the search
} else {
//don't do the search
}
?>
You could use 2 submit button inside a form :
<p><form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="submit" value="Search" />
<input type="submit" name="submit" value="New" />
</form>
</p>
<?php
if(isset($_GET['submit']) && $_GET['submit'] == 'Search'){
// do search
}
if(isset($_GET['submit']) && $_GET['submit'] == 'New'){
// do second search
}
?>
I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.
So far so good. What I'm trying to do is to close colorbox and refresh a div on success.
I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.
I'll appreciate any help here.
Here is my ajax:
jQuery(function(){
jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
cbox_submit();
}});
});
function cbox_submit()
{
jQuery("#pre-process").submit(function(){
jQuery.post(
jQuery(this).attr('action'),
jQuery(this).serialize(),
function(data){
jQuery().colorbox({html: data, onComplete: function(){
cbox_submit();
}});
}
);
return false;
});
}
form php code:
<?php
error_reporting(-1);
include "conf/config.php";
if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect
$session_id=session_id();
if(isset($_REQUEST['submit'])){
if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
}
if (array_search("", $_POST['opt']) !== false)
{
$msg = "Please select all accessories!";
}else{
$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));
if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}
$sql['session_id'] = $session_id;
$sql['rest_id'] = $_POST['rid'];
$sql['prod_id'] = $_POST['pid'];
$sql['extras'] = $extras;
$sql['added_date'] = Date("Y-m-d H:i:s");
$newId=insert_sql("cart",$sql);
}
}
?>
<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
<?php
$name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
$getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
while ($rsrw = #mysql_fetch_array($getRss)) {
$goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");
$goptionals=explode(', ',($goptionals));
echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
foreach($goptionals as $v)
{
$vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
while ($rsgb = #mysql_fetch_array($vname)) {
$aa=$rsgb['optional'];
}
echo "<option value=".$v." >".$aa."</option>";
}
echo "</select>(required)<br>";
//}
}
$getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid."");
?>
<br><br>
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td bgcolor="#EAFFEC">
<div style="width:440px; ">
<?php
while ($rssp = #mysql_fetch_array($getRss)) {
$optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
$price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>" /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>
</td>
</tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
</div><input type="hidden" name="submit" /><input id='submit' class="CSSButton" style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />
<br /><br />
</div>
</form>
I don't know colobox, but if I understand well what you are trying to do,
I would say your javascript should more look like this
function cbox_submit()
{
jQuery("#pre-process").submit(function(e) {
e.preventDefault(); // prevents the form to reload the page
jQuery.post(
jQuery(this).attr('action')
, jQuery(this).serialize()
, function(data) {
if (data['ok']) { // ok variable received in json
jQuery('#my_colorbox').colorbox.close(); // close the box
}
}
);
return false;
});
}
jQuery(function() {
jQuery('#my_colorbox').colorbox({
maxWidth: '75%'
, onComplete: cbox_submit // Bind the submit event when colorbox is loaded
});
});
You should separate at least your php script that does the post part.
And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:
<?php
# ... post part ...
# if success
ob_clean();
header('Content-type: application/json');
echo json_encode(array('ok' => true));
?>