Trying to check Unique Category Title Using Ajax and Jquery.
JQuery and ajax stuff
<script>
$(document).ready(function(){
$('#category_title').change(function(){
var category_title = $(this).val();
$.ajax ({
url : "ajax_calls.php",
method : "POST",
data : {category_title :category_title },
dataType: "text",
success:function(html)
{
$('#availablity').html(html);
}
});
});
</script>
ajax_call.php
<?php
include 'commands.php';
if (isset($_POST['category_title'])) {
$category_title = $_POST['category_title'];
$obj= new commands();
$result= $obj->check_category_title($category_title);
if (empty($result)) {
echo "<span class='status-available' style='color:green;'> Username Available.</span>";
} else {
echo "<span class='status-not-available' style='color:red;'>Category Already Exist</span>";
}
}
?>
HTML stuff
<form action="" method="post" id="my_form" enctype="multipart/form-data">
<div class="form-group">
<label class="tags">Category Title</label>
<input type="text" name="category_title" class="form-control" id="category_title"><span id="availablity"></span>
<p class="errorMsg"><?php if(isset($errorTitle) && $errorTitle== 1){echo "Field Required" ;} ?> </p>
</div>
</form>
MySQLi stuff
function check_category_title($category_title){
$stmt = $this->con->prepare("SELECT category_title FROM `nm_category` WHERE category_title='$category_title'");
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
I want to prevent user to submit if the category already exist in table else allow user to submit
Make changes like below in your php code :
if (empty($result)) {
echo "<span class='status-available' style='color:green;'> Username Available.</span>";
//show submit button if no data found
echo "<input type='submit' value='submit'>";
} else {
echo "<span class='status-not-available' style='color:red;'>Category Already Exist</span>";
//disabled button to prevent submit if category exist
echo "<input type='submit' value='submit' disabled='disabled'>";
}
Related
I load a form by click on a button with $("#btn").load("form.php") in index.php,
I want to avoid redirect the page to action file after submit and add an item in the table which is under the form.
my demo is on http://price.parag.website
<?php include "../connection.php" ?>
<h1>Add CPU</h1>
<form method="post" action="actions/cpu_action.php">
<label for="name">Name</label>
<input type="text" name="cpu_name" />
<label for="price">Price</label>
<input type="text" name="cpu_price" />
<input type="submit" value="Add" />
</form>
<?php
$sql = "SELECT id, cpu_name, cpu_price FROM cpu";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table>
<thead>
<tr>
<th>ID</th>
<th>CPU NAME</th>
<th>CPU PRICE</th>
</tr>
</thead>";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['cpu_name'] . "</td>";
echo "<td>" . $row['cpu_price'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
<h1>Add CPU</h1>
<form id="formupload" method="post" action="actions/cpu_action.php">
<label for="name">Name</label>
<input type="text" name="cpu_name" />
<label for="price">Price</label>
<input type="text" name="cpu_price" />
<input type="submit" value="Add" />
</form>
now we have to clear default action of form (i will use jquery)
$('#formupload').on('submit',function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $('#formupload').attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(result){
if(condition){}
else{}
}
})
})
Try this it will work
<button type="button" onclick="loadDoc()">Request data</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("table").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pageToPost.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("data1=bar&data2=foo");
}
</script>
This will take the response and update the element with id table with the repsonse, so make sure that it is in html.
In this programme i want to submit my form data if state name is already not present in database.if it is present in database then it gives mi alert that name already present and form not submited. but in the following programme if name is already present then then it gives alert message and form also not submitted. but if state name is not present then still it is not submitted my values(it is not calling form action="add_state_process.php"). i think i am wrong in returning true and false in javascript function.plz tell mi where i am wrong
<form name="addcategoryfrm" id="addcategoryfrm" onsubmit="return check_state();" action="add_state_process.php" method="POST">
<div class="formrow" style="margin-top:0px;height:80px;width:100%; padding-left:30%;">
<div class="txttitle" >Country Name</div>
<div class="txtinputouter1" style="padding-left:8px;">
<select name="country" id="country" class="required txtinput" value="">
<option value="">--- Select Country --- </option>
<?php
include("../config/database.php");
$query="SELECT * FROM `country`";
$result = mysql_query($query) or die(mysql_error());
echo $query;
//$result2 = mysql_fetch_array($result);
$row1=mysql_num_rows($result);
echo $row1;
while($numrow=mysql_fetch_array($result))
{ ?>
<option value=" <?php echo $numrow['id']; ?> ">
<?php echo $numrow['name']; ?>
</option>
<?php } ?>
</select>
</div>
</div>
<div class="formrow" style="margin-top:0px;height:80px;width:100%; padding-left:30%;">
<div class="txttitle">State Name </div>
<div class="txtinputouter1" style="padding-left:1%;">
<input type="text" class="required txtinput" name="state" id="state" class="categoryname" onblur=";"/>
</div>
</div>
<div class="txtinputouter1" style="padding-left:43%;padding-top:10px;">
<input type="submit" class="subbutton" value="Submit"/>
</div>
<div id="demo"></div>
</form>
////function call
<script>
function check_state()
{
valid=false;
var txtarea12 = document.getElementById("country").value;
var name = document.getElementById("state").value;
//var valid=true;
//alert(name);
//alert(txtarea12);
//$name = name;
$.ajax({ type: "GET",
url: 'ajax-state-model.php',
data: { name: name,
countryid:txtarea12
},
success: function(result)
{
if (result == 1)
{
alert("state name already present");
var txtarea = document.getElementById("state");
txtarea.value="";
txtarea.focus();
valid=false;
}
else
{
valid=true;
}
},
error: function(err)
{ alert(err); }
});
return valid;
}
</script>
///function ajax call
<?php
session_start();
if(isset($_SESSION['username1']))
{
include("../config/database.php");
$name=$_GET['name'];
$countryid=$_GET['countryid'];
$query="select * from state where country_name=$countryid && state_name='$name'";
$result = mysql_query($query) or die(mysql_error());
//echo $query;
$rows=mysql_num_rows($result);
if($rows>0)
{
echo 1;
}
else
{
echo 0;
}
}
?>
I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.
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));
?>
I have a table with records from a database which is dynamically filled.
<table>
<tr>
<td>name
</td>
<td>surname
</td>
...
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['Name'];?>
</td>
<td><?php echo $row_Recordset1['Surname'];?>
</td>
...
<td align="center">
<form name="form" action="novi.php">
<input name="check" type="radio" value="da">Да
<input name="check" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik" value="Испрати"/>
</form>
</td>
</tr>
<?php } while($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
And than I'm using J Query to create an AJAX call to another page which will run the query.
<script>
$('#klik').click(function() {
var check = $("input[name='check']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik').prop('value', 'Грешка');
setTimeout("$('#klik').prop('value', '.')",500);
setTimeout("$('#klik').prop('value', '..')",1000);
setTimeout("$('#klik').prop('value', '...')",1500);
setTimeout("$('#klik').prop('value', 'Испрати')",2000);
}
});
This is working OK if there is only one row in the table.
What I don't know how to do is, to make the script store all the generated CHECKED radio buttons in an array or something, plus all the ID's of the records from the database and send them to another page where according to their ID's a query will update the database..
<?php
if ($_POST['id'] != NULL) {
if ($_POST['check'] == "da") {
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 1 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}else if ($update === false){
echo 'Error!!!';
}
}
elseif ($_POST['check'] == "ne")
{
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 2 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}
else if ($update === false){
echo 'Error!!!';
}
}
} else {
echo 'Error!!!';
}
?>
Thanks!
P.S. I'm a noob in JQuery and a beginner in PHP...
UPDATE:
I did change some things. And now the values are shown as I want, when I click the button without a selection I'm getting the error message in the ELSE part of the JQuery code in the proper button. But no matter which button I click (if the table is populated with 3 records from the database, there are 3 buttons) only the first row from the table is updated in the database.
<form name="form" action="novi.php">
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="da">Да
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik<?php echo $row_Recordset1['id_korisnici'];?>" value="Испрати"/>
</form>
The JQuery:
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').click(function() {
var check = $("input[name='check<?php echo $row_Recordset1['id_korisnici'];?>']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Error');
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '.')",500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '..')",1000);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '...')",1500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Send')",2000);
}
});
Make each group of radio buttons have a unique name but the same class. Then you can iterate through them using jQuery:
var radioVals = new Array();
var i = 0;
$(".radioButtonClass:checked").each(function() {
radioVals[i] = $(this).val();
});
Then just pass the array in your ajax call.