show only latest rows from a database with jquery - php

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>

Related

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');

Multiple AJAX calls - 1st to fetch data and turn into JSON object & 2nd to update $_SESSION info

I have an ajax call which pulls data from the table and then transforms into a JSON object
Because I am also doing a lot with PHP as well I need to have a 2nd AJAX call
immediately after the first that will update $_SESSION info
I have tried putting
$_SESSION['company_id'] = $_POST['companyid'];
in the same file that handles the 1st AJAX call but it then doesn't process the data from the first call, hence I need to do the 2nd call
Here is my jQuery Code for the 1st and 2nd AJAX query
$(".showcompinfo").click(function(){
$("#comptable").hide();
$("#showcomptable").show();
var id = $(this).attr('id');
$("#comp_info").toggle();
var companyid = id;
var dataString = "companyid="+companyid;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/dataforms/complist.php",
data: dataString,
success: function(result){
var jsonObject = JSON.parse(result);
// here you can do your magic
var approved = jsonObject.customer_approved;
$("#showcompname").text(jsonObject.name);
// Get Reg Address Details - Check if any field is empty
var regoffice_2 = '';
var regoffice_3 = '';
var regoffice_city = '';
console.log(jsonObject.regoffice_city);
if(jsonObject.regoffice_2)
{
regoffice_2 = ', ' + jsonObject.regoffice_2;
};
if(jsonObject.regoffice_3)
{
regoffice_3 = ', ' + jsonObject.regoffice_3;
};
if(jsonObject.regoffice_city)
{
var regoffice_city = ', ' + jsonObject.regoffice_city;
};
var addlne1 = jsonObject.regoffice_1;
var regaddress = jsonObject.regoffice_1 + regoffice_2 + regoffice_3 + regoffice_city;
$("#addline1").val(jsonObject.regoffice_1);
$("#addline2").val(jsonObject.regoffice_2);
$("#addline3").val(jsonObject.regoffice_3);
$("#addcity").val(jsonObject.regoffice_city);
$("#addcounty").val(jsonObject.regoffice_county);
$("#countryselected").val(jsonObject.regoffice_country);
$("#countryselected").text(jsonObject.regoffice_country);
$("#addpostcode").val(jsonObject.regoffice_postcode);
console.log(regaddress);
if(approved == '1')
{
$("#approvedcust").text('Yes');
} else {
$("#approvedcust").text('Customer but Not Approved');
};
}
});
// 2nd Ajax
var companyid2 = jsonObject.company_id;
var dataString2 = "companyid="+companyid2;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/updatesession.php",
data: dataString2,
success: function(){
}
});
//
Here is the PHP code for complist.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){
$newdata = json_encode($result);
}
}
print_r($newdata);
If anyone can help even consolidate this into 1 ajax query or help me get 2 calls
working correctly it would be much appreciated
** EDIT **
OK I now have it displaying the Company ID in the session variable however when the user clicks to view a different company info result the session company_id does not update
I have changed the complist.php to the following
if(!empty($_POST['companyid']))
{
unset($_SESSION['company_id']);
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$_SESSION['company_id'] = $_POST['companyid'];
$newdata = json_encode($result);
}
}
print_r($newdata);
My thinking behind the above was that once the ajax call is made it immediately unsets the session variable company info
then once a result is found for the selected company it resets the session var company_id with the new value, however its not updating the session variable
Screenshots showing what I mean
Your code updates your session variable successfully. However, since you're making an AJAX call, only the code in the PHP script directly called by the AJAX ("complist.php" in this case) is executed on the server. None of the PHP code which originally used to create your page is run again - this is why you have to use JavaScript to populate the rest of your newly selected company details.
To update the ID on screen following the AJAX call, all you need to do is follow the pattern you've used to update the rest of the fields
Change your HTML so the element which contains the company ID has an ID which lets JavaScript identify it:
<span id="showcompname"></span><span id="showcompid"><?php echo $_SESSION['company_id'];?></span>
and then in the "success" callback of your AJAX code, write
$("#showcompid").text(jsonObject.company_id);
This is exactly the same concept as the other JavaScript code you've got e.g. to update the "showcompname" element.
Meanwhile, the value stored in your PHP session will be used next time you run the PHP code which updates the whole page (e.g. by refreshing the page).

Print an element array in jquery

I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});

use php inside script [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I am writing a program which I need to add php code inside script
The html has a table, with 2 chosen selectbox, I want to update 2nd selectbox when first when has been changed by user
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed
{
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
<?php
$ord = '<script>document.write(ord);</script>'; //javascript variable to php variable
//This code is not working, if I update the php variable from javascript variable
mysql_query('select * from ords where ord_id = '.$ord.');
?>
$(itemcode).append('<option>a</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
Any ideas?
You could try sending the variables by using the jQuery load function.
page1.html:
<script type="text/javascript">
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') {
var itemcode = $(this).parent().parent().find('[data-id="item"]');
$('#ord').load('page2.php?ord='+ord);
$(itemcode).append('<option>'+$('#ord').html()+'</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
</script>
<div id="ord"></div>
page2.php:
<?php
$ord = $_GET['ord'];
mysql_query('select * from ords where ord_id = '.$ord);
?>
Here's an example of how it could be done with AJAX. You probably need to adapt it to your needs. The idea was just to show you the basics of an AJAX request:
<script>
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed {
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
$.ajax({
url: "order.php",
type: 'POST',
data: {
ord: ord
},
cache: false,
success: function(data){
$(itemcode).append(data);
$(".chzn-select").trigger("liszt:updated");
}
});
}
});
</script>
Create a PHP file to handle the request and echo the HTML to be appended. This is just a rough example:
<?php
$ord = $_POST['ord'];
if (is_numeric($ord)){
$result = mysql_query('select * from ords where ord_id = '.$ord);
if ($result){
//process query result here
//create HTML string that will be appended
$str = '<option>'.$option.'</option>';
echo $str;
}
}
?>
PHP runs on server-side and prepares the page before the client-side javascript code is invoked. so, assuming this is a PHP file that contains javascript, be advised that best thing the PHP might do is prepare which javscript code will be in the page. if you want to pass javascript variable to PHP, you must SEND them from the client-side to the server-side (probably with $.POST command)
It does not work because $ord in literally the value of:
<script>document.write(ord);</script>
Which is no where near a id.
Try using the jquery post:
$.post("phpdoc.php", { name: ""+ord+""})//this sends the ord value to the php page
.done(function(data) {
alert("Data Loaded: " + data);//this will alert returned data
});

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

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>");

Categories