How to toggle the data fetched from AJAX? - javascript

I have this code in which I am trying to show and hide the data on clicking a product number and the data is being fetched from database through AJAX. I want the data to be shown beneath the desired row. I want to put the data in tbody and show it on clicking its product number.
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<tr><td align="center"><?php echo $row['FONumber']; ?></td></tr>
<tbody id='sd'<?php echo $p; $p++; ?>></tbody>
<?php }
}
Javascript and AJAX:
$(function(){
$('#hover1').on({
mouseenter:function(){$(this).css("background","grey")},
mouseleave:function(){$(this).css("background","white")}},'tr');
});
// number of tds
var c = $('#hover1').find('td').length;
var id = document.getElementById("hover1");
for(var i = 0; i < c; i++){
id.rows[i].onclick=(function(){
var a = $(this).find('td:eq(0)').text();
$.ajax({
url: 'printpo1.php',
type: 'post',
data: {fo:a},
success: function(data){
$('#name').html(data);
}
});
$('#sd'+i).toggle();
alert('#sd'+i);
});
}
So far the data I am trying to fetch is showing in the tbody of the first row. Any help will be really appreciated.

Related

How can I get my information to display into a link <a href> or a <div>?

The issue I am having is that I need the search results to be displayed in a link or a . Right now they display into a text input field. When I try to change it to a link or div no text is generated. I am almost certain it has to do with the java/jquery script I have. The script I am using is an open source script that I need for simple reasons.
What I have tried is changing the element in which the script calls for from an input to a div or a href. I have googled and tried to find some sort of reference to which the script selects what elements to display the code into and the only thing I can identify as being the problem is, "userid = ui.item.value; // selected id to input".
index.php - Script
<script type="text/javascript">
$(document).ready(function(){
$(document).on('keydown', '.username', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var name = response[0]['name'];
var displayid = response[0]['displayid'];
document.getElementById('name_'+index).value = name;
document.getElementById('displayid_'+index).value = displayid;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function(){
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='username' id='username_"+index+"' placeholder='Enter username'></td><td><input type='text' class='name' id='name_"+index+"' ></td><td><input type='text' class='displayid' id='displayid_"+index+"' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
</script>
index.php - Html
<div class="container">
<table border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Search</th>
<th>Name</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<tr class='tr_input'>
<td><input type='text' class='username' id='username_1' placeholder='Enter username'></td>
<td><input type='text' class='name' id='name_1' readonly></td>
<td><input type='text' class='displayid' id='displayid_1' readonly></td>
</tr>
</tbody>
</table>
<br>
<input type='button' value='Add more' id='addmore'>
</div>
getDetails.php
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM item_template WHERE name like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['entry'],"label"=>$row['name']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM item_template WHERE entry=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['entry'];
$name = $row['name'];
$displayid = $row['displayid'];
$users_arr[] = array("entry" => $userid, "name" => $name,"displayid" => $displayid);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I except the selector is wrong in the script, where it selects where to copy the text to.
You just need to use innerHTML instead of value.
document.getElementById('name_'+index).innerHTML = name;
document.getElementById('displayid_'+index).innerHTML = displayid;
and change the input tag to div tag. You might want to read more about innerHTML.

DIV not being created from PHP when doing AJAX call

I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});

Ajax dropdown call to function can't show me all values

Hello I'm using ajax to call on-change drop-down list and select all value from database into table row format but it only show me the last record from database into table row.
I have three rows in database related to one select from drop-down list and I want to show all three rows into table row format. My code is
$(document).ready(function(){
$('#location').change(function(){
$.ajax({
url:'location.php?location=' + $(this).val(),
type: "get",
timeout:10000,
dataType: 'json',
success: function(data){
document.getElementById("material_name").value=data.material_name;
document.getElementById("material_quantity").value=data.product_quantity;
},
error:function(){
}
});
});
and location.php page is as:-
<?php
require_once("shine_class.php");
$s = new shine;
$s->connection();
$location = $_REQUEST['location'];
$query ="SELECT * from material_used where product_name = '$location' ";
$query1=mysql_query($query);
while($row = mysql_fetch_array($query1))
{
$result1=$row['material_name'];
$result2=$row['product_quantity'];
}
echo json_encode(array("material_name"=>$result1,"product_quantity"=>$result2));
?>

is there a way to populate other textbox when onchange?

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>

Live table edit display field(s) from other mySQL tables

I have a table that works like this: http://www.datatables.net/examples/api/editable.html without the header sorting, page changing, and search. I have another functionality that allows me to add a row. All of this is done on the same page. The data is drawn directly from a database. I wrote the code generic so it could be used for any table I want to display.
However, I have came across a problem. Let's say an end-user wants to see a list of houses. This list would be drawn from a houses database. Each house has an owner. There is also an owners table. Each owner has an id (primary_key). In the houses table the owner field uses the owner's id to identify the proper owner. Here is where the problem arises. Once the data from the houses table is displayed the owner, for instance, shows up as an id number. Obviously, to the end-user it either is meaningless or at least annoying. I would like to have, in this case the owner's name, the field that is in question to show instead of a "seemingly" meaningless field. I'm posting the relevant code for my predicament.
Also, can I change mySQL booleans through jQuery? What I mean by that is if, for example, a house is not up for rent so the for_rent flag is set to 0 for FALSE. The table will show 0, as that is what is in the table. Can I change that through jQuery? (Find the 0s or 1s and make them say true or false? Any suggestions as to a direction for answering these questions would be great. Thanks.
Here is the relevant code:
PHP to display table:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
while ($row = mysqli_fetch_array($result))
{
$rowid = $row[$fields[0]];
echo "<tr class='edit_tr' id='".$rowid."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td' data-field='".$f."'><span id='".$rowid."' class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox' id='".$rowid."' data-field='".$f."'/> </td>";
}
$rowid++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
$recordid = $rowid;
//close connection
mysqli_close($con);
}
jQuery to live edit table:
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var table = $('body').attr('id');
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = {table:table, id:id, field:field, text:text};
if (field != text)
{
$.ajax({
type: "POST",
url: "classes/table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
jQuery to live add row:
$(document).ready(function()
{
$(".add").click(function()
{
var fieldArray = [];
var $table = $("#table");
var $lastRow = $table.find("tr:last");
var $dataFields = $lastRow.find("td");
$dataFields.each(function() {
fieldArray.push($(this).attr("data-field"));
});
$("#table").each(function()
{
var $table = $(this);
var id=$('#table tr:last').attr('id');
var $tr = $("#table").children('tr');
var tablename = $('body').attr('id');
var n = $('tr:last td', this).length;
var tds = '<tr class="edit_tr" id="' + id++ + '">';
for(var i = 0; i < n; i++)
{
tds += '<td class="edit_td" data-field="' + fieldArray[i] +
'"><span id="'+ id +'" class="text"> </span><input type="text" class="editbox" id="' +
id + '" data-field="' + fieldArray[i] + '"/> </td>';
console.log('id: ' + id);
}
tds += '</tr>';
var dataString = {table:tablename, id:id};
if($('tbody', this).length > 0)
{
$('tbody', this).append(tds);
$.ajax({
type: "POST",
url: "classes/table_new_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}else {
$(this).append(tds);
}
});
});
});
you will probably want to extend your generic function for generating the html table to include a joined db table if necessary, though that would get messy, so, create a new function for when you need to join 2 db tables.
The sql for retrieving the owners name into the list of houses would go something like (with a guess at what your field names are):
select a.housename,a.street,a.for_rent,b.name from houses a, owners b where a.owner_id=b.id

Categories

Resources