Dynamic posts loading with javascript and php - javascript

I've been trying to make a blog system but I've got lost at some point. The posts get generated in this format: posts/today/today.xml (for example: posts/2014-08-19/2014-08-19.xml) The xml contains the image's name, the title and the date when it was made. It's okay if I want to load today's posts, there's no problem with that but the main problem is about the posts loading which are older than a day.
I've got a function in ajax which loads the xml the only parameter it needs is the url to the xml. Let's call it loadPost(url).
I made the formatting purposely so I'd like to keep that.
I couldn't find a way to load it dynamically with php because after the php brackets are executed the variables delete right ? Or shall I use global variables ?
Now it looks like this:
<script type="text/javascript" language="javascript">
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
loadPost('posts/<?php echo $nextpost.'/'.$nextpost ?>.xml');
<?php
$nextpost = date ('Y-m-d',strtotime( '-1 day' , strtotime ($nextpost)));
echo $nextpost;
?>
}
});
</script>
I'm in really need for help, anybody got an idea how to go on ?
Thanks in advance !
EDIT:
This is called in the first few lines in index.php
<?php
session_start();
$_SESSION['dayCounter'] = 0;
$today = date("Y-m-d", time());
$nextpost = date ('Y-m-d',strtotime( '-1 day' , strtotime ($today)));
?>

Related

My Super Simple PHP Plugin is Appending an Extra Whitespace to its Output

I am brand spanking new to PHP so as a challenge I decided to try to design a super simple PHP plugin that would output a text greeting based on the time of day for a user. In order to use my plugin, you simply drop the .php file in your 'includes' folder then insert the line where you want the greeting to appear on your page.
My problem is that my plugin (named 'timely-greeting.php') is adding an extra whitespace at the end of the text output. I think I have narrowed down the problem, but first for clarity's sake, here is my whole PHP plugin code (also, I'm a noob so I'm sure I've made plenty of other logical errors/mistakes here so please let me know):
<?php
//timely-greeting.php
// Handle AJAX request (start)
if( isset($_POST['name']) ){
// Storing the timezone offset from the jQuery code
$timezone_offset_minutes = $_POST['name'];
// Convert minutes to seconds
$timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
//JS code is needed to retrieve the user's timezone dynamically so we have it set statically for now
date_default_timezone_set($timezone_name);
// Morning start and end times (12:00 AM - 11:59 AM)
$morningStart = '0000';
$morningEnd = '1159';
// Afternoon start and end times (12:00 PM - 4:59 PM)
$afterNoonStart = '1200';
$afterNoonEnd = '1659';
// Evening start and end times (5:00 PM - 11:59 PM)
$eveningStart = '1700';
$eveningEnd = '2359';
// YOU CAN EDIT THE GREETINGS HERE
$greetings = array(
"morning" => "Good morning",
"afternoon" => "Good afternoon",
"evening" => "Good evening"
);
// Retrieving the current time
$now = date('H:i');
$now = str_replace(":" , "" , "$now");
//Checking the current time of day in order to display the correct greeting
if ( ($now >= $morningStart) && ( $now <= $morningEnd ) ) {
echo $greetings["morning"];
} elseif ( ($now >= $afterNoonStart) && ( $now <= $afterNoonEnd) ) {
echo $greetings["afternoon"];
} elseif ( ($now >= $eveningStart) && ( $now <= $eveningEnd) ) {
echo $greetings["evening"];
}
exit;// Handle AJAX request (end)
}
?>
<span id="message"></span>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- Timezone offset Retrieval jQuery -->
<script>
$(document).ready(function(){
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
console.log( "TZ offset in minutes: " + timezone_offset_minutes); // logging the timezone offset in min
$.ajax({
/******* IMPORTANT: EDIT 'url' BELOW *******/
url: '../includes/timely-greeting.php', //replace the 'url:' with the new filepath for this file
type: 'post',
data: {name: timezone_offset_minutes},
success: function(response){
$('#message').text(response);
}
});
});
</script>
And this is how and where my plug-in gets used in my header.php file:
<ul class="nav navbar-nav navbar-right">
<li><?php include('includes/timely-greeting.php');?>, <?php echo $_SESSION['loggedInUser']; ?></li>
<li>Log out</li>
</ul>
This is the output I am looking for:
Good evening, Nick
But I am actually getting an extra space after the greeting, creating a space between the greeting and the comma which looks like this:
Good evening , Nick
So far I've narrowed down my problem to this line:
<span id="message"></span>
Notice that extra space between 'evening' and the comma seems to go away when I use a <div> instead of a <span> but the <div> of course creates a line break which also is a problem. This is the output now:
Good evening
, Nick
And of course my next idea was to keep the <div> tags and just add a style to make the tag inline, like style="display: inline; but that just brings me back to square one. This is my output when I use <div> tags and style them to be inline.
Good evening , Nick
SIDE NOTE: I've tried looking for a BOM to see if that's what is causing the extra space. I'm using Brackets as my code editor. I tried looking for extra characters using the Nano editor but couldn't find anything.
I would love to get the bottom of this and maybe also see if there is a better way to write this code (I'm sure there is). That way, I might be able to avoid running into these problems in the first place.
So I finally got to the root of the problem, which was the fact that I really had no clue what I was doing with my ajax request. After a lot of research I was able to reformat much of my code. This is what I did:
First of all I changed my ajax request to this:
$.ajax({
type: 'post',
data: {name: timezone_offset_minutes},
success: function(data){
$('#timelyGreeting').text(data);
}
});
Then in the header.php page where I want my greeting to display, I moved this line to the top of the page:
<?php include('includes/timely-greeting.php');?>
Then finally, I removed the tags from the 'timely-greeting.php' plugin file and instead put in my 'header.php' in the exact spot where I wanted my greeting message to go:
<span id="timelyGreeting"></span>
Now I just to understand how data is actually getting passed in my ajax request because I'm worried I'm doing something hacky here...

Call Javascript Date Code Into PHP Buffer

ISSUE:
I am attempting to call a JavaScript 'date_code' file (to get current YYYY/MM) to use as part of my 'directory URL' to store some .php files.
EXAMPLE:
"../Directory/2017/07.php" would represent the .php 'directory' file for the month of July, 2017.
NOTE:
A similar process works successfully if I am using it within a 'form submission'...
However, in this particular case, I am constructing a Cron Job, so a form will not be part of the process.
ATTEMPTS:
Among other things, I have attempted to use...
<?php $dateIndex = "path_to_date_code.js"; ?>
(as shown in the demo code below).
RESULTS:
So far... I have had no success at all being able to call in the JavaScript 'date code' or output the files to their proper destination.
SUMMARY:
If anyone could advise me what I am doing wrong or point me in the right direction, I would greatly appreciate it. Thank you in advance.
DEMO:
<?php ob_start(); ?>
<html>
<head>
</head>
<body>
<?php echo "Some Content" ?>
<?php $dateIndex = "path_to_date_code.js"; ?>
</body>
</html>
<?php echo ''; file_put_contents("../Directory/$dateIndex.php", ob_get_contents()); ?>
You are confusing the roles of PHP and Javascript. PHP runs on the server, while Javascript and your date code file only run IN THE BROWSER. The Javascript will do nothing on the server.
I don't really understand what you are trying to do, but how about constructing a path like this:
$date = date("Y/m"); // Y is 4 digit year, m is two digit month
$path = "../Directory/{$date}.php";
The braces are not really needed. They are used to isolate a variable when embedded in a string. I've added them so the variable stands out.
If you need to make a path for a given date, use this type of thing:
$date_to_use = "2015-12-12"; // whatever
$date = date("Y/m", strtotime($date_to_use));
$path = "../Directory/{$date}.php";

Jquery takes last output as value

I have some code and it is for sending comments to database.
And I have jquery and ajax code:
<script type="text/javascript">
$(document).ready(function() {
$('#comm1').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var comment = $('#comm1').val();
var fromstatid = '<?php echo $status->fromid; ?>';
var status = '<?php echo $status->id;?>';
var fromid = '<?php echo $frid; ?>';
$.ajax({
method: "POST",
url: "d/includes/counts.php",
data: {u: fromid, status: status, comment: comment, fus: fromstatid},
success: function(status) {
$('#comm1').val('');
}
});
};
});
});
</script>
#comm1 is textarea for comment ..
For php I have like basic output from database and the problem is that my jquery use only last output from database as value. In other words where ever I type a comment it send to database for the last output. It works if I have button for Reply and then it sends me to new page or something where I can limit output from database to 1 or to only that where I want to comment. But can I do it here on the page where are all comments... Also I was trying to set id as some word + php id from database for that output but it seem like when I add this to jquery code noting going to work....
The code I tried is : $("#something<?php echo $status->id; ?>").keypress.....
It stops the script it looks like the whole script is not working...
I asked similar question but no one answered me the right question... Also I was thinking of can I like make foreach in jquery here on this code.. And say for each output do something. I really don't know why it use only last output on page as value but it will help a lot if someone have some explanation?
EDITED:
Or do I need to echo for each output the jquery code?
UPDATE:
Tried by echoing the whole jquery code and it is not working....
NEW:
As you asked I have d/includes/counts.php file and the index.php
Inside counts.php i just input in database values send via ajax...
Inside index.php I said I have basic foreach database output to echo something like $status->text and for comment to echo textarea where I can type comment for text... Code is too long and I dont have problems with that code I have problems with connecting jquery code to all outputs not only last one....
Why does my var status = '<?php echo $status->id; ?>'; AND var fromstatid = '<?php echo $status->fromid; ?>'; use only last output values? Can I make some var inside echo for each output and use that var here in code to navigate which one is commented on?
I founded that also the script work only on one output like if I try to comment on the other one and press ENTER it wont work....
You must know that only the last output of the PHP file will be retrieved. So I'm wondering what did you output in the PHP file ? Can you post the PHP code please ? (Sorry, for answering here but not enough points to comment).

Minor difficulties with Ajax and PHP interaction

I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>

Reloading url page with ajax

i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?

Categories