not able to handling ajax request from a small chat module - php

i am developing a simple chat module for my client, but not able to handle loop from setInterval()
Here is the js code from which i sending the request to get the data from the database
function getData(){
jQuery.ajax({
url: '../../get_data.php',
data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>',
cache: false,
success: function(data){
jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
setInterval("getData()", 5000);
}
});
}
and here is the get_data.php file which produce the data according to request
require "../../support/connection/connect_gib.php";
$to = addslashes(trim($_REQUEST['to']));
$query = "select * from chat where
guest_id='".mysql_real_escape_string($to)."' order by id asc";
$result = mysql_query($query);
while( $row = mysql_fetch_assoc($result) ){
echo "<b>".$row['frm']." : </b> " .$row['message'] . "<br />";
}
i got the result in loop like all the data repeat again and again, but i want the newly updated data, please make me correct what i did wrong..

You are using appendTo function in jQuery.. So all chat messages will be appended after old list. You can use .html() function to replace complete data.
Another way is to get only last chat message from php side, so all data will not be repeated. You can use auto id to point which messages are fetched last.

You should preserve the last id fetched and use that for new request. And on server side you should fetch from there.
$id= addslashes(trim($_REQUEST['id']));
$query = "select * from chat where
guest_id='".mysql_real_escape_string($to)."' AND id > '".mysql_real_escape_string($id)."' order by id asc";
function getData(){
jQuery.ajax({
url: '../../get_data.php',
data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>&id=' + last_id_fecthed,
cache: false,
success: function(data){
jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
setInterval("getData()", 5000);
}
});
}

Related

How to perform ajax post request to get some values from the last row of?

Hi I was asked to get some data from the last row in the database using ajax post request.
I have two files which are PHP scrip which is used to connect to the database and get all the data and convert the data to json format. I performed ajax post to PHP script to get all data. I want to modify the ajax post to request an additional data from the last row of the tables in database.
For example, in student table, there are 10 rows of data in database. I want to get data from the last row. My question is how to get values from the last row in the database..
Requirement: do not modify the SQL code as I need all the data and additionally the last row of data.
I do not want this code data[9]['student_name'];
here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="result"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "student.php",
dataType: "json",
data: "how to request data from the last row of the database????
success: function(data){
console.log(data);
}
});
};
</script>
</body>
</html>
php script
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
?>
My question is how to get data from the last row of database?
Requirement: do not modify the SQL code as I only want to modify the ajax post. Please help me. This is for my project.
Change the PHP code as follows.
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
$limit = count($json_array);
echo json_encode($json_array[$limit-1]);
?>
Your question is a bit unclear. It seems you want to send a param to PHP the only the last row, but I'm not sure. If that's true, you can do what #Rossi proposed adding a parameter like:
data: {
lastOnly: true
}
And at the end of the script:
if (!isset($_POST["lastOnly"])) {
echo json_encode($json_array);
} else {
echo json_encode($json_array[count($json_array)-1]);
}
But, if still wants to get all data from back-end but deal with the last row in your javascript, you can do what i've said in the comments:
success: function(data) {
var lastRow = data[data.length - 1];
}
UPDATE: To get only one field.
You can send back only one value and your data will receive a string instead of a json object:
echo $json_array["student_name"];
You can get the the property from your json object:
data.student_name

Removing Selected Option From Database

I have a select element created dynamically with items from my database. I would like to be able to delete the record from the database if the delete button is selected. Currently I have an AJAX function that is sending a GET request to my current page to remove it, and it removes the item from my options, however, my PHP used to access my database is never called and therefore when I refresh, the query is ran and what I just "removed" is displayed again because it is still in my db. I know I must be missing something simplistic, I just can't quite put my
finger on it and would appreciate any help or advice. I'm open to other methods as well. This is definitely not my strong suit.
My AJAX:
window.onload = function () {
document.getElementById("deleteLoc").onclick = function () {
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "adminLocationEdit.php", //Where to make Ajax calls
data:{deleteLoc : $("#lList option:selected").val() },
dataType:"text", // Data type, HTML, json etc.
});
$("#lList option:selected").remove();
}
};
My HTML:
<select id ="lList" multiple="multiple" style="width:400px;height:400px;">
<?php
//Query that selects all locations from the database and creates the list dynamically.
$qry = "SELECT * FROM location";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-1");
//Echo the db results into the select box.
while($row = odbc_fetch_array($qry_result)){
//Sets each row to variable.
$locID = $row['locationName'];
echo "<option id =\"$locID\" name = \"$locID\" onclick =\"$('#form1').load('incl/adminLocationEdit.php?loc='+$(this).attr('id'));displayFieldsets('form1', 'locList', 'lList');\">" . $locID . "</option>";
}
?>
My PHP:
//If user wants to add a new location
if(isset($_POST['addLoc'])){
//Re-directs
//header("Location: adminLocation.php");
exit;
}
//If user wants to Delete a location from the database.
if(isset($_POST['deleteLoc'])){
$contentToDelete = $_POST['deleteLoc'];
//Deletes current location from the database.
$qry = "DELETE FROM location WHERE locationName = '" . $contentToDelete . "'";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-2");
}
You are mixing both GET and POST
If you are looking for post,
This should be
data:{deleteLoc : $("#lList option:selected").val() },
Or if you are looking fr GET
type: "GET",// this should be GET not POST

Fetch random row from MySQL on click

I am creating a random quote generator and store the data in a MySQL database.
The code is working but it continues to fetch the same row and not a new random row everytime I click. But if I wait for say 30 seconds and click again, it works as it should. I just want it to work right away on click.
<script type="text/javascript">
$(document).ready(function() {
$(".display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(response, 5);
//alert(response);
}
});
});
});
I suspect the timeout function is not working properly as it takes longer to fetch a new row. I used the order by Rand() to get the random row. My PHP looks like this:
<?php
include("connect.php");
$finds = "SELECT * FROM citater5 ORDER BY RAND() LIMIT 1";
$result = mysql_query($finds, $con) or trigger_error(mysql_error()." ".$finds);
while($data = mysql_fetch_row($result))
{
echo "<aside class=\"citatout\">";
echo "<div id=\"paradiso\" class=\"text-vertical-center-q\">";
echo utf8_encode("<h1 class=\"animated fadeIn\" align=center>$data[0]</h1>");
echo utf8_encode("<h2 class=\"animated fadeIn\" align=center>$data[1]</h2>");
echo "</div>";
echo "</aside>";
}
?>
Why is a new row not being fetched every time?
Not quite sure if ORDER BY RAND() is working as you want it too.
- I haven't really been working with PHP for a few years, but I would probably try something like this out:
<?php
include("connect.php");
$totalrows = mysql_num_rows(mysql_query("SELECT * FROM citater5"));
$finds = "SELECT * FROM citater5 WHERE id='".rand(1,$totalrows)."'";
$result = mysql_query($finds, $con) or trigger_error(mysql_error()." ".$finds);
$data = mysql_fetch_row($result);
echo "<aside class=\"citatout\">";
echo "<div id=\"paradiso\" class=\"text-vertical-center-q\">";
echo utf8_encode("<h1 class=\"animated fadeIn\" align=center>$data[0]</h1>");
echo utf8_encode("<h2 class=\"animated fadeIn\" align=center>$data[1]</h2>");
echo "</div>";
echo "</aside>";
?>
And - as you're only getting 1 result, theres no need to run it through a while().
Hope this helps a bit.
Like the others said, rand() may not be the best to use, but I don't think it is what is causing your issue. Most likely the result is being cached if it's displaying the same result for a short period of time.
You could try turning the cache off:
$.ajaxSetup({ cache: false });
Or append the URL in the ajax call with a random number or timestamp.

Select from mysql is not working in jQuery fancybox

Fancybox script POST my form data to go.php page then open go.php in fancybox iframe
<script>
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.post('go.php', $(this).parent().serialize())
.done(function() {
$.fancybox.open({
href : 'go.php',
type : 'iframe',
padding : 5
});
});
});
});
</script>
<select name="country">
<option value="US">US</option>
<option value="EU">EU</option>
</select>
<input type="button" value="Calculate" id="fancybox-manual-b"/>
in go.php, I receive the POST data from the form correctly and when I try to insert this data into DB, it's been inserted correctly too!
But now I want to select * from my DB table to echo all the data in the table where column = POST data, but this query doesn't work!
<?php
$country = $_POST[country];
mysql_query("INSERT INTO calculator (country) VALUES ('$country')"); //Works Correctly
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
} //Nothing appear
?>
Please checkout this method,
$country = $_POST[country];
if(mysql_query("INSERT INTO calculator (country) VALUES ('$country')"));
{
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
}
}
I used the same code you shared. But added an additional if loop on mysql_query part. It will make sure your select works after data being inserted.
We have to use jquery ajax to send form data to the php page with POST method then receive back any printed data from the php page in the ajax instead of the console.
We will open the fancybox iframe into ajax success instead of the console.
<script type="text/javascript">
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.ajax({
type: 'POST',
url: 'go.php',
data: $(this).parent().serialize(),
success: function(data){
$.fancybox(data);
},
fail:function(data){console.info(data)}
});
});
});
</script>

Retrieve Data from database if new records added in database

Hello i have gone through Long polling, websockets and APE, Ajax push, Ajax Pull. As the technology of websockets isnt yet much introduced in our World Wide Web now. i thought i would use the normal setInterval functions to check the database. this is for a chat application, my code :-
on Home.php :
Javascript:
$(document).ready(function(){
setInterval(function(){
var id = $id; // this is the id of the last message inserted in the database
var data = 'id='+id;
$.ajax({
type : "POST",
url : "check.php",
data : data,
success : function(data){
if(data)
{
$(".comments").append(data);
}
}
});
},1000);
and check.php
php code :
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM messages WHERE id>'$id' ORDER BY id DESC");
$num2 = mysql_num_rows($get);
$get2 = mysql_fetch_assoc($get);
$id = $get2['id'];
if($num2!=0)
{
$username = $get2['username'];
$a = mysql_query("SELECT * FROM people WHERE username='$username'");
$n = mysql_num_rows($a);
$b = mysql_fetch_assoc($a);
$file = $b['filename'];
$pic = "<img src=\"images/" .$file. "\" width=\"40\" height=\"40\">";
$name = $get2['fullname'];
$message = $get2['message'];
echo $pic.$message."<br/>";
}
else
{
}
if there is a new record inserted in the database it echo's out properly but then it doesnt update the $id in the home.php page so it sends the old id again and again and the comment gets appended again and again.
what i want is. for every interval . the $id of the home.php should be updated so that it sends only the present message id to the check.php page.
I gues that the first code you've post is in your template of home.php and the $id then goes replaced with the real number of the last ID.
this works for the first time when the page is processed with PHP, but once downloaded on users machine, you only have to rely on JavaScript...
I'm not sure in which form you receive the data from check.php, but you need to do something like
id = data.id
data = 'id='+id;

Categories