auto refresh the div with dynamic data - php

I have a div section. I want to reload this section every 5 seconds. How do I do this. Here is my code:
<script>
$("#send_parent_general_chat").submit(function()
{
var rec = $("#data").val();
var msg = $("#msg").val();
var dataString = 'rec='+ rec + '&msg='+ msg;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Client/send_general_parent_chat_msg/<?php echo $per_job->id;?>",
data: dataString,
cache: false,
success: function(result){
$('#display_general_msg').html(result);
$('#send_parent_general_chat')[0].reset(); //form reset
}
});
return false;
});
</script>
<script>
$(document).ready(function(){
setInterval(function(){
// alert("===111==");
$("#display_general_msg").load('<?php echo base_url(); ?>" + "Client/refresh_general_parent_chat_msg/<?php echo $per_job->id;?>')
}, 5000);
});
</script>
I have created one more controller for refreshing the div I have used the time interval function but it is not loading, it shows this error:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
I need to refresh only the div content not the whole page.
How do I achieve this?

You can Use :
setTimeout(function()
{
Your_Function(); //this will send request again and again;
}, 5000);
Replace Your_Function with your Function Name.
Hope this will help !!

Below is an example which will update the contents in every 5 seconds using php websockets. This is a simple example, but you can use it to modify to fit for your application needs. You don't need the timeout functions on the client side here we use server sleep
Install the Workerman socket library
composer require workerman/workerman
The client side code
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
//alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
//alert("Message is received..." + received_msg);
document.getElementById("demo").innerHTML = "Timestamp is updated every 5 sec " +received_msg;
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
<div id="demo" style="font-size: 64px; color: red;"></div>
</body>
</html>
The Server side code
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 4 processes
$ws_worker->count = 4;
// Emitted when new connection come
$ws_worker->onConnect = function($connection)
{
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
while(true) {
$connection->send(time());
sleep(5); //Sleep for 5 seconds to send another message.
}
};
// Emitted when connection closed
$ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
};
// Run worker
Worker::runAll();
The backend service can be started with the following command from the terminal or you can autostart on boot if you want.
$php index.php start
Here index.php is our backendnd file name.
Just start the service and load the page then you can see the timestamp is updated every 5 seconds which comes from the server side. This is a working example tested on my local machine. Try and let me know if you need any other help.
The output

you can also try below one:
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
setInterval approach will be more accurate than the setTimeout approach
// or
$(function(){ // document.ready function...
setTimeout(function(){
$('form').submit();
},5000);
});

Related

Unable to run jsvascript until page refresh

I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.
<script>
$( document ).ready(function(){
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
function requestContent() {
var date = new Date();
$.ajax({
type:'POST',
url:'php/app/adminTimeline.php',
data:{
date: date.yyyymmdd()
},
success: function(data) {
if (data == '') {
alert("No data found!");
} else {
// $("#loading_spinner").css({"display":"none"});
$('#timeline-content').prepend(data);
}
},
error: function(data) {
// $("#loading_spinner").css({"display":"none"});
alert("Something went Wrong!");
}
});
}
window.onload = requestContent();
});
</script>
The document.onready method and window.onload the method seems not to be working too.
Ps: I have the Jquery library linked in the header too.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
Also you're calling requestContent()
window.onload must be function, not returning value.
$(document).ready(function(){
// here you ajax
}
https://jsfiddle.net/cqfq5on5/1/
The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.
However where you create the date object, uses this, which executes after the document is fully loaded
$(document).ready(function(){
//Code
});
This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (#sagid) pointed out, window.onload cannot be a returning value but must be a function.
i.e.
window.onload=function(){
//Code
};
This means, your solution is to change window.onload=requestContent(); to
$(document).ready(function(){
requestContent();
});
Good luck!

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

Too many connections to db error, after adding an ajax auto save

I have PHP site with MySql data base
I just added automatic save for a text area
and one of the users received the following error:
Too many connections in ...Unable to connect to database
maybe I have to change my ajax auto save:
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
in the page "ajax_for_auto_save_interview.php" I`m including the connection to the DB.
First thing is you should close your mysql connection every time you open it after your usage.
You can have a javascript variable to check whether an AJAX call is already issued and is it finished or not. Only if it is finished, you can re-issue new call
Like this:
var isAjaxStarted = 0;
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
if(isAjaxStarted == 0)
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
isAjaxStarted = 1;
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ isAjaxStarted = 0; });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
maybe I am writing late you help in place it? thank you very much
<script type="text/javascript">
bkLib.onDomLoaded(function() {
var myNicEditor = new nicEditor({buttonList : ['bold','italic','underline','strikethrough','left','center','right','justify',/*'ol','ul',*/'forecolor',/*'fontSize','fontFamily',*//*'fontFormat',*//*'indent','outdent',*/'image','upload','link','unlink'/*,'bgcolor'*/,'hr','removeformat', 'youTube'/*,'subscript','superscript'*/],/*fullPanel : true,*/
iconsPath : '<? echo "".$IndirizzoPagina."".$IndirizzoCartella."";?>default/image/EditorDiTesto/nicEditorIcons.gif'});
myNicEditor.setPanel('myNicPanel'); //PANNELLO DI CONTROLLO
myNicEditor.addInstance('titolo'); //TITOLO
myNicEditor.addInstance('contenuto'); //CONTENUTO
});
<textarea name='contenuto' id='contenuto' class='box2'>".$ContenutoNotizia."</textarea>"
i used this code http://nicedit.com/

Comunication between Express.js and PHP through jQuery Ajax

I'm developing a small project where I have a web page (index.html) loading in Express.js and it sends some data to a PHP script running on a MAMP server. The PHP script processes the data and returns a JSON encoded array back to the web page and finally the Node.js server sends data to connected clients using socket.io.
I have problems with the communication with PHP using jQuery Ajax. I send the data to PHP using POST and I know PHP receives that data but I don't know how to catch the response from PHP to know how the processing went.
I have no experience with Node.js. What can I do to make this thing work?
So far this is the code I have
Node.js - Express.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, db = require('./routes/db')
, http = require('http')
, socketio = require('socket.io')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); //Middleware
app.use('/', express.static(__dirname + '/public'));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
HTML Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Site</title>
<script src="js/jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<div id="formContainer">
<form enctype="multipart/form-data">
<input type="text" name="texto">
<button type="button" id="buttonSend">Enviar</button>
</form><br/><br/>
</div>
<script type="text/javascript">
$('#buttonSend').click(function(e){
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/NodePHP/test.php',
type: 'POST',
dataType: "json",
data: {value: 1},
success: function(data){
if(data.success == true){
alert("Perfect!");
}
else{
alert("Error!");
}
},
error: function(xhr,status,error){
//alert("Error de llamada al servidor");
alert(xhr.responseText);
//$('#botonUsarFoto').css('display','block');
}
});
});
</script>
</body>
</html>
PHP Script
<?php
$number = $_POST['value'];
echo $number;
// move the image into the specified directory //
if ($number == 1) {
$data = array("success"=>"true");
echo json_encode($data);
} else {
$data = array("success"=>"false");
echo json_encode($data);
}
?>
Thanks in advance for any help
In order to make a request with Node, we'll use the http and querystring modules. Here's an example lovingly adopted from the Nodejitsu folks:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
value: 1
});
var options = {
host: 'localhost',
path: '/myPHPScript',
method: 'POST'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(data);
req.end();
Alternatively, you could use the request module, but first things first.

Is this a true long polling?

After a lot of trials, I am successfully able to maintain continuous server connection with a database.
Now code keep checking and show the messages, if there are new in database.
Please review and tell:
if there is true long polling technique used in this code? If it is not, then please suggest, where I am wrong(deviating from long polling) and how this can be made a true long polling.
Currently, I am getting these errors. However still it maintains the continous connection with database.
**each time only one message is pulled instead of all **(I used each loop but it stops the long polling)
After every 10/15 seconds, token error appeares (Parse error (syntax error=unexpected token)).
var last_msg_id = 2;
function load_msgs() {
$.ajax({
type:"Post",
url:"getdata.php",
data:{
last_msg_id:last_msg_id
},
dataType:"json",
async:true,
cache:false,
success:function(data) {
var json = data;
$("#commidwin").append(json['msg']);
last_msg_id = json["last_msg_id_db"];
setTimeout("load_msgs()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("load_msgs()", 15000);
}
});
}
Php file is here
$last_msg_id=$_POST['last_msg_id'];
$last_msg_id_db=1;
while($last_msg_id>$last_msg_id_db){
usleep(10000);
clearstatcache();
$sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");
$sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid FROM chat_com");
$row_m=mysqli_fetch_array($sql_m);
$last_msg_id_db=$row_m['maxid'];
while($row=mysqli_fetch_array($sql)){
$textt=$row['mesg'];
$last_msg_id_db=$last_msg_id_db;
$response=array();
$response['msg']=$textt;
$response['last_msg_id_db']=$last_msg_id_db;
}
}
echo json_encode($response);
Polling is a bit harder than a simple while : just because generally all things you output to the browser will be interpreted when complete. Your example is quite clear :
success:function(data) {
var json = data;
$("#commidwin").append(json['msg']);
last_msg_id = json["last_msg_id_db"];
setTimeout("load_msgs()", 1000);
},
jQuery will wait until the response is complete to build your data variable and then will call your success callback.
One way to create long-polling is to have a task and a follower :
the task is the "infinite" loop, it displays nothing but just catch and trigger events, put in a "box".
the follower is an ajax call made every X seconds, it looks inside the "box" filled by the task, and immediately act inside the page.
Here is an example of long-polling, there is no follower, just an event (release) that stops the poll, but you'll get the idea :
<?php
// For this demo
if (file_exists('poll.txt') == false)
{
file_put_contents('poll.txt', '');
}
// If this variable is set, a long-polling is starting...
if (isset($_GET['poll']))
{
// Don't forget to change the default time limit
set_time_limit(120);
date_default_timezone_set('Europe/Paris');
$time = time();
// We loop until you click on the "release" button...
$poll = true;
$number_of_tries = 1;
while ($poll)
{
// Here we simulate a request (last mtime of file could be a creation/update_date field on a base)
clearstatcache();
$mtime = filemtime('poll.txt');
if ($mtime > $time)
{
$result = htmlentities(file_get_contents('poll.txt'));
$poll = false;
}
// Of course, else your polling will kill your resources!
$number_of_tries++;
sleep(1);
}
// Outputs result
echo "Number of tries : {$number_of_tries}<br/>{$result}";
die();
}
// Here we catch the release form
if (isset($_GET['release']))
{
$data = '';
if (isset($_GET['data']))
{
$data = $_GET['data'];
}
file_put_contents('poll.txt', $data);
die();
}
?>
<!-- click this button to begin long-polling -->
<input id="poll" type="button" value="Click me to start polling" />
<br/><br/>
Give me some text here :
<br/>
<input id="data" type="text" />
<br/>
<!-- click this button to release long-polling -->
<input id="release" type="button" value="Click me to release polling" disabled="disabled" />
<br/><br/>
Result after releasing polling :
<div id="result"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
// Script to launch polling
$('#poll').click(function() {
$('#poll').attr('disabled', 'disabled');
$('#release').removeAttr('disabled');
$.ajax({
url: 'poll.php',
data: {
poll: 'yes' // sets our $_GET['poll']
},
success: function(data) {
$('#result').html(data);
$('#poll').removeAttr('disabled');
$('#release').attr('disabled', 'disabled');
}
});
});
// Script to release polling
$('#release').click(function() {
$.ajax({
url: 'poll.php',
data: {
release: 'yes', // sets our $_GET['release']
data: $('#data').val() // sets our $_GET['data']
}
});
});
</script>
Demonstration : here.

Categories