I'm trying to create an dynamic AJAX function using PHP and MySQL but have had little success so far. Its purpose is to update records in a database without refreshing the page or changing to another page.
On the page with the forms I have the following code:
// jQuery
<script type="text/javascript">
<?php
$sql = "SELECT * from pm_schedule";
$result = $pdo->query($sql);
foreach ($result as $row)
{
echo
"$(document).ready(function() {
$('#updatebtn".$row['id']."').click(function() {
$('#result".$row['id']."').show('slow').delay(4000).hide('slow')
$.post('process.php', $('#updateform".$row['id']."').serialize())
});
return false;
});";
}
?>
</script>
// form
$sql = "SELECT * from pm_schedule";
$result = $pdo->query($sql);
foreach ($result as $row)
{
echo
'<form id="updateform'.$row['id'].'">
<div class="tbl_header">'.$row['task'].'</div>
Due Date:
<script>
$(function() {
$( "#datepicker'.$row['id'].'" ).datepicker({ minDate: -0,
dateFormat: \'dd/mm/yy\', maxDate: new Date(2013, 1,22) })
});
</script>
<input type="text" id="datepicker'.$row['id'].'" style="width: 100px; height: 10px;" value="'.$row['duedate'].'" name="duedate"/>
Status:
<select style="width: 125px;" name="status">
<option>'.$row['status'].'</option>
<option>----</option>
<option>Pending</option>
<option>In Progress</option>
<option>Complete</option>
</select>
<input type="hidden" name="id" value="'.$row['id'].'">
<input type="submit" id="updatebtn'.$row['id'].'" value="Update"
style="width: 100px;"/>
</form>
<div id="result'.$row['id'].'" style="display: none; color: red">
Update successful!
</div>
<p>';}
On the page responsible for the processing (process.php), I have the following code:
<?php
$name = mysql_real_escape_string($_POST["name"]);
$status = mysql_real_escape_string($_POST["status"]);
$id = mysql_real_escape_string($_POST["id"]);
$sql = "UPDATE pm_schedule SET name=?, status=?, id=? WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($name,$status,$id));
?>
What am I doing wrong?
The return false is in the function called on $(document).ready, not in the click-handler, so I guess this causes the form to submit anyway after finishing the clickhandler. Maybe move the statement one line up:
echo
"$(document).ready(function() {
$('#updatebtn".$row['id']."').click(function() {
$('#result".$row['id']."').show('slow').delay(4000).hide('slow');
$.post('process.php', $('#updateform".$row['id']."').serialize());
return false;
});
});";
As ripa said, a few more ; should be helpful either.
place ; over here
foreach ($result as $row)
{
echo
"$(document).ready(function() {
$('#updatebtn".$row['id']."').click(function() {
$('#result".$row['id']."').show('slow').delay(4000).hide('slow');
$.post('process.php', $('#updateform".$row['id']."').serialize());
});
return false;
});";
}
Related
I was working on my assignment to make an ajax live search. Unfortunately, I've got an error saying 'undefined index = q'.
Here is my jquery:
<script>
$(document).ready(function(e){
$("#search").keyup(function(){
$("#here").show();
var x = $(this).val();
$.ajax({
type:'GET',
url:'index.php',
data:'q='+x,
success:function(data){
$("#here").html(data);
},
});
});
});
</script>
<input type="search" name="search" id="search">
<div id="name">
</div>
my php:
<?php
if(empty($_GET['q']))
{
$q = $_GET['q'];
$query = "SELECT * FROM info WHERE name LIKE '%$q%'";
$result = mysqli_query($conn, $query);
while($output = mysqli_fetch_assoc($result))
{
echo '<a>' . $output['name'] . '</a>';
}
}
?>
Your code is wrong. Here is a fix
<script>
$(document).ready(function(e){
$("#search").keyup(function(){
$("#here").show();
var x = $(this).val();
$.ajax({
type:'GET',
// Here we will pass the query to the php page
url:'index.php?q='+x,
// disabling the cache
cache: false,
success:function(data){
$("#here").html(data);
},
});
});
});
</script>
<input type="search" name="search" id="search">
<div id="name">
</div>
my php:
<?php
if(isset($_GET['q']))
{
$q = $_GET['q'];
// You need to sanitize the input before pass the query.
$query = "SELECT * FROM info WHERE name LIKE '%$q%'";
$result = mysqli_query($conn, $query);
while($output = mysqli_fetch_assoc($result))
{
echo '<a>' . $output['name'] . '</a>';
}
}
?>
I am trying to make a live search using ajax. The search is working fine but i want it to be clickable. This is the code
<div class="box-body">
<h2>Search Database</h2>
<input class="form-control" type="text" name="search" id="search" placeholder="search our inventory">
<br>
<br>
<h2 class="bg-success" id="result">
</h2>
<script type="text/javascript">
$('#search').keyup(function(){
var search = $('#search').val();
$.ajax({
url:'searchproditem.php',
data:{search:search},
type: 'POST',
success:function(data){
if(!data.error) {
$('#result').html(data);
$('#result li').click(function(){
var res_value = $(this).text();
$('#search').attr('value', res_value);
});
}
}
});
});
</script>
<?php
include 'db/db.php';
$search = $_POST['search'];
if (!empty($search)) {
$res = $con->prep("SELECT * FROM items WHERE itemname LIKE :search ");
$res->bindValue(':search', "$search%");
$res->execute();
$count = $res->rowCount();
if (!$res) {
die('QUERY FAILED');
}
if ($count <= 0) {
echo "Sorry We dont have that item in stock";
}else{
while ($r = $res->fetch(PDO::FETCH_ASSOC)) {
$brand = $r['itemname'];
?>
<ul class="list-unstyled">
<?php
echo "<li>{$brand} in stock</li>";
?>
</ul>
<?php
}
}
}
?>
Try this for click function. To bind events with dynamically generated events, we can use following approach.
$('#result').on('click', 'li', function(){
var res_value = $(this).text();
$('#search').attr('value', res_value);
});
I am new to this so an early sorry if my question useless... :) I want to be able to click on a result of a search output (the same as a dropdown menu except it's with a search bar) I have looked on internet but nothing could interest me. Thank you. PS: the connection of my database is in an other code but that shouldn't be useful.
Here is my code so far :
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche" class="search" onkeypress="showdiv()">
</div>
<div class="resultat" id="resultat" id="resultat" style="display: none;">
<a>Please continue typing...</a>
<br>
<br>
<br>
<br>
</div>
<script type="text/javascript">
function showdiv() {
document.getElementById("resultat").style.display = "block";
}
</script>
PHP:
<?php
include 'connect.php';
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$sql = "SELECT name FROM smartphone WHERE name LIKE '%" . $motclef . "%' LIMIT 5";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "Aucun resultat trouvé pour: " . $motclef;
}
}
?>
jQuery:
$(document).ready(function(){
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#recherche').keyup(function() {
delay(function(){
var recherche = $('#recherche').val();
if (recherche.length > 1) {
$("#resultat").html("");
$.get( "fetch.php", { motclef: recherche} )
.done(function( data ) {
$("#resultat").html(data);
});
}
}, 1000 );
});
});
First-page.php
<?php
global $wpdb;
$supplier_prod_table=$wpdb->prefix.'supplier_product_post';
$sup_query=$wpdb->get_results("SELECT * FROM $supplier_prod_table");
$supp_name_chek=$user_info->user_login;
?>
<div class="form-group">
<input name="keysearch" value="<?php if($supp_name_chek!='') { echo $supp_name_chek; }?>" placeholder="name" id="keysearch" type="text" class="form-control">
<input type="hidden" value="" id="supplier_id">
<span id="loading">Loading...</span> </div>
db page
if(isset($_POST['keysearch']))
{
include('../../../../wp-load.php');
global $wpdb;
$search = $_POST['search'];
$table_name= $wpdb->prefix.'users';
$data = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `user_nicename` like '%$search%' OR `display_name` like '%$search%'");
foreach($data as $key)
{
$user_id=$key->ID;
$user = new WP_User( $user_id );
$role=$user->roles[0];
if($role=='supplier'){
$username = $key->user_login;
?>
<div class="search_show" align="left" id="<?php echo $user_id ?>"><?php echo $username; ?></div>
<?php
// echo "<div class='show' onclick='select_supp()'>".$username."</div>";
}
}
}
JS Code
jQuery(document).ready(function(){
jQuery('#keysearch').on('keyup', function(){
var ajax_search_url=search_url;
var key = jQuery('#keysearch').val();
if (key && key.length > 2)
{
jQuery('#loading').css('display', 'block');
jQuery.ajax({
url : ajax_search_url,
type : 'POST',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
jQuery('#loading').css('display', 'none');
jQuery("#search_result").html(data).show();
}
jQuery('#search_result .search_show').click(function() {
var text = jQuery(this).text();
var sid = jQuery(this).attr('id');
jQuery('#keysearch').val(text)
jQuery('#supplier_id').val(sid);
jQuery('#search_result').fadeOut(1000);
});
}
});
}
else
{
jQuery('#loading').css('display', 'none');
jQuery('#search_result').css('display', 'none');
}
});
});
I need help on this code. I want to dynamically prohibit a user from adding to cart if the requested stock item (Database) is less than his request (qty). Will appreciate, if I can know where I am wrong and probably someone correct it for me.
HTML FORM
<form action="cart.php?adm_id=<?php echo urlencode($patient["adm_id"]);?>" method="post" name="CartForm" target="_self">
<p>Product Name:<select name="prod_name" size="1" id="prod_name">
<option value="Select">Select</option>
<?php
while ($line = mysqli_fetch_array($query, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['prod_name'];?>"> <?php echo $line['prod_name'];?> </option>
<?php } ?>
</select></p>
<p>Quantity:<input type="number" name="qty" id="qty" size="30" required="required"/></p>
<input name="submit" type="submit" value="Add to Cart" id="btn"/> | <input name="reset" type="reset" value="Cancel" />
Ajax Code:
<script src="javascript/jquery-2.0.3.js">
</script>
<script type="text/javascript">
$(document).ready(function(ex) {
//$('#stock').load('pharmacy_summary.php');
$('#qty').change(function(){
var prod_name = $('#prod_name').val();
var qty= $('#qty').val();
$.ajax({
url: 'confirmStock.php',
data:{prod_name: prod_name, qty: qty},
success: function(e){
if(e == 'true'){
/*if the quantity is greater than the stock*/
alert('stock Item is lower to your request, reduce it');
$('#btn').prop('disabled', true);
}else{
$('#btn').prop('disabled', false);
} }
})});
});
</script>
PHP/MYSQLI Code:(ConfirmStock.php)
<?php require_once("/includes/db_connection.php");?>
<?php require_once("/includes/functions.php");?>
<?php
if(isset($_GET['prod_name'])){
$getProd = $_GET['prod_name'];
$getQty = $_GET['units'];
global $connection;
$val = "SELECT * FROM pharmacy_stock_tab WHERE prod_name='".$getProd."'";
$conf = mysqli_query($connection,$val);
$fetchVal = mysqli_fetch_array($conf);
$stock = $fetchVal['units'];
if($getQty>$stock){
return $stock;
}else{
return $stock;
}
}
?>
You must change the way you send response and the way you handle the response. change the code in ConfirmStock.php
change the return statements in following way
$result = array();
if($getQty>$stock){
$result['success'] = 'true';
$result['stock'] = $stock;
}else{
$result['success'] = 'false';
}
header('Content-Type: application/json');
echo json_encode($result);
die();
In Ajax success method
success: function(response){
if(response.success == 'true'){
/*if the quantity is greater than the stock*/
alert('stock Item is lower to your request, reduce it');
$('#btn').prop('disabled', true);
}else{
$('#btn').prop('disabled', false);
} }
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));
?>