I have a bash script that connects to a telnet port; opens some diagnostics; exits; and, opens another telnet port.
To check if the script works fine, I can execute it with jQuery and AJAX, but I'm having trouble continually updating the div with the results.
I don't want to keep calling the same command when reloading the php to the div, but just want to refresh the results.
The bash script is pretty basic:
#!/bin/bash
{
sleep 2
echo diag gps info
sleep 2
echo exit
} | telnet 10.10.2.1 1700
telnet 10.10.2.1 1800
HTML/PHP file:
<!DOCTYPE HTML >
<html>
<head>
<meta charset="UTF-8">
<title>diag stuff</title>
</head>
<body>
<button id="startGpsDiag" >Start gps diag</button>
<div id="results"></div>
</body>
<!-- <script langauge="JavaScript" src="{#javaScriptDir#}/jquery-min-1.8.js"> </script> -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery(document).ready(function () {
jQuery.ajaxSetup({cache: false});
jQuery("#startGpsDiag").click(function () {
// alert('true');
callGpsDiag();
});
function callGpsDiag(){
jQuery.ajax({
type: "POST",
url: "gpsDiag.php",
data: "execGpsDiag=1",
success: function(data) {
alert('success');
jQuery('#results').html(data);
setInterval(function() {
jQuery('#results').html(data);
},3000);
},
error: function() {
// alert('fail');
}
});
}
});
</script>
php logic file:
if(isset($_POST['execGpsDiag'])) {
echo system('./gpsdiag.sh');
}
I may want to edit the bash file and remove the last telnet connection it's the one I want to monitor and move it to the php logic with an if we are not initially setting the diagnostics the monitor the port
I have also tried doing echo system(telnet 10.10.1.2 1800)
and tried the setinterval by itself to just load the monitoring port but could not get any results
if I run gpsDiag.php from command line with either just echo system(telnet 10.10.1.2 1800) or echo system('./gpsdiag.sh'); it works and displays results to screen.
You need to set a timeout and call your function inside the timeout callback.
function callGpsDiag(){
jQuery.ajax({
type: "POST",
url: "gpsDiag.php",
data: "execGpsDiag=1",
success: function(data){
alert('success');
jQuery('#results').html(data);
setTimeout(function(){
callGpsDiag();
},3000);
},
error: function() {
//alert('fail');
}
});
}
Related
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);
});
I am trying to get response from php echo statement but I am not getting any response, my code seems fine but I don't know why it doesn't work
test.php
<?php echo "test" ?>
dashboard.php
<script type="text/javascript">
function loadlink(){
$.ajax({
url: 'test.php',
success: function (response) {
alert("Hello"),
document.getElementById("links").innerHTML=response;
}
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
</script>
<div id="links"></div>
I am testing on my localhost, I do not get any response when I open the page
I have fixed the error, I debugged using google chrome, the code is correct but apparently i did not declare java script before the code
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 :)
Using PhoneGap, I'm trying to build a basic android app that makes an AJAX call to a PHP API and return some JSON data. The code, in its entirety works on the desktop, but it doesn't seem to work for my Android when I make a build. When I build the app, install it on my device, and load it up, I get blank screen.
Here's the client that I wrote... Is there anything wrong with this code?
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css" />
</head>
<body>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use the PhoneGap API
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
url: 'http://api.example.com/test.php',
dataType: 'json',
timeout: 5000,
success: function(data, status) {
//data loaded
$('#results').append(data[0].about);
},
error: function() {
//error loading data
$('#results').append('No data received.');
}
});
$(document).ajaxError(function(event, request, settings) {
$("#msg").append("<li>Error requesting page " + settings.url + "</li>");
});
$(document).ajaxComplete(function(event, request, settings) {
$("#msg").append("<li>Request Complete.</li>");
});
}
</script>
<p id="results"></p>
<p id="msg"></p>
</body>
</html>
I also set the access origins in the config.xml to:
<access origin="http://example.com" subdomains="true" />
<access origin="*"/>
It seems that the AJAX code (and the global AJAX event handlers) is not getting called.
Be sure to have cordova.js included in the right location and available (e.g. by alert(<some cordova property>);). Then try if the onDeviceReady is called at all:
document.addEventListener("deviceready", function(){
alert("deviceready");
},false);
I am trying to directly load a page using ajax. Here are the details:
HTML:
<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>
script.js:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
do.php:
<?php
//Do whatever...
echo "Done!";
?>
What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?
As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.
I can suggest 2 things:
You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.
Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.
You could start loading immediately and then add the data when everything has completed.
var _data = null;
var _ready = false;
$.ajax({
url: 'do.php',
success: function(data){
_data = data;
tryAddData();
}
});
$(document).ready(function() {
_ready = true;
tryAddData();
});
function tryAddData(){
if(_ready && _data !== null){
$('#feedback').html(_data);
}
}