I designed a site that gets news from another site's RSS and saves it to my DB. To do this I must send request to another site and save changes to my DB.
this is my code for sending request:
$q = $d->query("select * from site_setting where id=1");
$setting = $d->fetch($q);
$start = $setting['last'];
$q = $d->query("select *from newsagency order by id limit ".$start.",1");
while($agency = $d->fetch($q)){
$url = $agency['link'];
$size = 20;
$agencyId = $agency['id'];
$time = time();
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
$MaxTime = $d->getrowvalue("time","select `time` from news where agency={$agencyId} order by time DESC limit 0,1",true);
foreach($recents as $article)
{
$articleTime = strtotime($article["date"]);
if($articleTime > ($MaxTime+1)){
$d->iquery("news",array(
'title'=>htmlspecialchars($article["title"]),
'time'=>$articleTime,
'link'=>$article["link"],
'type'=>$article["type"],
'img'=>$article["media"],
'regTime'=>$time,
'agency'=>$agencyId
));
$return .= $article['title']."<br>";
}
}
}
$last = $start +1;
$agencyCount = $d->getrowvalue("agenC","select count(id) as agenC from newsagency",true);
$agencyCount--;
if($last>$agencyCount) $last = 0;
$d->uquery("site_setting",array('last'=>($last)),"id=1");
this code gets rss link one by one from db and then gets data from rss and saves it to db, and everything in OK. to refresh the php page, we have a code like this :
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$.ajax({
url: "load.php",
context: document.body,
success: function(vars){
document.getElementById("imge").innerHTML+=vars;
}
})
}, 500);
});
</script>
</head>
<body dir="rtl">
<div id="imge"></p>
</body>
I refresh this code every 500 ms and get content from rss. The problem is that this page must forever be open and I don't have any idea to solve this problem. How can I send this request without getting the client's computer busy?
Related
I am using an 'infinite scroll' script that keeps sending requests to the database even when there are no more records. When that happens, it reloads the last set on the page. I would like for the function to stop running when it reaches the last record on the database. I'm new to JS so this is a bit difficult for me to troubleshoot, also, I'm not using jQuery. I am doing most of the work in the PHP script.
I've been reading a lot of posts in here about 'infinite scroll' and I am unable to get how other people check the limits in JS.
JavaScript
function loadPosts(){
var target = document.getElementById('PostsContainer');
var contentHeight = target.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
var xhr = ajaxObj("POST", "loadContent.php");
xhr.onload = function(){
target.innerHTML += xhr.responseText;
}
xhr.send("action=loadMore");
}
}
window.onscroll = loadPosts;
PHP
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC LIMIT 2" //Original content on page
$totalPosts = 12; (query to DB)
$max = 1;
$current = 2; //Start on record after initial content
while($current < $totalPosts){
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC
LIMIT $current, $max";
$result = $db_link->query($sql);
$posts_list += ... //Collect the data from DB
$current++;
}
echo $posts_list;
No matter how many times I keep scrolling the new content keeps loading even after I run out of records in the DB. Output keeps repeating every single time I get to the bottom of the page. In this case I have 7 posts in the DB I start with 7, 6... then I keep getting posts 5-1.
So in this case what you can do,
just add one parameter in json, from php or server side which will tell, is data present or not, based on that, you can stop calling loadPosts function
so basically Algorithm be like,
...php
while($current < $totalPosts){
......................
......................
if($current >= $totalPosts)
{
$getNext = False;
}
else
{
$getNext = True;
}
}
...javasrcipt
function loadPosts(){
if(!getNext)
return false;
else
{
......................
......................
}
}
window.onscroll = loadPosts;
Hope this strategy will help you
I am beginner in web development so please understand me. I am trying to create a session using php file and call it in javascript using ajax request. but after I input the path of the index.html in address bar, it always shows the index. I want to know how can i possibly do this with javascript and php. restricting the all the pages of the site if there is no user active.
for example logic:
if (userhasValue == true) {
//redirect to index and can access the whole website
} else {
// redirect to login page
}
I have tried the code below but it still redirecting to index.html even if the data recieve in ajax request is empty.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$temparray = array();
$ses_sql = mysqli_query($db,"select user_id,username,fullname from user where username = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
if ($row > 0 ){
array_push($temparray, $row); //save your data into array
echo json_encode($temparray);
} else {
echo 'Error';
}
?>
function getUser(){
var user ='';
var fullname ='';
var id ='';
var tempArray = '';
var name = '';
$.ajax({
type:'POST',
url:'../bench/php/session.php',
data:'',
success:function(msg){
alert(JSON.stringify(msg));
let tempArray = JSON.parse(msg)
user = JSON.stringify(tempArray[0]['username']);
fullname = JSON.stringify(tempArray[0]['fullname']);
id = JSON.stringify(tempArray[0]['id']);
document.getElementById('fullname').innerHTML = fullname;
if (msg == 'Error') {
window.location.href = "../pages-login.html";
}
}, error: function(e){
console.log(e);
}, complete: function(c){
console.log(c);
}
});
}
The code above does not restrict the accessibility of the index.html and other pages if the user is not logged in.
I want to restrict the index page and other pages if the user try to redirect to index page without logging in.
Please help me. Any help will much be appreciated! Thanks in advance
I have a big problem to make a progress bar in AJAX. The whole page is in AJAX, inside one of the webpage is AJAX which loads a function to get some big rows from the database.
I tried to make progress bar in this script in a foreach loop a flush() method and by writing/reading to $_SESSION, but still nothing. I really tried everything I don`t know how to do this. Need only this to complete my project. Could someone help me with this?
It is anyway which script I want to load, how is the template for this progress bar to use it in GET or POST ajax, for any AJAX.
<script>
jQuery(document).ready(function($) {
$(document).on('click','#save',function () {
setTimeout(getProgress,1000);
$(this).text('Pobieram analizę...');
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var id = $.urlParam('id');
var idt = $.urlParam('idt');
$.ajax({
url: "views/getresults.php?id="+id+"&idt="+idt,
success: function(data) {
$("#loadresults").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'views/listen.php',
success: function(data) {
if(data<=100 && data>=0){
console.log(data);
$('#loadresults').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / 100)*100 +'%">'+ data + '/' +100+'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#loadresults').text('Pobieram dane');
console.log('End');
}
}
});
}
});
</script>
and here is a getresults.php
foreach($result as $resul) {
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = 100;
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
and a get progress function listen.php
<?php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
?>
Writing and reading session doesn't work because the standard behavior of PHP is to lock the session file while your main code is being executed.
Try to create a file and update the its content with the percentage done during the execution of your function. Something like:
<?php
function slowFunction() {
$file = uniqid();
file_put_contents($file, 0);
// Long while that makes your stuff
// you have to know how many loops you will make to calculate the progress
$total = 100;
$done = 0;
while($done < $total) {
$done++;
// You may want not to write to the file every time to minimize changes of being writing the file
// at the same time your ajax page is fetching it, i'll let it to you...
$progress = $done / $total;
file_put_contents($file, $progress);
}
unlink($file); // Remove your progress file
}
?>
You can't get the progress of the data download from ajax. Once you request you to the server, the next response will be only after fetching the data or when the error occurs.
The solution to you is, get the data as fractions. Such as first download the 1/10th of the data, and in the success callback, recursively call the ajax again requesting the 2/10th data. On each success callback, you could change the progress bar.
Take a look at Server Side Events or Long polling as options
I'm trying to send data to a php file to save in database, but I don't have any response. If a checkbox is check, the [obj][idCheckbox] = 1, else [obj][idCheckbox] = 0.
File that sends
var i=0;
var objetoTodasPermissoes = function(){};
var objTodasPermissoes = new objetoTodasPermissoes();
$.each($(".classePermissoes"), function(){
objTodasPermissoes[$(this)[0].id] = 0
i++;
});
$.each($(".classePermissoes:checked"), function(){
alert('ok');
objTodasPermissoes[$(this)[0].id] = 1;
});
console.log(objTodasPermissoes);
$.each($("#userList tr"),function(){
alert(this.id);
var iduser = this.id;
$.ajax({
url:'../json/usuarioperm/savePermissions.php',
data:({
idusuario:iduser,
objTodasPermissoes:objTodasPermissoes,
}),
success:function(a){
Alert("Saved!");
}
});
});
}
the savePermissions.php file.
$iduser = $_POST["iduser"];
$perm_usuarios = $_POST["objTodasPermissoes"]["perm_usuarios"];
$perm_importar = $_POST["objTodasPermissoes"]["perm_importar"];
$perm_log = $_POST["objTodasPermissoes"]["perm_log"];
$perm_proto = $_POST["objTodasPermissoes"]["perm_proto"];
$perm_limpeza = $_POST["objTodasPermissoes"]["perm_limpeza"];
$perm_lixeira = $_POST["objTodasPermissoes"]["perm_lixeira"];
$perm_relatusuarios = $_POST["objTodasPermissoes"]["perm_relatusuarios"];
$perm_deptos = $_POST["objTodasPermissoes"]["perm_deptos"];
$perm_deptospastas = $_POST["objTodasPermissoes"]["perm_deptospastas"];
$perm_empresas = $_POST["objTodasPermissoes"]["perm_empresas"];
mysql_query("UPDATE hospital.users set
perm_usuarios=".$perm_usuarios.",
perm_importar=".$perm_importar.",
perm_log=".$perm_log.",
perm_proto=".$perm_proto.",
perm_limpeza=".$perm_limpeza.",
perm_lixeira=".$perm_lixeira.",
perm_relatusuarios=".$perm_relatusuarios.",
perm_deptos=".$perm_deptos.",
perm_deptospastas=".$perm_deptospastas.",
perm_empresas=".$perm_empresas." where id=".$iduser) or die (mysql_error());
Thank you.
PHP is kind of interesting in that it doesn't pull from $_POST like other forms when Ajax is involved. You actually will need to read the input from php://input
Here is a tiny example
$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$emailAddr = $response["email"];
Hopefully you can apply that successfully.
Edit: You can add the filter_var command to strip bad characters and sanitize the input.
$emailAddr = filter_var($response["email"], FILTER_SANITIZE_EMAIL);
$firstName = filter_var($response["firstName"], FILTER_SANITIZE_STRING);
While debugging this I would highly recommend using Chrome's Developer mode with the 'network' tab. Find your ajax call near the bottom and you can view exact header info.
I'm pulling data from Google Calendar events and wanting to display it in my HTML markup. I've got the data being pulled successfully from Google and thought I was passing it into and array the proper way and encoding into JSON. I was also able to make the GET request via JQuery and confirmed it by checking the console to see if it was received. The problem was trying to display it in the HTML markup.
But, after further debugging, it seems my JSON array isn't correct. Almost as if it duplicates itself everytime it looks for more data from Google.
Here is my code:
<?php
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('google-api-php-client-master/autoload.php');
date_default_timezone_set('America/New_York');
//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar");
$client->setDeveloperKey('my_api_key');
$cal = new Google_Service_Calendar($client);
$calendarId = 'my_calendar_id';
//TELL GOOGLE HOW WE WANT THE EVENTS
$params = array(
'singleEvents' => true, //CAN'T USE TIME MIN WITHOUT THIS, IT SAYS TO TREAT RECURRING EVENTS AS SINGLE EVENTS
'orderBy' => 'startTime',
'timeMin' => date(DateTime::ATOM),//ONLY PULL EVENTS STARTING TODAY
);
$events = $cal->events->listEvents($calendarId, $params);
$count = 0;
$items_to_show = 3;
$data = array();
foreach ($events->getItems() as $event)
{
if($count <= $items_to_show)
{
//Convert date to month and day
$eventDateStr = $event->start->dateTime;
if(empty($eventDateStr))
{
// it's an all day event
$eventDateStr = $event->start->date;
}
$temp_timezone = $event->start->timeZone;
if (!empty($temp_timezone))
{
$timezone = new DateTimeZone($temp_timezone); //GET THE TIME ZONE
}
else
{
$timezone = new DateTimeZone("America/New_York"); //Set your default timezone in case your events don't have one
}
if ($count >= $items_to_show)
{
break;
}
$eventdate = new DateTime($eventDateStr,$timezone);
$data[$count]['newmonth'] = $eventdate->format("M");
$data[$count]['newday'] = $eventdate->format("j");
$data[$count]['newtime'] = $eventdate->format("g:i A");
echo json_encode($data);
++$count; //INCREASE COUNT AND START AGAIN.
}
}
?>
Here is my JSON array (there are only 3 events on the calendar) but it looks like it duplicates or resets everytime it looks for more:
[{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"},{"newmonth":"Jan","newday":"18","newtime":"3:00 AM"}]
Here is my JQuery that I want to display in the HTML automatically:
$(document).ready(function()
{
function load()
{
$.ajax
({
type: 'GET',
url: 'googlesidebar.php',
// data: {key: 'value'},
dataType: 'json',
success: function(data)
{
console.debug(data);
for (var i = 0; i < data.length; i++)
{
$('.newmonth').append(data[i].newmonth),
$('.newday').append(data[i].newday),
$('.newtime').append(data[i].newtime)
};
setTimeout(load, 5000);
},
error: function(data)
{
//called when there is an error
console.log(data.message);
}
});
};
load();
});
HTML Markup:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="newmonth"></div>
<div class="newday"></div>
<div class="newtime"></div>
<footer>
</footer>
<script src="ajax.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Any help would be greatly appreciated!