How to use setInterval() when there's a param? - javascript

I'm trying to get a single div on a php page to refresh every 5 seconds.
In HTML I have: EDIT: NEW SCRIPT FUNCTION
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'game.php',
success:function(data){
$("#read_chat").html(data);
}
});
}
setInterval(callAjax, 5000);
});
</script>
And the function (in a php block) I'm trying to refresh is:
echo" <div class='read_chat' >";
function get_messages($db){
//get messages
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
//display messages
foreach ($messages as $row) {
//display each message in row
if ( $row['character_name'] == NULL){
echo "<div class='left'>" . $row['user_name'] . ": </div>";
}
else {
echo "<div class='left'>" . $row['character_name'] . ": </div>";
}
echo "<div class='center'>" . $row['message'] . "</div>";
echo "<div class='right'>" . $row['time'] . "</div>";
}
}
echo "</div>";
The display of this is only the CSSed block without any content. If I just call get_messages($db) all the chat from the database loads. How do I make this div refresh automatically? Thanks!
EDIT:
The name of the file is "game.php" and the php function is "get_messages()".
For the record I looked at:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
and
Pass parameters in setInterval function

Javascript
setTimeout(function(){
$.ajax({url: "get_message.php", success: function(result){
var num_records = result.length,
i,
content;
for(i=0;i<num_records;i++){
if (result[i]['character_name'] !== null){
content += "<div class='left'>" + result[i]['character_name'] +": </div>";
}
else{
content += "<div class='left'>" + result[i]['user_name'] +": </div>";
}
content += "<div class='center'>" + result[i]['message'] + "</div><div class='right'>" + result[i]['time'] + "</div>";
}
$('.read_chat').html(content);
}});
}, 5000);
get_message.php
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
$response = array();
foreach ($messages as $row) {
$response[] = $row;
}
echo json_encode($response);

I'd suggest using jQuery $.load, see the example below:
setTimeout(function(){
$('.read_chat').load('get_message.php');
}, 5000);
You'll need to return nice html from the PHP script instead, but it's cleaner.

Related

Deleting database data with button in table

I have a search page on my web app which searches for events in my event table in my database. I would like to have it so that there is a delete button at the end of the search result with the ability to delete a database entry but also a pop up alert box before they delete the data.
My search results are displayed with the code below:
if(mysqli_num_rows($result) > 0) {
echo "<br>Result Found: ";
echo "<br><table>";
While($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>Event Number: " . $row['EventID'] . "</td>";
echo "</tr><tr>";
echo "<td>Location: " . $row['Location'] . "</td>";
echo "</tr><tr>";
echo "<td><input type='button' name='Delete' value='Delete' onClick='getConfirmation();'></td>";
}
echo "</table
I'm not too sure what to put in the javascript function. I want it to come up a basic alert box and if the user clicks the okay button then the action will be 'delete.php' and ideally another pop-up come up saying "Record Deleted Successfully". I also need to make sure to get the eventID from the record so that I can delete it successfully. So far for the JS function I have:
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Are you sure you would like to delete this record?");
if( retVal == true ) {
delete.php
document.write("Record deleted successfully");
}
else {
return false;
}
}
//-->
</script>
I know this is wrong but I am wondering how I can fix this?
Also could I just put it that if they press yes the php executes rather than going to delete.php?
To achieve this, you need to pass eventId in your onclick event as below:
if(mysqli_num_rows($result) > 0) {
echo "<br>Result Found: ";
echo "<br><table>";
While($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>Event Number: " . $row['EventID'] . "</td>";
echo "</tr><tr>";
echo "<td>Location: " . $row['Location'] . "</td>";
echo "</tr><tr>";
echo "<td><input type='button' name='Delete' value='Delete' onClick='getConfirmation(".$row['EventID'].");'></td>";
}
echo "</table>";
and in your JS code, you need to:
1. Get eventId in your js function.
2. Call ajax to delete that event.
3. show success alert after
<script type = "text/javascript">
function getConfirmation(eventId) {
var retVal = confirm("Are you sure you would like to delete this record?");
if( retVal == true ) {
$.ajax({
url: "delete.php",
method: "POST",
data: {eventId: eventId},
success: function (response) {
if(response.status) {
alert("Record Deleted Successfully");
}
}
});
} else {
return false;
}
}
</script>
Also, in your delete.php file, you need to get eventId by $_POST['eventId'] and you can execute delete query. and you need to send back to status. Hope it will help you.

Alert box not showing when action from php js php

I have a problem in showing the alert box. This code for the rating star.
rating.js
$(document).ready(function(){
$('.post li').mouseout(function(){
$(this).siblings().andSelf().removeClass('selected highlight')
}).mouseover(function(){
$(this).siblings().andSelf().removeClass('selected');
$(this).prevAll().andSelf().addClass('highlight');
})
$('.post li').click(function(){
$(this).prevAll().andSelf().addClass('selected');
var parent = $(this).parent();
var oldrate = $('li.selected:last', parent).index();
parent.data('rating',(oldrate+1))
data = new Object();
data.id = parent.data('id');
data.rating = parent.data('rating')
$.ajax({
url: "add_rating.php",// path of the file
data: data,
type: "POST",
success: function(data) {
}
});
})
/* reset rating */
jQuery('.post ul').mouseout(function(){
var rating = $(this).data('rating');
if( rating > 0) {
$('li:lt('+rating+')',this).addClass('selected');
}
})
})
add_rating.php
<?php
include("dbconnection.php");
session_start();
$myid = $_SESSION['id'];
// echo "".$myid;
$sql_notification ="SELECT * FROM table_user_skills where user_id='$myid' and rating=5";
$result = $conn->query($sql_notification);
$count = 0;
while ($row=$result->fetch_assoc()) {
if ($row['rating']==5) {
$count = $count +1;
}
}
// echo "Count: ".$count;
if(!empty($_POST["rating"]) && !empty($_POST["id"])) {
$myrate=$_POST["rating"];
if($count<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Less than 5");';
print '</script>';
} else if($myrate<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Rate Less than 5");';
print '</script>';
}else if($count>5){
print '<script type="text/javascript">';
print 'alert("Lpas 5 stars");';
print '</script>';
}
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE skills_id='" . $_POST["skills_id"] . "'";
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE user_id='" . $_POST["userid"] . "' and skills_id='" . $_POST["id"] . "' and category_id='" . $_POST["category"] . "'";
}
?>
My problem is that the alert box is not showing. I have to limit the number of 5 stars being updated. If anyone could help me figure out what's wrong with my code, I would appreciate it.
Look at the success callback function for your AJAX call - it's empty. You're having PHP print out the alert box code in the ajax call and then never doing anything with that output.
To make the alert show up, you would have to append the code your AJAX call returns to the DOM. However, it would probably be better to just return just the message and let the JavaScript code take care of raising the alert box. Just a simple alert(data) should do the trick.

AJAX Search Function Not Updating Answer

I have an AJAX function that calls a php function to search a mysql database. The script fires off on keyup and the problem is on the first key press the html content is updated but it will not update after the initial keyup event
How do I make the page continuously update the html content with the new data that is coming in after every keyup.
My AJAX function,
var searchPath = "<?php echo $searchPath ?>";
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
And this is the php behind it all,
<?php
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>

Unwanted JSON Response

I'm using this small JSON function with a database.
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
This produces this in the browser, which I don't want/need.
{"users":[{"Title":"Anyway","ArtistNumber":"2","TrackTime":"167","Composer":"John
Glaze","Lyricist":"Kellee
Maize","FileLocation":"public/Anyway.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"One
Way Heartbeats","ArtistNumber":"4","TrackTime":"187","Composer":"Bill
Bobs","Lyricist":"Michael
McEachern","FileLocation":"public/OneWayHeartbeats.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Parallel
Me","ArtistNumber":"3","TrackTime":"192","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"private/ParallelMe.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"1"},{"Title":"Poisoned
Oxygen","ArtistNumber":"3","TrackTime":"177","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"public/PoisonedOxygen.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Xmas
Prison Blues","ArtistNumber":"1","TrackTime":"192","Composer":"Steve
Perry","Lyricist":"Steve
Perry","FileLocation":"private/XmasPrisonBlues.wma","rated":"0","scores":"[0,0,0,0,0]","free":"1"}]}
Any ideas on how to hide it or remove it from coming up?
Thanks
This is the Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
Using jQuery 1.10.2
The songlist element is found here
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><div id= songlist> </div> </p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p>Songs</p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
And basically whenever I run these files, I get that long string I stated at the beginning as a response in my browser everytime.
Well your PHP appears to be returning a valid json string, but it is not being coverted automatically to a json object so that it can be processed by javascript as an object.
You could try forcing the parse to a json object like this
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Categories