Displaying data as a table using $.ajax() and jQuery - php

I'm new to jQuery and PHP.
I'm developing a web page to display a set of records taken from a database. Here I have used PHP and jQuery.
I need to display a set of records as a table. Data is retrieved from a MySQL database using php. Set of rows is passed to the html page as a string using json_encode().
The problem is that I can't display those data in a table row by row. I'm using a table created with <div>. So I need to know how to display this string of data row by row and separating the value for each column.
Here is what I have done to display only one row, but the data is not displayed as a table. No compile error either. I need help to extend this to display multiple rows too.
demo.html (page I'm going to display the records):
<div class="table">
<div class="headRow">
<div class="cell">ID</div>
<div class="cell">First Name</div>
<div class="cell">Last Name</div>
<div class="cell">Age</div>
<div class="cell">Class</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'beta.php' ,
data:"",
dataType: 'json',
success:function(data){
var elementArray = new Array(); //creating the array
elementArray = data.split(""); //splitting the string which was passed using json_encode()
var id = elementArray[0]; //passing values corresponding to the columns
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
$("<div>", { //creating a new div element and assiging the value and appending it to the column 1
"class":"cell",
"text":id
})
.appendTo("document.body");
$("<div>", { //cloumn 2 value
"class":"cell",
"text":fnam
})
.appendTo("document.body");
$("<div>", { //cloumn 3 value
"class":"cell",
"text":lname
})
.appendTo("document.body");
$("<div>", { //cloumn 4 value
"class":"cell",
"text":age
})
.appendTo("document.body");
$("<div>", { //cloumn 5 value
"class":"cell",
"text":grade
})
.appendTo("document.body");
}
});
});
</script>
</div>
</div>
demo.php (retrieving data from the database):
$result = mysql_query("SELECT * FROM student WHERE StuId=1",$con) or die (mysql_error());
$resultArray = mysql_fetch_row($result);
echo json_encode($value);
If someone can help me it would be a great.

try this one....
var id = elementArray[0];
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
then create table using these values something like this....
$("<table>").appendTo("document.body");
$("table").html("<tr><td>"+id +"</td><td>"+fname +"</td><td>"+lname +"</td><td>"+age +"</td><td>"+grade +"</td></tr>);

Here is a Jfiddle, if you use .html and append to a empty table on your page you can append the var contents returned from your ajax query just the same
http://jsfiddle.net/L4G79/1/
this your code will look something like
var id = elementArray[0]; //passing values corresponding to the columns
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
$("table").html("<tr><td>"+id +"</td><td>"+fname +"</td><td>"+lname +"</td><td>"+age +"</td><td>"+grade +"</td></tr>");

Related

PHP AJAX HTML: changing unique table data in foreach loop

I'm new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.
I have a PHTML template which looks like the following:
<?php
$content = "";
// creates data selector
$content .= "
<form id = select_data>
<select id = data_selection>
<option value = data1>Data 1</option>
<option value = data2>Data 2</option>
<option value = data3>Data 3</option>
<option value = data4>Data 4</option>
</select>
<input id = selected_data type=submit />
</form>";
// creates table header
$content .= "
<tr>
<th>Data</th>
</tr>";
$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
$object = // instantiate object by array_id, pseudocode
$object_data = $object->getData('default-data'); // get default data to display
// create table item for each object
$content .= "
<tr>
<td><p>$object_data</p></td>
</tr>";
}
print $content;
?>
This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag.
And then I have some Javascript which looks like the following:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){ // get selected data type
e.preventDefault();
var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected},
success: function(data){
$("p").html(data); // replace all <p> tag content with data
}
});
});
});
</script>
This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:
<?php
$attribute = false;
if (isset($_POST['data_selected'])){
$data = $_POST['data_selected']; // assigns variable out of ajax data
$object = //instantiate object, again pseudocode
$object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
echo $object_data;
}
?>
The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.
I tried to identify each <p> tag with the following:
<td><p id = $array_id>$object_data</p></td>
And then creating a new Javascript variable out of the array ID:
var p_tag_id = <?php echo $array_id; ?>;
And finally making the Ajax success function target element ID's based on var p_tag_id:
$("#" + p_tag_id).html(data);
While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.
How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?
You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.
You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):
var num = data_selected.slice(-1) - 1;
(Subtract 1 because the table rows are zero-indexed)
Then, in the AJAX code block's success function:
$('table tr').each(function(i,v){
if (i == num){
$(v).find('td').find('p').html(data);
}
});
The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob's yer uncle.
I haven't tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.
I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:
<td><p id = $array_id>$object_data</p></td>
Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:
$("p").each(function() {
var array_id = $(this).attr("id");
And finally I made the Ajax success target elements based on their ID:
$("#" + array_id ).html(data);
Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){
e.preventDefault();
var data_selected = $("#data_selection :selected").val();
$("p").each(function() {
var array_id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected, array_id: array_id},
success: function(data){
$("#" + array_id).html(data);
}
});
});
});
});
</script>

Getting ID value of clicked row - jquery

ok .. quick overview.
I have a table and each row has the ID attribute value assigned based on the ID form the db record
I have a click event that shows / hides a div and I want the data it displays
in that div to be based on the results from the DB for that corresponding ID value
Here is my table code showing the ID
<td class="hidden-xs">
<a data-toggle="toggle" href="#comp_info" class="showcompinfo" id="<?php echo $complistr['company_id'];?>">
<?php echo $complistr['registered_office_address'];?>
</a>
</td>
This is where I want the data displayed
<div class="panel-heading">
<i class="fa fa-building" style="color:orangered"></i>
<span id="showcompname"></span>
</div>
Here is the jquery code
$(document).ready(function () {
$('#comp_info').hide();
$('.showcompinfo').click(function () {
var id = $('.showcompinfo').attr('id');
$('#comp_info').toggle();
var companyid = id;
var dataString = 'companyid=' + companyid;
$.ajax({
type: 'POST',
url: '../inc/dataforms/complist.php',
data: dataString,
success: function (result) {
$('#showcompname').html(result);
}
});
});
});
Here is the PHP code for the query
include('../config.php');
if (!empty($_POST['companyid'])) {
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc, "SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if ($result) {
echo $result['name'];
}
}
Please dont say .. your code is open to SQL injection .. i've said before its on a closed system with no external access and the people using it can barly use a PC
All I want it to do is to display the company name in the showcompname span box
If possible am I also able to display different result data in different divs ?
To retrieve the ID from the clicked <a> tag, in your jQuery code change this line:
var id = $('.showcompinfo').attr('id');
For this one:
var id = $(this).attr('id');
That way you are retrieving the id attribute from the element that was the target of the click event.
Your original code was retrieving an array of ids of all elements with the class showcompinfo.
Your problem lies in the selector for the id, var id = $('.showcompinfo').attr('id');.
You are selecting every showcompinfo in the page.
You would be better off by using this in that selector.
This would correctly select your id, based off the clicked td.
var id = $(this).attr('id');

show only latest rows from a database with jquery

I've been trying to retrieve new rows from a databse with ajax. like the sort of thing that happens on facebook chat. What I've been doing is I get the last ten rows from the database with ajax every two seconds and try to show the ones the user hasn't seen. I have two columns, id and name. I created an onordered list and set each li elements id to the id from the database. each li is for a row. then I try to get the id of the last li element and check if the id from the database is greater, if it is then append a new li containing the id and name. but for some reason, it just appends the whole 10 rows every two seconds. what have I done wrong?
this is the code I'm using.
<ol id="output"><li id="1">test</li></ol>
<script id="source" language="javascript" type="text/javascript">
function reloadw()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var lastId = $('ol#output li').attr('id');
var id = row[0];
var vname = row[1];
if(id > lastId){
$('#output').append("<li id="+id+"><b>id: </b>"+id+"<b> name: </b>"+vname+"</li>");
}}
}
});
} setInterval(reloadw,2000);
this is what I use in retrieving data from the db
$result = mysql_query("SELECT * FROM $tableName ORDER BY id");
$data = array();
for($i=0;$i<=9;$i++){
$row = mysql_fetch_row($result);
$data[] = $row;
}
echo json_encode( $data );
If you take out issue where you are fetching the data, another issue you have is in your javascript code.
Change
var lastId = $('ol#output li').attr('id'); //will always fetch the first li's id
to
var lastId = $('ol#output li:last').attr('id');
With the lastId selection code that you have, it will always fetch only the id of the first one and your comparison id > lastId will always be true except for the first element's id. So you end up appending even if that record has been already added before.
But ideally you should do this logic at the server to get only the data to be presented.
If you want to sort last result from database this is very simple, you can try this code in your sql: $result = mysql_query("SELECT * FROM $tableName ORDER BY id DESC");
var lastId = $('ol#output li').attr('id');
That line will always lookup the first element in the list, whereas you probably are looking for the last. Try replacing the line with:
var lastId = $('ol#output li').last().attr('id');
You could write your JavaScript code like this.
<script>
var seen = new Array();
function reloadw(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows){
rows.forEach(function(row){
if(seen.indexOf(row.id) == -1){
$('#output').append("<li id="+row.id+"><b>id: </b>"+row.id+"<b> name: </b>"+row.name+"</li>");
seen.push(row.id);
}
});
} setInterval(reloadw,2000);
</script>

Get just one of a divs IDS with jQuery

I have a div with more than one ID and I need to get each ID separately and send both variables off to a PHP file. I feel this would be the simpler option if achievable but the other option is to split the two IDS on the server side with PHP once the ID has been sent to it by jQuery. One ID is the timestamp the other the ID in the database.
HTML div example:
<div style="margin-bottom:10px;" id="1000003 2012-09-04 21:24:32" class="newsItem"></div>
The 1000003 is the ID i need to get into one separate variable and the rest is the timestamp I need in another separate variable.
The jQuery I have:
window.setInterval(function(){
//scripting here
var obj = $('.newsItem:first').map(function(_, elem){
return elem.id;
});
var ids = $.makeArray(obj); //variable of IDS
$.get("AJAX/get_feed_updates.php",{ ids: ids },function(result){
$("#newsFeed").html(result);
});
}, 5000);
The PHP file just puts the ID into a variable and queries the database with it.
Store one in the DATA attribute. Here is another reference to how its used.
Is this right?
window.setInterval(function(){
//scripting here
var theId = $('.newsItem:first').attr('id');
var a = theId.split(' ');
var theId = a[0];
var theStamp = a[1]+''+a[2];
$.get("AJAX/get_feed_updates.php",{ ids: theId },function(result){
$("#newsFeed").html(result);
});
}, 5000);
You should use data attribute. Then you can do something like this..
<div data-timestamp="1000003 2012-09-04 21:24:32" id="myId"></div>

to get value from database table into select box

i m creating a combo box which gets value from mysql database table.
here is a sample code which i m implementing but it will not populates selectbox values.
mydata +='<div class="content nodisplay"><div class="row"><div class="label" style="font-size:22px;">Subject</div><div class="data">
<select id="fillsubject" name="fillsubject">';
$.post(document.URL,qstring,function(data){
var subjects = $(data).filter('.subjects');
$.each(subjects,function(index,value){
var subid = $(this).attr('id');
var subname = $(this).text();
mydata += "<option value='"+subid+"'>"+subname+"</option>";
//mydata += "<option value='english'>english</option>";
});
});
mydata +='</select></div></div></div>';
var mydata +='<div class="content nodisplay"><div class="row"><div class="label" style="font-size:22px;">Subject</div><div class="data"><select id="fillsubject" name="fillsubject"></select></div></div></div>';
$.post(document.URL,qstring,function(data){
var subjects = $(data).filter('.subjects');
var subopts = '';
$.each(subjects,function(index,value){
var subid = $(this).attr('id');
var subname = $(this).text();
subopts += "<option value='"+subid+"'>"+subname+"</option>";
});
//after the loop is over building your <options/> inject the html
$('#fillsubject').html(subopts);
});
You are splitting the <select></select> that's not necessary. You can do it as above.
How does the code sample fit into the rest of your source code?
Rather than using
mydata += "<option value='"+subid+"'>"+subname+"</option>";
in your .each function, you would be better off using
$("#fillsubject").append("<option value='"+subid+"'>"+subname+"</option>");
I don't know what you're doing with mydata after the code sample you post, but since .post is asynchronous, mydata may have already been displayed to the user when your js gets the reply from your server. If this is the case, then the suggestion above will work as expected.

Categories