Loading data from database in every few seconds without page refresh - php

I want to load contents from database in every 10 seconds to a particular . But however i try whole page gets refreshed. Not getting where oi am going wrong.
Here is my code
<?php
include('header.php');
include('includes/Connection.php');
include('includes/GeneralFunctions.php');
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
setInterval(function(){
$('#test').load('#test');
},5000);
</script>
<div id="test">
<?php
$l1 = $con->prepare("SELECT msg, topic FROM messages ORDER BY id DESC");
$l1->execute();
$cntmsg = $l1->rowCount();
foreach($l1 as $r1)
{
echo $r1['topic']."<br />";
echo $r1['msg']."\n";
}
?>
</div>

Use ajax in your SetInterval function.
ajax() method is used to perform an AJAX (asynchronous HTTP) request
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});

Related

AJAX in PHP function is applying to every next instance of the function

Here I have an .ajax function within a PHP function, like this:
function phpFunction($ID) {
print "<script>
$('.uparrow').click(function(){
request = $.ajax({
etc... the rest isn't important.
Anyway, the class .uparrow is an html element that runs this .ajax function when clicked. The other thing you should know is that this function: phpFunction() is called a few times in the document, like this:
phpFunction(1)
phpFunction(2)
phpFunction(3)
However, the problem is that when I load phpFunction(), and I click on the .uparrow element, the .ajax call is made on behalf of each instance of phpFunction() that follows the one whose element I clicked on.
So if I clicked on the .uparrow of phpFunction(1), I would also be virtually clicking on the .uparrows of phpFunction(2) and phpFunction(3). Essentially, I need .uparrow to just be a local class that only applies to the instance of phpFunction() that is currently being called.
The only solution I could think of is to replace .uparrow's class name with something unique to each call of this function. The only difference between each instance of phpFunction() is their input $ID and I was thinking I could redefine .uparrow as:
class = '$ID.uparrow'
or
class = $ID + 'uparrow'
But that doesn't work. So how do I make sure that when I click on .uparrow within phpFunction(1), that the .ajax function only gets called that one time?
This is pretty confusing to explain and probably to understand, so please tell me if there's something that needs elaboration.
Let's say you have a list of elements, and when you click one of them, you want to do an ajax call.
click me
click me
<script>
$(function(){ //on DOM ready
$('.uparrow').on('click', function(){
//do ajax call
$.ajax({
url: 'url here'
type: 'post|get'
data: $(this).attr('data-id'), // you only send the ID of the clicked element
... callbacks, etc
})
});
})
</script>
Now you only have a function that makes an ajax call and takes the parameter to send from the element you clicked.
I hope this is what you wanted to achieve
Try something like this
$('[class="uparrow"]').click( function () {
var request = $.ajax({
// Your ajax call
});
});
this will execute ajax on the clicked element with .uparrow class
HTML
<a class="uparrow" href="#" data-ajax="I'm the first element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the second element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the third element">Click Me</a>
JS:
$('[class="uparrow"]').click(function () {
var currentAjax = $(this).data('ajax')
console.log(currentAjax);
});
And the DEMO
Do not call your php function multiple times. Just one time is sufficient.
Modify the markup of your .uparrow element to include the id like so:
<a class="uparrow" data-id="<?php echo $id; ?>" href="#">TextM/a>
Then re-write your php function like so:
function phpFunction() { /* no need to pass the ID */ ?>
<script>
$(function(){
$(document).on('click', '.uparrow', function(){
$.ajax({
url: 'URL',
type: 'POST'.
data: $(this).attr('data-id')
})
});
})
</script>
<?php } ?>
Call your phpFunction like so:
phpFunction();
UPDATE
<!doctype html>
<html>
<head>
<title>trop</title>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/postStyle.css' />
<link href='http://fonts.googleapis.com/css?family=Exo+2:400,300,200|Homenaje&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel='shortcut icon' href='http://icons.iconarchive.com/icons/visualpharm/icons8-metro-style/256/Music-Note-icon.png'>
<script src='../jquery.js'></script>
<script type='text/javascript' src='../script.js'></script>
</head>
<body>
<?php
$ids = array(1,2,3); // IDs of the posts you want
$result = mysql_query("SELECT * FROM all_posts WHERE ID IN($ids)");
while ($data = mysql_fetch_array($result)){
?>
<div class='post' style='width:470px'>
<h3><?php echo $data['Title']; ?></h3>
<div class='date'><?php echo $data['DateTime']; ?></div>
<iframe width='470' height='300' src='http://www.youtube.com/embed/WF34N4gJAKE' frameborder='0' allowfullscreen></iframe>
<p><?php echo $data['Body']; ?></p>
<div class='postmeta1'>
<p><a href='<?php echo $data['DownloadLink']; ?>' target='_blank'>DOWNLOAD</a></p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta2'>
<p class='uparrow' data-id="<?php echo $data['id']; ?>">▲</p>
<div class='votes'>3</div>
<p class='downarrow'>▼</p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta3'>
<div class='tags'>
<p><?php echo $data['Tags']; ?></p>
</div>
</div>
</div>
<?php } ?>
<script>
var request;
$('.uparrow').click(function(){
request = $.ajax({
url: 'votesHandler.php',
type: 'post',
data: { add : '1', ID : $(this).attr('data-id') }
});
request.done(function (response, textStatus, jqXHR){
alert('Voted!');
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
'Oops, something went wrong'
);
});
request.always(function () {
alert('Done.');
});
});
</script>
</body>
</html>

Trying to Send data using jquery .post()

In insert.php I have the following
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript" src="includes/js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".like").click(function() {
var data = $(this).attr('data-id');
$.post("data.php", {'name': data}, function(response){
$('#dv').html(response);
});
});
});
// ...
</script>
<!-- ... -->
<?
if (!is_bool($result) && !is_null($result)){
while($row = mysql_fetch_array($result))
{
?>
<? $id = $row['uniqueid'];?>
<? echo "<br>ID: " . $row['uniqueid'];?>
<? echo "<br>Name: " . $row['surname']; ?>
<? echo "<br><a href class=like id=buton data-id='$id'> Like (" . $row['likes'] . ") </a>"; ?>
<? echo "<br><br>"; ?>
<!-- ... -->
in data.php I have
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript" src="includes/js/jquery.form.js"></script>
<script type="text/javascript">
alert("<? echo $_POST['name']; ?>");
</script>
I fixed a couple of things I was told were wrong but it still does't work. The alert box is blank. Please help. Thanks.
this is completely wrong... for your data.php this will not parse javascript the way you are expecting.. it will simply take in POST data and ECHO out a result.. dont try and use client-side javascript because it will not do anything
data.php: its php just simply do
<?php
echo $_POST['name'];
?>
in your js if you really want a popup to show then you have to wait for the results of the POST/RESPONSE and do it
$.post("data.php", {'name': data}, function(response){
$('#dv').html(response);
alert(response);
});
remember the php script you call from a POST or ajax call will only process server side code.. PHP, perl, java, C... not client-side code like javascript

How to update a RSS feed presented in a slideshow?

I'm trying to put a rss feed on my webpage and would like to present the articles in a slideshow (Cycle 2).
I'm using a php script ("functions.php)to get the feed and everything works fine but I need help on how to update the feed every 5 minute to check if there are any new articles in the feed.
This is what I have in my div:
<div id="rss-news" class="cycle-slideshow"
data-cycle-fx="fade"
data-cycle-speed="500"
data-cycle-timeout="6000"
data-cycle-slides="> div"
>
<?php
include("functions.php");
//Runs function with feed url and number of posts as arguments
$my_rss = fetch_rss_feed('http://www.thefeed.com/rss', 10);
?>
<?php foreach ($my_rss as $k => $v) : ?>
<div>
<span class="title"><b><?php echo $v['title']; ?></b></span>
<!--<span class="date"><?php echo $v['date']; ?></span> -->
<span class="descr"><?php echo $v['descr']; ?></span>
<span class="enclosure"><img src="<?php echo $v['enclosure']; ?>"></span>
</div>
<?php endforeach; ?>
Update:
I've tried with this code. But it shows all articles at the same time - no cycling:
<html>
<head>
<title>Test</title>
<!--<link rel="stylesheet" href="style.css">-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.cycle2.js"></script>
<script type="text/javascript">
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'getrss.php',
timeout: 2000,
success: function(data) {
$("#div-one").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
}
$(document).ready(function() {
update();
});
</script>
</head>
<body>
<div id="div-one" class="cycle-slideshow"
data-cycle-fx="fade"
data-cycle-speed="500"
data-cycle-timeout="6000"
data-cycle-slides="> div"
></div>
<div id="notice-div"></div>
</body>
</html>
Any ideas?
You need Javascript/jQuery for this, have a look at this here: Jquery/Ajax call with timer so basically you are setting up a function that gets called every 5min and this function pulls the new data and inserts it in the area where the slideshow is located (the jQuery .html() function will come in handy here)

Can't use PHP value from jQuery.load() content

I'm working on a project that uses jQuery modals that dynamically load their content on a button click.
I am having an issue using this loaded content like I would normally.
Here is an example of my problem
<script type="text/javascript>
click function{
load modal{
open: $('#modalID').load('phpfile.php?id=<?php echo $id ?>');
}
</script>
That all works fine, but when trying to use jQuery within the "phpfile.php" is where the problem lies
<?php
$id = $_GET['id'];
$db = USE ID TO GET DATABASE INFO; //works fine here
?>
//ECHO SOME HTML HERE
<script type="text/javascript">
$('#buttonID').on('click', function(){
alert('test <?php echo $id ?>');
});
</script>
When I click the button, I get the alert but it just says test and I don't get the ID like I should.
Thanks in advance for your help and suggestions on this one!
You have pasted pseudo code so it is difficult to say what is wrong in your code.
The following should work, give it a try:
File 1.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<?
$id = "10";
?>
<script>
$(document).ready(
function(){
$('#modalID').load('phpfile.php?id=<?php echo $id ?>');
});
</script>
<div id = 'modalID'></div>
And phpfile.php:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<?php
$id = $_GET['id'];
?>
<script>
$('#buttonID').on('click', function(){
alert('test <?php echo $id ?>');
});
</script>
<input type="button" id = "buttonID" value="click me">
Please check on the do you have any errors in your browser's console. The above code should work. The possibilities are like if you don't get your $_GET['id'] or any script errors will prevent execution of your code.
I have created a sample php file which is working fine.
<?php
$id = rand();
?>
<button id="buttonID"> Click </button>
//ECHO SOME HTML HERE
<script type="text/javascript">
$('#buttonID').on('click', function(){
alert('test <?php echo $id ?>');
});
</script>

Jquery Not Loading PHP File

I have not been able to use JQuery/Ajax to load the content of my PHP file into a div tag.
Here is my page that is loading the file:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function init() {
reloadChat();
setInterval (reloadChat, 5000);
}
function reloadChat() {
$.ajax({
url: "chat.php",
cache: false,
success: function(){
$("#chatmenu").load("chat.php");
},
});
}
</script>
<body onLoad='init()'></body>
<div id='chatmenu'></div>
The PHP file I am loading (chat.php) is in the same folder, and is just an echo statement:
<?php echo "test"; ?>
To make sure it was not a problem with my Javascript functions, I added an alert under the success function, and it did alert me every 5 seconds, so I think it is something with the load statement.
Use .load() straight away, no need to make an Ajax request first:
function reloadChat() {
$("#chatmenu").load("chat.php");
}
Update:
I notice that in your example code, you close your body-tag before your div element.
<body onLoad='init()'></body> <!-- This ain't right -->
<div id='chatmenu'></div>
Try this instead:
<body onLoad='init()'>
<div id='chatmenu'></div>
</body>
Try this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function init() {
reloadChat();
setInterval (reloadChat, 5000);
}
function reloadChat() {
$.ajax({
url: "chat.php",
cache: false,
success: function(response){
$("#chatmenu").text(response);
},
});
}
</script>
<body onLoad='init()'></body>
<div id='chatmenu'>
</div>
Also, for the love of god, please use an up-to-date version of jQuery
It looks your first request from $.ajax will return 'test', and then you're using that as the URL for $("#chatmenu").load.
Try this:
function reloadChat() {
$.ajax({
url: "chat.php",
cache: false,
success: function(data){
$("#chatmenu").append(data);
},
});
}
Or, if you want to replace the contents of #chatmenu the method posted by Christofer Eliasson where you just call $("#chatmenu").load("chat.php") in reloadChat will work.
Putting it all together:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="chatmenu"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
setInterval (function() {
$("#chatmenu").load("chat.php");
}, 5000);
});
</script>
</body>
</html>

Categories