am new with php.
Am creating a form with a dropdown list option from my db, i want this option to display the rest of the details in the text field when a user select any.
In the DB i have id, employee_name, employee_salary, employee_age.
This my Html file
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript" src="script/getData.js"></script>
</head>
<body>
<select id="employee" class="form-control" >
<option value="" selected="selected">Select Employee Name</option>
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee";
$resultset = mysqli_query($conn, $sql);
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["employee_name"]; ?></option>
<?php } ?>
</select>
<br>Craft 1<br>
<input type="text" id="craft_1_points" name="craft_1_points" value="">
<br>Craft 2<br>
<input type="text" id="craft_2_points" name="craft_2_points" value="">
<br>Craft 1<br>
<input type="text" id="craft_3_points" name="craft_3_points" value="">
<br>Craft 2<br>
<input type="text" id="craft_4_points" name="craft_4_points" value="">
</body>
</html>
</center>
<?php include('include/footer.php');?>
I have managed to add the names to the drop down list which is working and i used ajax and java to link.
But when i select any option e.g. Tiger Nicxin it supposed to fill the text field with the rest info of the selected name, id,age and salary. It's not working
please what do i have to do.
JS file
$(document).ready(function(){
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'getlist.php',
dataType: "json",
data: dataString,
cache: false,
success: function(empData) {
if(empData) {
$("#errorMassage").addClass('hidden').text("");
$("#recordListing").removeClass('hidden');
$("#empcraft_1_points").val(empData.id);
$("#empcraft_2_points").val(empData.employee_name);
$("#empcraft_3_points").val(empData.employee_age);
$("#empcraft_4_points").val("$"+empData.employee_salary);
} else {
$("#recordListing").addClass('hidden');
$("#errorMassage").removeClass('hidden').text("No record found!");
}
}
});
})
});
Ajax file
<?php
include_once("include/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, employee_name, employee_salary, employee_age
FROM employee
WHERE id='".$_REQUEST['empid']."'";
$resultSet = mysqli_query($conn, $sql);
$empData = array();
while( $emp = mysqli_fetch_assoc($resultSet) ) {
$empData = $emp;
}
echo json_encode($empData);
} else {
echo 0;
}
?>
please help me with solution
in ajax your datatype changed to dataType: "json" and your id was wrong.
and include your DB connection in a index file or main file
you js file:
$(document).ready(function(){
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'getlist.php',
dataType: "json",
data: dataString,
success: function(empData) {
if(empData) {
$("#errorMassage").addClass('hidden').text("");
$("#recordListing").removeClass('hidden');
$("#craft_1_points").val(empData.id);
$("#craft_2_points").val(empData.employee_name);
$("#craft_3_points").val(empData.employee_age);
$("#craft_4_points").val("$"+empData.employee_salary);
} else {
$("#recordListing").addClass('hidden');
$("#errorMassage").removeClass('hidden').text("No record found!");
}
}
});
})
});
Related
First, I will summary my demo for you: I have a form for me to type an api link and type of the chart I want to draw from my api link. After that, I will click the button to create chart and insert my input to MySQL database to show it on screen. Each chart have a button for me to delete it if I want.
Everything worked fine except delete funtion to delete my input from database. When I press delete button, it's only delete in html, not delete in my database. Can you help me? Thank you!
Here is my code:
My input form:
<!--HTML Form input-->
<div class = "login-block">
<form id="form1" style="display: block" method="POST" action="chart_test.php">
<!--Input link api-->
<b>Link: </b><input type="text" id="link" name="apilink"><br>
<br>
<!--Chart Type-->
<b>Chart Type:</b>
<label class="custom-select">
<select id="chartType" name="chartType">
<option value="">Select</option>
<option value="pie">Pie Chart</option>
<option value="column">Column Chart</option>
<option value="bar">Bar Chart</option>
</select>
</label>
<br><br>
<!--Button create chart-->
<div class ="wrapper">
<button type="submit" name="create" onClick="drawChart()">Create</button>
<br><br>
</div>
</form>
</div>
Insert input to database and show to screen:
<!--insert form data to mysql-->
<?php
$con = mysql_connect("localhost","root","123456");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysql_select_db("activiti_report");
//check data when first load page to not showing notice error
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$apilink = $_POST["apilink"];
$chartType = $_POST["chartType"];
}
if(isset($_POST['create'])) {
$sql = "INSERT INTO chartinfo (link, typeChart) VALUES ('$apilink', '$chartType')";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
Query database to show chart on screen and the button with script to delete:
<?php //query data from database
$result = mysql_query("SELECT * FROM chartinfo");
?>
<?php //while loop to read data from query result
while($db_field = mysql_fetch_assoc($result)):
?>
<?php //unique chartId for not the same to show more chart
$idChart = 'chartContainer_' . uniqid();
?>
<!--Show chart from database-->
<br>
<div class = "chart-block">
<?php // 2 lines about chart infomation
echo ("<b>API Link:</b> "); print $db_field['link'] . "<BR>";
echo ("<b>Chart Type:</b> "); print $db_field['typeChart'] . "<BR>";
?>
<!-- The <div> and <script> to show the chart -->
<div id="<?=$idChart?>" style="height: 360px; width: 70%;"></div>
<script>
$(document).ready(function() {
var dataPointsA = []
var text = document.getElementById('chartType')
var strChart = text.options[text.selectedIndex].value
$.ajax({
type: 'GET',
url: "<?php echo $db_field['link']?>", //assign URL from query result field
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
label: field[i].name,
y: field[i].value
});
}
var chart = new CanvasJS.Chart("<?=$idChart?>", {
title: {
text: "Activiti Report"
},
data: [{
type: "<?php echo $db_field['typeChart']?>", //assign type of chart from query result field
name: "chart",
dataPoints: dataPointsA
}]
});
chart.render();
}
});
});
</script>
<br>
<!--Button to delete the chart and row in database-->
<button type="submit" name="delete" onClick="removeParent(this.parentNode)">Delete</button>
<!--Script remove <div> contain the chart-->
<script>
function removeParent(parent) {
parent.remove();
}
</script>
<!--Script delete form data from mysql-->
<?php
if(isset($_POST['delete'])) {
$sql = "DELETE FROM chartinfo (link, typeChart) WHERE link ='" .$db_field['link']. "' AND typeChart = '" .$db_field['link']. "'";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
I know I should use mysqli_* instead mysql_* but this is just a demo for me to understand PHP, I learned it only a few days. Sorry for a lot of code but I think I should show to you to understand what I am doing.
Thank you very much!
Your delete button trigger its action from the js code not the php code. It only remove from the view but will appear on reload. You can use ajax in your remove function or use a delete link instead of button
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php",
data: {id:id},
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
<script>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php?id="+id,
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
</script>
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
There Should be an Input textbox, If user writes any text it should display dropdown list of customer names
<script>
function custlist() {
$.ajax({
url: "custlist.php",
success: function(result) {
$("#customerlist").html(result);
}
});
}
function showCustomers(str) {
$.ajax({
type: "GET",
url: "customerlist.php",
data:'q='+str,
success: function(result) {
$("#customerlist").html(result);
}
});
}
</script>
<input type="text" oninput="showCustomers(this.value)" placeholder="Search here" name="CustomerNo" />
<select name="Cno" id="customerlist" onfocus="custlist()">
<option value="">Customer Name</option>
</select>
custlist.php
<?php
$sql2 = 'SELECT Customer_Name as Cname,No from customers order by Customer_Name';
$result2 = mysqli_query($connection, $sql2);
if (mysqli_num_rows($result2) > 0) { ?>
<option value="">Customer Names</option>
<?php // output data of each row
while($row2 = mysqli_fetch_assoc($result2)) { ?>
<option value="<?php echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?>
</option>
<?php } ?>
<?php } ?>
customerlist.php
<?php
$q = $_REQUEST["q"];
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$sql2 = "SELECT Customer_Name as Cname,No from customers where Customer_Name like '".$q."%s' order by Customer_Name";
$result2 = mysqli_query($connection, $sql2);
if (mysqli_num_rows($result2) > 0) { ?>
<option value="">Customer Names</option>
<?php // output data of each row
while($row2 = mysqli_fetch_assoc($result2)) { ?>
<option value="<?php echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?>
</option>
<?php } ?>
<?php } ?>
<?php } ?>
I am getting the data in my dropdown, but I want that if I write something in text box then automatically it shows dropdown with matching that characters.
And one more issue I have...
2nd Issue:- When I type "abd" first it shows customer names starting with "abd" but automatically it shows next names starting with "ab" then "a" then empty..
Why is that?
Thanks in advance.
Instead of
Javascript:
$.ajax({
type: "GET",
url: "customerlist.php",
data:'q='+str,
success: function(result){
$("#customerlist").html(result);
}
});
And php:
<?php
$q = $_REQUEST["q"];
Try doing this Javascript:
$.ajax({
type: "POST",
url: "customerlist.php",
data: {q: str},
success: function(result){
$("#customerlist").html(result);
}
});
And php:
<?php
$q = $_POST['q'];
Hope this helps!
i am using json for like button. when users clicks it correctly increases the like count and stores in database for corresponding id but it shows increment for all ids in browser which is wrong. i want to display for only id where users has liked but it shows for all.
test url is http://way2enjoy.com/app/check/test/indexp.php
indexp.php file is
<?php
include('/home/xxx/con.php');
$query="Select * from users_jokes order by id desc limit 10";
$result=mysql_query($query);
?>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr('action');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden").value;
$.ajax({
url: url,
data:{
'action':'addComment',
'comment':comment,
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
'action':'getLastComment',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
$('#jokes_comment').val("");
console.log(result[0].description);
$("#header ul").append('<li>'+result[0].description+'</li>');
},
error: function(){
alert('failure');
}
});
},
error: function(){
alert('failure');
}
});
// return false so the form does not actually
// submit to the page
return false;
}
var ajaxLike=function()
{
var joke_id=document.getElementById("joke_id_hidden").value;
// setup the ajax request
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'increment_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'display_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
console.log(result);
$("label[for='like_counter']").text(result.likes);
},
error: function(result)
{
alert("error 2");
},
});
},
error: function()
{
alert('failure');
}
});
return false;
}
</script>
<p>commnet list</p>
<div id="header">
<ul id="commentlist" class="justList">
<?php
$query="Select * from comment where joke_id='2'";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)){
$cont = $data['description'];
?>
<li><?php echo $cont;
?></li>
<?php
}
?>
</ul>
</div>
<?php
?>
<form method="post" action="processkk.php" onSubmit="return ajaxSubmit(this);">
<input type=text id="jokes_comment" name="jokes_comment">
</input>
<input type="submit" value="comment">
</form>
</body>
</html>
<?php
while($data = mysql_fetch_array($result)){
$id = $data['id'];
$cont = $data['content'];
$likes = $data['likes'];
?>
<p><?php echo $cont;?></p>
<input type="hidden" value="<?php echo $id ;?>" id="joke_id_hidden">
<p><button onClick="ajaxLike();">Like</button> <label for="like_counter"><?php echo $likes;?></label></p>
<?php }
?>
</body>
</html>
likeskk.php
<?php
include('/home/xxxxxxx/con.php');
$action=$_POST['action'];
if($action=="increment_like")
{
$joke_id=$_POST['joke_id'];
$query="update users_jokes set likes =likes+1 where id='".$joke_id."'";
$result=mysql_query($query);
// setup our response "object"
$retVal=array("Success"=>"true");
print json_encode($retVal);
}
if($action=="display_like")
{
$joke_id=$_POST['joke_id'];
$query = "select likes from users_jokes where id = '$joke_id'";
$qry = mysql_query($query);
while($rows = mysql_fetch_array($qry)){
$likes = $rows['likes'];
}
header('Content-Type: application/json');
// print json_encode(array('foo' => 'bar'));
print json_encode(array('success'=>'true','likes'=>$likes));
}
?>
when i click on one like all like increases. when i post comment on one id it appended and displays in all id
Copy and paste it.
<html>
<head>
<script>
function clickCounter(element)
{
element.value = parseInt(element.value) + 1;
}
</script>
</head>
<body>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
</body>
</html>
Because you are using the same id. id must be unique
<input type="hidden" value="4638" id="joke_id_hidden">
Rather than using a hidden input for each entry you could use a dataset on the button itself with the corresponding ID. When the button is clicked the javscript function could read that dataset value and use that in the ajax POST request. So, as an example:
<!doctype html>
<html>
<head>
<title>Like the jokes...</title>
</head>
<body>
<form id='bttns'>
<?php
/* pseudo generate some jokes with buttons and labels to emulate your page */
for( $i=1; $i < 20; $i++ ){
$random=rand(1,20);
echo "
<p>Funny joke...[{$i}]</p>
<input type='button' value='Like' data-id='$i' />
<label class='counter'>{$random}</label>";
}
?>
</form>
<script type='text/javascript'>
var col=document.querySelectorAll('#bttns input[type=\"button\"]');
for( var n in col )if(col[n].nodeType==1)col[n].onclick=function(e){
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
var label=el.nextSibling.nextSibling;
var id=el.dataset.id;
label.innerHTML=parseInt( label.innerHTML )+1;
alert( 'use ajax to POST this id: '+id );
}
</script>
</body>
</html>
I should add perhaps that the ajax callback function would be the place to update the value of likes for each joke rather than as here - it's just example code showing how you could do away with hidden fields and the problem of duplicate ids.
I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
And, another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my view.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.
here's my code. I'm new to php. so sorry in advance.
I actually want to check my input in txtbarcode and if it is existing in my database I would like to populate the txtdescription but I don't know how to do it or is it even possible?
<?php
$barcode = $_POST['txtbarcode'];
$query = "SELECT * FROM product WHERE product_id = '$barcode'";
$query_exe = mysql_query($query);
$chk_query = mysql_num_rows($query_exe);
if($chk_query > 0)
{
$row = mysql_fetch_assoc($query_exe);
?>
<th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>" style="width:80px"/></th>
<th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>" style="width:100px"/></th>
<?php
}
?>
You can do this using JQuery Ajax. Just using the change listener on the barcode field, it will send an ajax call to the check_barcode file - which will query the table and echo the data you want. The result will then be placed into the other textfield via JavaScript :).
The following is a separate PHP file.
<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------
if (isset($_POST['barcode'])) {
$query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
$row = mysql_fetch_assoc($query);
echo $row['product_name'];
}
}
?>
The following is your HTML and JavaScript code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#txtbarcode').change(function() {
var barcode = $(this).val();
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
success: function(result) {
$('#txtdescription').val(result);
}
});
});
});
</script>
<input type="text" name="txtbarcode" id="txtbarcode" />
<input type="text" name="txtdescription" id="txtdescription" />
UPDATE: Returning more data, and populating extra fields.
You'll need you echo a json array from the php script which contains both of the values.
For example:
echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));
and then within the JavaScript
<script>
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
dataType: 'json',
success: function(result) {
$('#txtdescription').val(result.product_name);
$('#unitofmeasure').val(result.unit_measure);
}
});
</script>