ajax, jquery and Iframe (creating a message box system) - javascript

I'm trying to create a sort of mail on my site.
So I have a table that contains three columns, let's say (for simplicity , but in reality) , with the two int fields ( from, to ) and a timestamp (date of sending )
a part of my page , I display a list of messages with a group by to to group all messages that are destined for the same person .
Eventually I want to display the entire conversation when clicking on the message but it is not obvious.
I tried jquery ajax and then an iframe but it is not great , because on one hand it does not return me anything (white pages) and secondly the reload each second is not great .
At first I would like to display the result of my request.
I have not set callback because I do not know what to do with an application in a jquery callback . I thought the easiest way was to do my processing in php and run my loop then displays everything in the iframe .
So I put it in jquery
$( ".load_message" ).click(function() {
//On marque uniquement l'id de l'expediteur et du destinataire
// pour chercher les messages expédiés par A vers B ou inversement
var from = $(this).closest('tr').find('span.from').text();
var to = $(this).closest('tr').find('span.to').text();
$.ajax({
type: 'POST',
url: 'pages_ajax/fetch-messages.php',
data: { from: from, to: to},
dataType: "json"
});
});
setInterval(refreshIframe1, 1000);
function refreshIframe1() {
$("#messages")[0].src = $("#messages")[0].src;
}
and the php page I have this:
<?php
session_start();
require_once("../../lib_php/librairie.php");
require_once("../../config/connexion.php");
//header('Content-Type: application/json; charset=utf8');
/**
* Fonction qui retourne une liste de messages
* #return int
*/
function fetchMessages() {
if (isset($_POST['from'])) {
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$query = "SELECT `id`, `from`, `to`, `message`, `sent`, `read`, `direction`
FROM `cometchat`
WHERE `from` = {$from} || `from` = {$to} || `to` = {$to} || `to` = {$from}";
return $query;
} else {
return null;
}
}
if (isset($_POST['from'])) {
$liste_messages = fetchMessages();
if (!is_null($liste_messages)) {
$result_message = mysql_query($liste_messages);
while ($mess = mysql_fetch_assoc($result_message)):
?>
ici
<?php
endwhile;
}
}
?>
But for now nothing works I do not even have my messages while running the echo of my query in phpMyAdmin return me something. I guess I'm loosing context when reloading ($_POST are loosing themselves)
I would initially display the entire conversation in an iframe or a div, then after whatever it is automatically updated if ever there's new posts in the meantime a bit like the messaging system on Facebook with no reloading of the page.
Any help will be greatly appreciated.

it's been a while you asked the question hope u solved it. Anyway is what i can tell from your code and what you try to do:
Your jquery function have no callback (success, complete)
Your php code don't return anything, you just do a loop like you want to manipulate each record, and reading your post you want to have your ajax to read all value in a success callback... So don't need a loop except you want to parse it, just expose them with json_encode($mess);
setInterval 1s? argh!!! Will your server handle it? Use something like 10 à 30s or 4:
go for websocket solution like racket in php or use nodejs plateform (nodejs + socket.io + redis)
Hope it helped you out or someone else

Related

How to avoid double login in PHP?

I am creating a system where the objective is that only one person per user can access the system, for this I have in my DB two tables called: users and accesses What I am doing is that when person 1 logs in, it is saved in my DB the id of the session in the two tables, if person 2 with the same user tries to access then the first person to log in takes it out of the system. I do this with help with AJAX, comparing if the last user who started has the same session id then he can navigate without problem, if he does not close session.
The problem is that I make this ajax request every 10s, but I would have problems if 10,000 people or more log in, then the request will be sent to the server every 10 seconds and this could saturate the server.
Try an active field if the session is equal to 1 and if the session is equal to 0, then discard this since if the user closes the browser then I never close session and the person will not be able to access, I also tried using a ajax method to detect if you close the browser but it is not very reliable. Has anyone had the same problem? I would thank you a lot.
I leave my php and js code to display as I do:
Code JS:
$(function() {
cron(); // Lanzo cron la primera vez
function cron() {
$.ajax({
method: "POST",
url: "closeuser.php",
data: { action: 1 }
})
.done(function(msg) {
var trimmedString = msg.trim();
console.log(trimmedString)
if( trimmedString == 'success' ) { // Valida si el server devolvió 'success'
location.href='logoutuser.php';
}
});
}
setInterval(function() {
cron();
}, 10000); // cada 10 segundos
});
Code PHP:
<?php
require_once 'Connections/sesionunica.php';
$connection_s = new sesionunica();
if(!isset($_SESSION["id_user"])){
echo"<script>location.href='index.php';</script>";
}
if(isset($_POST["action"])) { // Se pasa una acción
switch(sprintf("%d", $_POST["action"])) { // ¿Qué acción?
case 1:
cerrar();
break;
default:
echo "default";
}
}
function cerrar(){
$ses = session_id();
$connection_s = new sesionunica();
$userById = $connection_s->getUsers($_SESSION["id_user"]);
if ($userById["id_sesion"] <> $ses) {
echo "success";
}
}
?>
In the same way, I cannot use websockets since there are accessibility problems with the server.
I think you could create an "access filter" that would check if the "access token" is valid or not in every request the users would make.
If the "access token" is expired, then return an HTTP status 401 (unauthorized), and, in client-side, redirect the user to login page.
Request filter is a very common resource that many REST frameworks have.

ajax callback display function closing too fast

I have a funcction in ajax callback that display a div with bootstrap alert inside. The problem is that it only stay for about half a second before it dissaspear. I'd like it to stay for 2 seconds. Async is set to false because I need form input to reload themself with the updated values and if it's set to true, I have to manually refresh the page with F5 to see the updated version.
function
$('#btnEnregistrerMembre').on('click', function (e) {
$.ajax({
async: false, type: 'POST', url: 'functionPHP.php', data: {
userID: document.getElementById('id').value, nomUtilisateur: document.getElementById('nomUtilisateur').value, estActif: +document.getElementById('actif').checked, estAdmin: +document.getElementById('admin').checked, updateMembre: 'updateMembre'
},
success: function (msg) {
ajouterMessage('messageArea', 'succes', 'Les modifications ont étés prises en compte.');
// alert('succes ajax');
},
error: function (err) {
ajouterMessage('messageArea', 'danger', 'Les modifications ont échouées.');
}
});
});
AjouterMessage
function ajouterMessage(locationID, type, message) {
var endroit = document.getElementById(locationID);
var element = document.createElement('div');
if (type == 'danger')
{
element.className = 'alert alert-danger';
element.innerHTML = '<strong>Erreur!</strong>' + ' ' + message;
}
else
{
element.className = 'alert alert-succes';
element.innerHTML = '<strong>Succès!</strong>' + ' ' + message;
}
endroit.appendChild(element);
}
Thank you for your help.
Your problem is that async is set to false. I know you want the page reload effect, but you are trying to set a value in the old page before the reload.
What is happening:
You send a request synchronously
receive the response from the server
You handle the response message and show and appropriate message
The web browser also handles the response from the server (remember, it's synchronous!)
The page reloads because the request was synchronous and not asynchronous and your message is lost
You have a few options here...
Option 1 (recommended):
You can send the request asynchronously and return whatever relevant data you need to be refreshed in the response.
Option 2:
Set a cookie with a flag to indicate what message should be set upon refresh of your page. Remember to clear the flag after reading it.
Si c'est plus facile pour toi, je peux traduire ma réponse en français.
Edit: It should be noted that synchronous AJAX is altogether not that useful. It stands for Asynchronous Javascript And XML. If you want to send a synchronous request, a simple form submission or link with some GET parameters would probably be far more simple.
Thank you for this very clear answer. However, i have a return value in the function that update the database, but how can I get the values in the modifierUtilisapeur.php page? Here is some code on the function if it can help:
update
function updateMembre($id,$nomUtilisateur,$status,$admin){
$caught = false;
$connexion = Connexion(NOM, PASSE, BASE, SERVEUR);
$requete = "update utilisateur set nomUtilisateur = '".addslashes($nomUtilisateur)."', estActif = '".$status."',estAdmin = '".$admin."' where id ='".$id."' ;";
try{
ExecRequete($requete, $connexion);}
catch (Exception $e){
$caught = true;
echo '<div class="alert alert-danger">
<strong>Erreur!</strong> Le nom d\'utilisateur existe déjà.
</div>';
}
finally{
if (!$caught){
echo '<div class="alert alert-success">
<strong>Succès!</strong> Les modifications ont étés prises en compte.
</div>';
}
}
return getMembre($id);
}
getMembre
function getMembre($nomUtilisateur){
$connexion = Connexion(NOM, PASSE, BASE, SERVEUR);
$requete = "SELECT * FROM utilisateur where nomUtilisateur = '".$nomUtilisateur."';";
$resultat = ExecRequete($requete, $connexion);
$resultat->data_seek(0);
$row = $resultat->fetch_assoc();
return $row;
}

jQuery open page in a new tab while passing POST data

I have a javascript variable called "list". I need to send it as a POST data to another page and open that page in a new tab (with the POST data present).
This code:
jQuery.post('datadestination.php', list);
sends the data all right, but ofcourse it opens the page in the same tab.
I saw some solutions to similar problems using invisible form and things like that, but I could not get them to work. Is there any simple solution?
You can send a form using the target="_blank" attribute.
<form action="datadestination.php" method="POST" target="_blank" id="myform">
<input type="hidden" name="list" id="list-data"/>
<input type="submit" value="Submit">
</form>
Then in JS:
jQuery('#list-data').val(list);
jQuery('#myform').submit();
This is an implementation of Sergey's solution.
<?php // this is save.php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
// So even if someone passed _POST[isAdmin]=true, all that he would do
// is populate _SESSION[data][isAuthenticated], which nobody reads,
// not the all-important _SESSION[isAuthenticated] key.
if (array_key_exists('data', $_POST)) {
$_SESSION['data'] = $_POST['data'];
$_SESSION['data.timestamp'] = time();
// Let us let the client know what happened
$msg = 'OK';
} else {
$msg = 'No data was supplied';
}
Header('Content-Type: application/json; charset=utf8');
die(json_encode(array('status' => $msg)));
?>
In the first page:
$.post('save.php', { data: list }, function(response){
if (!response.status) {
alert("Error calling save");
return;
}
if (response.status !== 'OK') {
alert(response.status);
return;
}
// We had a response and it was "OK". We're good.
window.open('datadestination.php');
});
And in datadestination.php add the fix:
if (!array_key_exists('data', $_SESSION)) {
die("Problems? Did you perchance attempt to reload the page and resubmit?");
// For if he did, then yes, $_SESSION would have been cleared.
// Same if he is operating on more than one window or browser tab.
}
// Do something to validate data. For example we can use data.timestamp
// to assure data isn't stale.
$age = time();
if (array_key_exists($ts = 'data.timestamp', $_SESSION)) {
$age -= $_SESSION[$ts];
}
if ($age > 3600) {
die("Data is more than one hour old. Did someone change server time?!?");
// I actually had ${PFY} do that to me using NTP + --hctosys, once.
// My own time zone is (most of the year) exactly one hour past GMT.
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data'], $_SESSION['data.timestamp']);
// keep things clean.
// From here on, the script behaves "as if" it got a _POST.
Update
You can actually merge save.php and datadestination.php and use a "saving stub" savepost.php that you can recycle in other pages:
<?php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
if (array_key_exists('data', $_POST)) {
// Timestamp sent by AJAX
if (array_key_exists('ts', $_POST)) {
// TODO: verify ts, but beware of time zones!
$_SESSION['data'] = $_POST['data'];
Header("Content-Type: application/json;charset=UTF-8");
die(json_encode(array('status' => 'OK')));
}
die("Error");
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data']); // keep things clean.
?>
Now your call becomes
$.post('datadestination.php', { data: list, ts: Date.now() }, function(){
window.open('datadestination.php');
});
and in your datadestination.php (or anywhere else) you add
require 'savepost.php';
I suggest:
Pass that list with the jquery.post() function and save it in the SESSION array.
Open a new tab with the same file/address/URL with the window.open() function.
Retrieve saved data from the SESSION array.
This seems straightforward and clean to me.

Passing a JavaScript value to PHP on completion of quiz

I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});

Request timeout

I'm using some jQuery to display tweets but once the Twitter API limit is reached, the request is sent but just keeps loading and loading. This doesn't look good. I want to be able to determine if the request is taking too long and then obviously do stuff, like cancel the request, change the styling, etc.
So this is the code that sends the request:
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "http://search.twitter.com/search.json?q="+buildString+"&callback=TweetTick&rpp=50");
document.getElementsByTagName("head")[0].appendChild(fileref);
And this is the TweetTick function:
function TweetTick(ob)
{
var container=$('#tweet-container');
container.html('');
$(ob.results).each(function(el){
/* in here, a div is built for each tweet and then appended to container */
});
container.jScrollPane(); /* just adds the scrollbar */
}
You need to cache twitter api response on your server side.
How do I keep from running into the rate limit?
I had a very similar problem lately. I use this script by Remy Sharp for most of my twitter requests: http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
What you need to realise is that the api timeout is per IP address. So if the api has timed out for you based on your testing, it won't have timed out for someone else on a different IP address. Now, if someone accessing the site is doing so within a corporation or business, and others in the same place are doing the same, that timeout will occur almost instantaneously.
To get around this you need to cache your results. The way I did this was as follows.
I created a twitter caching system using the following code:
$twitter_username = "tadywankenobi"; //
$number_of_tweets = "10";
$options[CURLOPT_URL] = 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name='.$twitter_username.'&count='.$number_of_tweets.'&include_rts=1';
$options[CURLOPT_PORT] = 80;
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 60;
$tweets = cache($options);
$twxml = new SimpleXMLElement($tweets);
echo "<ul>";
for($i=0;$i<=($number_of_tweets-1);$i++){
$text = $twxml->status[$i]->text;
echo "<li>".auto_link_twitter($text)."</li>";
}
echo "</ul>";
function cache($options) {
$cache_filename = "/var/cache/tweets.xml";
if(!file_exists($cache_filename)){
$handle = fopen($cache_filename, 'w') or die('Cannot open file: '.$my_file);
fclose($handle);
}// Check if cache file exists and if not, create it
$time_expire = filectime($cache_filename) + 60*60; // Expire Time (1 hour) // Comment for first run
// Set time to check file against
if(filectime($cache_filename) >= $time_expire || filesize($cache_filename) == 0) {
// File is too old or empty, refresh cache
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
if($response){
file_put_contents($cache_filename, $response);
}
else{
unlink($cache_filename);
}
}else{
$response = file_get_contents($cache_filename);
}
return $response;
}
What the cache function at the end does is create a file on the server and stores the twitter xml feedback in there. The system then checks to see the age of that file and if it's younger than an hour old, it takes its results from there. Otherwise, it re-accesses twitter. You need to have the file writable in the /var/cache folder (create it if it's not there).
I've kinda hacked this code together a bit, so let me know if you run into any issues with it. It also uses an auto_link_twitter() function, which creates the links required within the twitter text. I didn't write that, so I'll try and find you a link to it now.
Hope that all helps,
T
UPDATE: I can't remember where I got the auto_link_twitter() function, so here it is. If the person who wrote it reads this post, my apologies, I couldn't find the source again.
function auto_link_twitter($text) {
// properly formatted URLs
$urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
$text = preg_replace($urls, " <a href='$1'>$1</a>", $text);
// URLs without protocols
$text = preg_replace("/href=\"www/", "href=\"http://www", $text);
// Twitter usernames
$twitter = "/#([A-Za-z0-9_]+)/is";
$text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>#$1</a>", $text);
// Twitter hashtags
$hashtag = "/#([A-Aa-z0-9_-]+)/is";
$text = preg_replace ($hashtag, " <a href='http://twitter.com/#!/search?q=%23$1'>#$1</a>", $text);
return $text;
}
You can use specific jQuery methods to make a JSONP request. There is basic $.ajax method and shorthand method $.getJSON which fits better for you. To control timeout of the request you can use timeout parameter. Request exceeded timeout can be processed using the error callback.
$.ajax(
dataType: 'jsonp',
url: 'http://search.twitter.com/search.json',
data: {
q: buildString,
rpp: 50
},
jsonpCallback: 'TweetTick',
timeout: 30000,
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == 'timeout') {
alert('timeout exceeded');
}
}
);

Categories