I wanted to make a "friend request" option on my website and I would like if friend requests can be displayed as soon as possible. (even if I don't reload page) So what I've read here I need setInterval
and Ajax, I found the code, and it works perfect for the first time, but it doesn't refresh on database changes. Is that intended or am I doing something wrong? Example, I have 2 friend requests, and I get one more friend request while my page is idle, and it doesn't shows up, even tho my javascript is doing the query again, right? I know I shouldn't use mysql_query
, and I will fix that as soon as possible, but no way that could be the problem.
$(document).ready(function(){
var ajax_call = function() {
document.getElementById('js_hack').innerHTML = "<?php
$ses_sql3=mysql_query("select * from friend_request where reciver='$login_username'", $connection);
$num_rows = mysql_num_rows($ses_sql3);
if($num_rows > 0) { echo $num_rows; }?>";
};
var interval = 1000 * 1; // where X is your every X minutes
setInterval(ajax_call, interval);
});
Place your <?php?>
code in a separate file, and call that file.
I didn't look at the rest of your code to validate that it is "good", thought.
You can't have serverside code perform on the client side, like that; nor do you want it to.
Here is an example, and what looks to be a dupilcate question: Ajax time interval call to a php function
When a client executes that php script on your site, the database is analyzed only once then after that, every "interval" ms, the html element with the ID of js_hack will always be rewritten with the same value.
Do some research on The XMLHttpRequest Object:
http://www.w3schools.com/xml/xml_http.asp
When you are done, make a php file that contains the data you're trying to set innerHTML to, then make a function in javascript that uses the xmlhttprequest functionality to open and process that newly created php file.