PHP : echo message for a specified amount of time - php

I want to display a string "Your status has been posted" for something around 3 or so seconds than I want it to go away.
As of right now I have a news feed where the user can post messages and after they post it echoes that string of text until the url is re-enetered. Does anyone have any suggestions?
if ($_POST['submit'])
{
$body = $_POST['body'];
if ($body)
{
include ('connect.php');
$date = date("Y-m-d");
$email = $_SESSION['email'];
$who = mysql_query("SELECT firstname FROM people WHERE email = $email");
$insert = mysql_query("
INSERT INTO status VALUES('','$email','$body','$date')");
echo ('Your status has been posted <p></p>');
}
else
echo 'Status required to post into news feed! <p></p>';
}
?>
Status :
Thanks for your help!
Jeff

You need to add some JavaScript to do this. Here is an outline to get you started:
<p id="info-message">Your status has been posted</p>
<script>
setTimeout(function(){
document.getElementById('info-message').style.display = 'none';
/* or
var item = document.getElementById('info-message')
item.parentNode.removeChild(item);
*/
}, 3000);
</script>
Also you may want fade-out effects. For that I'd recommend using a library like jQuery or Scriptaculous.
Useful links:
https://developer.mozilla.org/en/Window.setTimeout
http://api.jquery.com/fadeOut/
http://script.aculo.us/
Oh, by the way, your script is vulnerable to SQL injection. Always escape your query parameters (or use prepared queries)!

You can't do that with php. Try Javascript instead.

Unless you go for some weird "100 Continue" approach interleaved before you present your next web page you will need to do this in javascript.
If this i to display for a period after they first see a webpage then you can have something like a This message will disappear and then add a script which is called from your tag's onLoad action which would (e.g.) sleep for three seconds and then set the content of that div to be empty.

I'd use AJAX for that. You can assure yourself that the data has been well inserted into the DB, and then show the message with javascript for amount the time you want.

If sending output to the browser, then you can use javascript to control the time-window you want your text to be visible.
If using jquery you could use .hide() http://api.jquery.com/hide/

You cannot achieve this with PHP only; you need JavaScript. Here's a simple example using jQuery: http://jsfiddle.net/4surX/

Related

Issues on using $.post to insert db data through PHP

So... I've been trying to use a JQuery post requests to insert data in my database for 2 days and can't make it work, and don't have any idea why... I bet someone already faced this issue too, so I'm here looking for this person :)
Here's the issue:
Into the html file, the part with JQuery (it's on a click event):
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$.post("add.php", eventData);
The add.php file:
$con = mysqli_connect("localhost", "root", "", "jqcalendar" );
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
mysqli_query($con, "INSERT INTO jqcalendar(title,start,end) VALUES({$title},{$start},{$end})");
mysqli_close($con);
Can't make this thing work, already tried putting echoes but it seems the php file isn't even being executed by the $.post command... If someone could help I'd really really appreciate it...
EDIT:
the title, start and end are strings previously defined with the "" !
I used the console inspection and got this error at the same line as the
$.post:
$.fullCalendar.select # index.html:35
You have to use quotes when you are specifying the value in a javascript object (otherthan for numbers).
eventData = {
title: "title",
start: "start",
end: "end"
};
Tips
Also, you can see whether there's an error with your javascript part by inspecting element. Right click and click inspect/inspect element. Then go to the console. You will see errors there if there's any once you execute the javascript part.
Also when debugging javascript part, you can use console.log() to see the values of the variables
Figured it out, the problem is within the variables "start" and "end", they're composite date type ISO8601, what was causing trouble when received for inserting into database... thank you all for your time, but now the problem is converting this date object to a custom String...

Auto redirecting to another pages at regular intervals

I want to create an application in PHP.
concept is very simple, I want to just auto load every page randomly at a regular intervals.
For example, if I entered to facebook.com, it would be auto load randomly profile.php, notifications.php, messages.php etc... I am not sure about its practicality. So my question may be stupid, but I need help. I only know meta refresh which is only for refreshing the page.
<meta http-equiv="refresh" content="5; url=http://example.com/">
But I think, using the loop , My concept will work. But I have no idea how loop will work with meta tag.
Looking strange requirement, anyhow, you can use
sleep(5)
function after your page get loads in a recursive way..
you should read this..
The below code will redirect you to the appropriate page. You could check the time stamp, and if it is so much different than the initial page load timestamp, execute the header commmand. You really would be better off using meta in this case.
Header('Location: http://www.google.com');
TrY:
while(1=1){
sleep(5);
//Use one of the following methods to refresh.
echo "<meta http-equiv=\"refresh\" content=\"5; url=/profile.php?pid=".$profile_id."\">";
Header('Location: /profile.php?pid='.$profile_id);
echo "<script>javascript:window.href.replace('/profile.php?pid=".$profile_id."');";
}
also review: Server Sent Events
I finally got the soloution,
<script>
var interval = 5; // in seconds
var pages = [
'http://website.com/link1.php',
'http://website.com/link2.php',
'http://website.com/link3.php'
];
var current_page_index = 0;
setInterval(function() {
loadintoIframe('myframe', pages[current_page_index]);
current_page_index = (current_page_index + 1) % pages.length;
}, interval * 1000); // second setInterval param is milliseconds
</script>

Retrieve constantly from database

I am doing this animation tool where I fetch a value from my database and then a picture will animate to a certain position. My question is if it is possible to retrieve data constantly or like every 5 seconds?
Somehow like this:
while(autoretreive){
$data = mysql_query("select * from ......");
}
UPDATED from here
Thanks for your answers! Made it a little bit clearer what to do! Maybe I can explain better what I'm doing in my code.
I am doing this animation program as said, where balls with information is moving around to different locations. I have one value that will be updated frequently in the database, lets call it 'city'.
First at previous page I post the balls of information I want based on the 'city' and I do like this (simplified):
$pid = $_POST['id'];
$pcity[0] = $_POST['city'];
$pcity[1] = $_POST['city'];
$pcity[2] = $_POST['city'];
//...
$while(autoretrieve) { // HOW TO?
$data = mysql_query(select * from table where city == $pcity[0] OR $pcity == [1] //...);
while($rows = mysql_fetch_array($data)){
$city = $rows['city'];
$id = $rows['id'];
if($city == example1){
"animate to certain pos"; //attached to image
}
else if($city == example2){
"animate to certain pos"; //attached to image
}
}
}
So for every update in the database the image will animate to a new position. So a time interval of 5 seconds would be great. I'm not an expert in coding so sorry for deprecated code. Not so familiar with AJAX either so what is going to be imported to the code? It is also important that the page is not reloading. Just the fetch from database.
you can do it with ajax and javascript
make one javascript function which contains ajax code to retrive data from database
and at your page load using setTimeout call your ajax function at every 5 second
You can use sleep function to control how often you want to fetch data.
while(autoretreive){
$data = mysql_query("select * from ......");
//output your data here, check more in link about server sent events bellow
sleep(5);
}
Since you haven't specified how you plan to access data I'm writing this answer assuming Server-Sent Events as they are only ones that make sense according to your question.
Now all this was according to your question which wasn't very clear on how do you plan to use data. Again you'll most likely want to fetch data using ajax, but Server Sent Events can also be a good way you could achieve this.
And don't use mysql_* it's deprecated, switch to PDO or mysqli_*

Looking to connect back with the server upon exit. Any form of Javascript / jQuery / AJAX trap out there I can set?

First things first. I'm running CodeIgniter on a PHP/MySQL site.
I've been tasked with creating a "shell" application for a series of movies that a person can view for a training website that I'm building. The idea here is that a person would be able to log on to a page, click "Take Course" and have it log what time the course was taken. Then, when the person exits the page carrying the movie, I would be able to record what time the course was ended. This way I can compare the start and end times, and determine if the user had viewed most of the film in order to give the user credit. Well, the first part is easy. First, I've built a table in my database with the following fields:
intKey (intKey(10))
strHash (varchar(255))
dtBegan (datetime)
dtEnded (datetime)
varIpAddress (varchar(255))
I've put in a controller that does this:
$ip_address = $_SERVER['REMOTE_ADDR'];
$data['hash'] = md5(time() . "Proof of Concept!");
$this->db->query("INSERT INTO pocTime SET strHash = '" . $data['hash'] . "', dtBegan = now(), varIpAddress='$ip_address'");
$this->load->view('welcome_message',$data);
OK... easy enough, yes? I also know that when I am done, I want to launch a file that does this:
$ip_address = $_SERVER['REMOTE_ADDR'];
$this->db->query("UPDATE pocTime SET dtEnded = now() WHERE strHash = '" . $data['hash'] . "' AND varIpAddress='$ip_address'");
What I'm hoping to do is have a page that is called by the 1st block of code, and set a "trap" so to speak so that the 2nd block of code is run by some kind of "post back" if the rendered page is closed. Any suggestions? I know that I could put some sort of big "CLICK HERE TO END YOUR VIDEO" type button that would cover this, but I'm looking to run code on some form of exit from a page, because I don't know what the user would do after viewing the video. Any thoughts?
Simple but should work, using jQuery
$(window).unload(function(){
$.get("test.php?dim1=turn&dim2=off");
});
Using unload which jQuery documentation tells what triggers this:
http://api.jquery.com/unload/
Using get which jQuery documentation is here:
http://api.jquery.com/get/
Or you can use post as well
$(window).unload(function(){
$.post("test.php", { dim1: "turn", dim2: "off" } );
});
http://api.jquery.com/jQuery.post/
You are looking for jQuery's unload event.
I would also recommend that you use Codeigniter's Active Record Syntax in your database queries. Not only does it make writing INSERT and UPDATE queries much easier, it will also escape and sanitize your input to protect you from SQL injection.

Using PHP to flag a form for insert or update function

wondering what the the best way to achieve something is.
To summarise, I have a form that I load by ajax which I use for to both update and insert new rows into a database. To determine whether it is an update or an insert I use the below code (updated forms use the mysql query to populate the form fields).
My code seems sloppy and not best practice. Are there any other suggestion on what would be the best way to do this?
<?
require_once("config.php");
$insert = false;
$update = false;
$targID = 0;
if(isset($_POST['targID'])){
$targID = $_POST['targID'];
$targRow = mysql_fetch_array(mysql_query("select * from events where eventid=$targID"));
$update = true;
}else{
$insert = true;
}
?>
<script type="text/javascript">
var insert = <? echo $insert; ?>+0;
var update = <? echo $update; ?>+0;
......javascript button events, validation etc based on inssert/update
</script>
You already know in the client whether it is an update or an insert, by the fact that you send or do not send the POST data item. So I would write JS in the original page to control the submit and what to do with the data that is sent back. It's difficult to write code without seeing the rest of the page, but at pseudo-code level, you could do the following:
use onsubmit() to catch original submit action
look to see if targID provided
if yes, send update request to server. When row data comes back, fill out form details and display form (you can 'show' a hidden DIV containing the form, for example)
if no - do you need to send anything? - just reveal an empty form (again, show a previously hidden DIV)
Hope this is useful in some way.
You should use native mySQL:
INSERT ... ON DUPLICATE KEY UPDATE
See:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
What's the point in determining that on the client side? Does it make any difference?
For the server side I'd use $targID passed from the hidden field. if it's greater than zero - update, otherwise - insert.

Categories