So I'm trying to create a custom script for a website of mine, and I'm looking at doing a status script. now I've done some research however I have scrapped what I have until I can find something that works better.
I am currently using fopen to check if a port is open, however it slows the page load time down considerably, I was wondering if there is a way to do this is jquery and ajax. allow the page to load first, then present an image if the port was open, and an alternate image if it was closed or inaccessible.
I've seen it done before, I just can't seem to find any documentation on this.
Load the page, send an ajax request to your page to check if it's open or not.
$.getJSON('checkstatus.php', {
port: 8070
}, function (data) {
if (data.status === 'on') {
$('#img').attr('src', 'on.png');
} else {
$('#img').attr('src', 'off.png');
}
});
<?php
......code.....
header('content-type: application/json');
echo json_encode(array('status'=>get_port_status($_GET['port'])));
edit :
//checkstatus.php
<?php
$host = $_GET['host'];
$ports = array(PORT 1, PORT 2, PORT 3, PORT 4, PORT 5, PORT 6, PORT 7, PORT 8, PORT 9);
$status = array();
foreach($ports as $port) {
$connection = #fsockopen($host, $port);
if (is_resource($connection)) {
$[$port] = 'on';
fclose($connection);
} else {
$[$port] = 'off';
}
}
header('content-type: application/json');
echo json_encode($status);
?>
///status.html
<table id="portStatus">
<tbody></tbody>
</table>
<script>
$(function () {
var table = $('#portStatus tbody');
var hosts = ['host1.com', 'host2.com'];
for (var i = 0; i < hosts.length; ++i) {
var host = hosts[i];
$.getJSON('checkstatus.php', {
host: host
}, function (data) {
var tr = $('<tr/>');
tr.append($('td').html(host)); //this appends the hostname to the td;
for (var port in data) {
tr.append($('<td><img src="' + (data[port] === 'on' ? 'accept.png' : 'error.png') + '"></td>');
}
table.append(tr);
});
}
});
</script>
This should give you a basic idea, try it and modify it.
Note, the javascript part uses jQuery.
Related
I have created a chatbot using chatscript. It works perfectly in .cmd when I execute a chatscript.exe program.
Now I am trying to run the chatbot the browser using xampp.
I have done the following steps:
I have installed XAMPP on C drive.
In XAMPP > HTDOCS folder I have added the Chatscript folder in it.
I am using Better web interface provided by chatscript.
When I try to run the index.php file, the bot doesn't reply.
Please find below code used in the web interface.
Index.php
<!DOCTYPE HTML>
<html>
<head>
<title> CHATSCRIPT SERVER
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
#responseHolder {
min-width: 600px;
min-height: 300px;
width: 80%;
height: 300px;
overflow: auto;
margin: 10px auto;
background-color: pink;
}
</style>
</head>
<body class="bgimg">
<div id="responseHolder"></div>
<form id="frmChat" action="#">
<p>
Enter your message below:
</p>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="txtUser" name="user" size="20" value="" />
<input type="hidden" name="send" />
</td>
</tr>
<tr>
<td>Message:</td>
<td><input type="text" name="message" id="txtMessage" size="70" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="send" value="Send Value" /></td>
</tr>
</table>
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var botName = 'rose'; // change this to your bot name
// declare timer variables
var alarm = null;
var callback = null;
var loopback = null;
$(function(){
$('#frmChat').submit(function(e){
// this function overrides the form's submit() method, allowing us to use AJAX calls to communicate with the ChatScript server
e.preventDefault(); // Prevent the default submit() method
var name = $('#txtUser').val();
if (name == '') {
alert('Please provide your name.');
document.getElementById('txtUser').focus();
}
var chatLog = $('#responseHolder').html();
var youSaid = '<strong>' + name + ':</strong> ' + $('#txtMessage').val() + "<br>\n";
update(youSaid);
var data = $(this).serialize();
sendMessage(data);
$('#txtMessage').val('').focus();
});
// any user typing cancels loopback or callback for this round
$('#txtMessage').keypress(function(){
window.clearInterval(loopback);
window.clearTimeout(callback);
});
});
function sendMessage(data){ //Sends inputs to the ChatScript server, and returns the response- data - a JSON string of input information
$.ajax({
url: 'ui.php',
dataType: 'text',
data: data,
type: 'post',
success: function(response){
processResponse(parseCommands(response));
},
error: function(xhr, status, error){
alert('oops? Status = ' + status + ', error message = ' + error + "\nResponse = " + xhr.responseText);
}
});
}
function parseCommands(response){ // Response is data from CS server. This processes OOB commands sent from the CS server returning the remaining response w/o oob commands
var len = response.length;
var i = -1;
while (++i < len )
{
if (response.charAt(i) == ' ' || response.charAt(i) == '\t') continue; // starting whitespace
if (response.charAt(i) == '[') break; // we have an oob starter
return response; // there is no oob data
}
if ( i == len) return response; // no starter found
var user = $('#txtUser').val();
// walk string to find oob data and when ended return rest of string
var start = 0;
while (++i < len )
{
if (response.charAt(i) == ' ' || response.charAt(i) == ']') // separation
{
if (start != 0) // new oob chunk
{
var blob = response.slice(start,i);
start = 0;
var commandArr = blob.split('=');
if (commandArr.length == 1) continue; // failed to split left=right
var command = commandArr[0]; // left side is command
var interval = (commandArr.length > 1) ? commandArr[1].trim() : -1; // right side is millisecond count
if (interval == 0) /* abort timeout item */
{
switch (command){
case 'alarm':
window.clearTimeout(alarm);
alarm = null;
break;
case 'callback':
window.clearTimeout(callback);
callback = null;
break;
case 'loopback':
window.clearInterval(loopback);
loopback = null;
break;
}
}
else if (interval == -1) interval = -1; // do nothing
else
{
var timeoutmsg = {user: user, send: true, message: '[' + command + ' ]'}; // send naked command if timer goes off
switch (command) {
case 'alarm':
alarm = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
break;
case 'callback':
callback = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
break;
case 'loopback':
loopback = setInterval(function(){sendMessage(timeoutmsg );}, interval);
break;
}
}
} // end new oob chunk
if (response.charAt(i) == ']') return response.slice(i + 2); // return rest of string, skipping over space after ]
} // end if
else if (start == 0) start = i; // begin new text blob
} // end while
return response; // should never get here
}
function update(text){ // text is HTML code to append to the 'chat log' div. This appends the input text to the response div
var chatLog = $('#responseHolder').html();
$('#responseHolder').html(chatLog + text);
var rhd = $('#responseHolder');
var h = rhd.get(0).scrollHeight;
rhd.scrollTop(h);
}
function processResponse(response) { // given the final CS text, converts the parsed response from the CS server into HTML code for adding to the response holder div
var botSaid = '<strong>' + botName + ':</strong> ' + response + "<br>\n";
update(botSaid);
}
</script>
</body>
</html>
ui.php
<?php
// ============= user values ====
$host = "localhost"; // <<<<<<<<<<<<<<<<< YOUR CHATSCRIPT SERVER IP ADDRESS OR HOST-NAME GOES HERE
$port = 8080; // <<<<<<< your port number if different from 1024
$bot = "rose";
// <<<<<<< desired botname, or "" for default bot
//=========================
// Please do not change anything below this line.
$null = "\x00";
$postVars = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
extract($postVars);
if (isset($send))
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$userip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$userip = $_SERVER['REMOTE_ADDR'];
}
$msg = $userip.$null.$bot.$null.$message.$null;
if(!$fp=fsockopen($host,$port,$errstr,$errno,300))
{
trigger_error('Error opening socket',E_USER_ERROR);
}
// write message to socket server
fputs($fp,$msg);
while (!feof($fp))
{
$ret .= fgets($fp, 512);
}
fclose($fp);
exit($ret);
}
Please find below screenshot of the issue:
Issue while accessing chatbot on localhost:8080
I am having difficulty in connecting my chatscript server and localhost. Please let me know what should I change in UI.php so that bot will send the reply.
Thanks in advance.
There is one error in the UI.php file. The $ret variable breaks because it is not declared. If you add $ret = ''; just above fputs the code should work:
// write message to socket server
$ret = '';
fputs($fp,$msg);
while (!feof($fp))
{
$ret .= fgets($fp, 512);
}
fclose($fp);
exit($ret);
}
Besides the $ret correction, upon running in XAMPP, as the web host is Apache, so client uses port 8080 or 8088, upon using CS over Web.
ChatScript as server, start the ChatScript system with using port 1024 ( or user-defined) is needed.
Furthermore, Harry Bot is also called in index.php file, change to Rose as in ui.php file.
I have CS responses after doing these.
I have this little problem with downloading my xlsx-file.
I am sending my request for the file over jquery Ajax and on the backend the data is correctly collected and assembled to a xlsx-file. So now on its way back to the frontend i am setting all the headers in preparation to force download the file, but the download never starts.
These are the response headers of my request:
Connection Keep-Alive
Content-Disposition attachment; filename="export.xlsx"
Content-Length 346420
Content-Type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date Mon, 23 Nov 2015 13:23:30 GMT
Keep-Alive timeout=5, max=91
Server Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
Set-Cookie <cookiesettings>
content-transfer-encoding binary
x-powered-by PHP/5.6.12
imho the download should start immediately, but nothing happens.
EDIT:
Until now I used a form submit, but the data amount is really big so the time which is needed to assemble the file is also really long and sometimes a couple of minutes or even an hour, so this was no longer possible.
So I built a java-job to build the file and startet an ajax snippet which asks for completion every second or so.
So here is my Code.
Frontend:
This is called on button-click
download: function (type, maximum) {
var
self = this,
oParams = this.oTable.oApi._fnAjaxParameters(this.oTable.fnSettings()),
aoPost = [
{ 'name': 'exportType', 'value': type },
{ 'name': 'exportMax', 'value': maximum },
{ 'name': 'handleId', 'value': self.options.handleId }
],
nIFrame, nContentWindow, nForm, nInput, i
;
// Call a self made function to get extra search parameters
// without call an data update AJAX call.
self.oTable.fnSettings().addAdditionalSearchData(oParams);
// Create an IFrame to do the request
nIFrame = document.createElement('iframe');
nIFrame.setAttribute('id', 'RemotingIFrame');
nIFrame.style.border = '0px';
nIFrame.style.width = '0px';
nIFrame.style.height = '0px';
document.body.appendChild(nIFrame);
nContentWindow = nIFrame.contentWindow;
nContentWindow.document.open();
nContentWindow.document.close();
nForm = nContentWindow.document.createElement('form');
nForm.className = 'export-table';
nForm.setAttribute('method', 'post');
// Add POST data.
var formData = {};
for (i = 0; i < aoPost.length; i++) {
nInput = nContentWindow.document.createElement('input');
nInput.setAttribute('name', aoPost[ i ].name);
nInput.setAttribute('type', 'text');
nInput.value = aoPost[ i ].value;
nForm.appendChild(nInput);
formData[aoPost[ i ].name] = aoPost[ i ].value;
}
// Add dataTables POST.
for (i = 0; i < oParams.length; i++) {
nInput = nContentWindow.document.createElement('input');
nInput.setAttribute('name', oParams[ i ].name);
nInput.setAttribute('type', 'text');
nInput.value = oParams[ i ].value;
nForm.appendChild(nInput);
formData[oParams[ i ].name] = oParams[ i ].value;
}
nForm.setAttribute('action', '/service/exportTableData');
// Add the form and the iFrame.
nContentWindow.document.body.appendChild(nForm);
// Send the request.
//nForm.submit();
// Send the request.
var form = $(nContentWindow.document.body).find('form.export-table');
var jobId = 0;
form.ajaxForm(
{
'showMessagesOnSuccess': false
},
{
'getData': function () {
return formData;
}
}
).data('ajaxForm').submit();
}
The Ajax request on submit:
$.ajax({
type: 'POST',
url: self.handler.getServiceUrl(),
timeout: GLOBALS.AJAX_REQUEST_TIMEOUT,
cache: false,
data: (<get the Data>)
,
success: function (response) {
if (response.success === true) {
// Check if we have to wait for a result.
if (response.jobId !== undefined && response.jobId !== 0) {
self.checkJobStatus(response.jobId);
} else {
<success - show some messages>
}
} else {
self.handler.error(response);
}
},
error: function () {
<Show error Message>
}
});
The CheckJobStatus:
checkJobStatus: function (jobId) {
var self = this;
$.ajax({
type: 'POST',
timeout: GLOBALS.AJAX_REQUEST_TIMEOUT,
cache: false,
data: { 'jobId': jobId },
url: self.handler.getServiceUrl(),
success: function (response) {
if(response !== null && response.data !== undefined) {
if (response.data.isFinished === true) {
if (response.success === true) {
// Check if we have to wait for a result.
self.handler.success(response);
} else {
self.handler.error(response);
}
} else if (response.success === true && response.data !== null) {
setTimeout(
function () {
self.checkJobStatus(jobId);
},
500
);
} else {
Helper.logFrontendError();
}
} else if (response !== null && response.success === true) {
setTimeout(
function () {
self.checkJobStatus(jobId);
},
1000
);
} else {
Helper.logFrontendError();
}
},
error: function (response) {
Helper.logFrontendError();
}
});
}
Backend - php:
(...)
if ($action == 'exportTableData' || $action == 'exportChartData') {
$responseData = $service->execute();
if(isset($responseData->data['contentType']) && $responseData->data['contentType'] != null && isset($responseData->data['data'])) {
$this->sendTextData($responseData->data['contentType'], $responseData->data['data']);
} else {
$this->sendJsonData($responseData);
}
} else {
$this->sendJsonData($service->execute());
}
(...)
private function sendTextData($contentType, $data) {
$this->set('filename', 'export.xlsx');
$this->set('data', $data);
$this->response->type($contentType);
$this->render('/Layouts/excel', 'excel');
}
(...)
$handlerResult = new HandlerResult();
if($dataServiceResult == null) {
$service = new DataService();
$dataServiceResult = $service->exportTableData(
$controller->Auth->User('id'),
json_encode($request->data),
null
);
} else {
if ($dataServiceResult->header->resultKey == 0) {
$handlerResult->wsData['data'] = $dataServiceResult->data;
$handlerResult->wsData['contentType'] = $dataServiceResult->contentType;
}
}
$handlerResult->wsResultHeader = $dataServiceResult->header;
return $handlerResult; // ++++ this result returns to the first codeblock in this section ++++
Backend - java - This is where the File is assembled:
(...)
if (jobId > 0) {
FrontendJobStatus status = FrontendJobQueue.getJobStatus(context.userId, jobId);
this.result = (WSExportTableDataResult) status.getResult();
logger.info((this.result.data == null) ? "ByteArray is EMPTY" : "ByteArray is NOT EMPTY");
} else {
this.jobId = FrontendJobQueue.addJob(this.context.userId, new ExportTableDataJob(this.context, this.postData));
this.result.header.jobId = this.jobId;
}
(...)
The Jop:
<Workbook assembly>
ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out);
this.result.data = out.toByteArray();
this.result.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// this.result.contentType = "application/vnd.ms-excel";
this.result.setResultHeader(APIConstants.RESULT_SUCCESS);
Layout/excel:
<?php
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
ob_clean();
echo $data;
EDIT 2:
So I tried to open a new window on success with the Data, and i could start the download, but the file ist no valid xlsx File anymore.
var reader = new FileReader();
var blob = new Blob([response.responseText], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
reader.readAsDataURL(blob);
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}
Any Ideas?
After a lot of research i found this site and the essence of its statment is that jquery ajax does not support receiving binary data, but provides a solution for implementing plain xhr request which support blob transfer.
The Site:
http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
To expand on my comment, instead of trying to send back binary data via ajax, simply save to a temp file , send the file reference back to js. On receiving the file reference, simply set window.location.href to point to a filereading endpoint, passing the file reference. I have done this a few times and it works fine even on ancient browsers:
$('#start').click(function(){
$.post('/createfile.php', {some:data}, function(response){
if(response.started){
pollFile(response.fileId);
}
});
);
function pollFile(fileId){
$.get('/filestatus.php?fileid=' + fileId, function(response){
if(response.fileCompleted){
window.location.href = '/downloadfile.php?fileid=' + fileId;
}else{
setTimeout('pollFile', 5000, fileId);
}
});
}
//createfile.php
$fileId = uniqid();
SomePersistentStorage::addJob($fileID);
//start file job here, code should run in a seperate process/thread, so
//either use a job queue system, use shell_exec or make an http request,
//then once job is queued/started:
header('Content-Type: application/json');
echo json_encode(['started'=>true, 'fileId'=>$fileId]);
//processjob.php - the file that does the work, could be your java
//program for example, just using php here for consistency
//after file is done
file_put_contents($filepath, $data);
SomePersistentStorage::updateJob($fileID, true);
//filestatus.php
$fileId = $_GET['fileid'];
header('Content-Type: application/json');
echo json_encode(['fileCompleted'=>SomePersistentStorage::isJobCompleted($fileID)]);
//downloadfile.php
$fileId = $_GET['fileid'];
$filepath = 'tmp/' . $fileId . '.tmp';
//correct headers here, then
readfile($filepath);
unlink($filepath);
If you dont want to imediatly delete the file, then you could just run a cron to delete files in the specific folder, that are older than x.
I have tried to get the image from gallery and upload the selected image to server using webservices in titanium.
I have used below code. But am getting the debug error : HTTP error And also it shows the alert box like "There was an error during the connection"
This code is working fine in my development server.But it is not working in my client server. What's the reason ? why my code is not working in my client server ?
The file upload is working fine when upload the file from android device.But it's not working while upload a file from iphone device.Can you please give me a idea to resolve this issue ?
Why am getting this error on my console window.
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var request = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}
else{
alert(this.responseText);
}
},
onerror: function(e){
Ti.API.debug(e.error);
alert("There was an error during the connection");
},
timeout:20000,
});
var uploadabc = event.media.imageAsResized(400 , 400);
request.open("POST",url+"client/manager/at_manager_create_common_file.php");
var params = ({"manager_id": manager_id,"file": uploadabc,});
// var params = ({"manager_id": manager_id,"file": event.media,});
request.send(params);
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]
});
}
EDIT:
this is php file :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$manager_id = $data['manager_id'];
$file_name = $data['file_name'];
$source = base64_decode($data['source']);
include "db_connect.php";
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * from at_common_files WHERE user_id = '$manager_id' and file_name = '$file_name'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$response='{"Error":"1","Message":"Filename already existed"}';
echo $response;
} else {
$upload_dir = 'common_files/'.$manager_id."_".$file_name;
file_put_contents($upload_dir,$source);
$qugery = mysql_query("insert into at_common_files (user_id,file_name) values ($manager_id, '$file_name') ");
$response = '{"Error":"0","Message":"Successfully file is created"}';
echo $response;
}
?>
EDIT:
As am getting the below error :
: [DEBUG] HTTP error
: [INFO] IN ERROR {"type":"error","source":{"cache":false},"code":404,"error":"HTTP error","success":false}
if i have call the same url and pass a manager_id alone , am getting the results fine.if i have passing the manager_id and file, this time only am getting the Http error. i can't find a exact issue.Because the same titanium code and php code (development server)is working fine and the image is uploading to development server folder. but i have moved the same php file to my client server.now it is not working . also the same web service url is working fine in browser and android.it's not working in iphone only.so that exactly i can't find where is the issue ? can you please give me a solutions.
EDIT :
please refer the below link:
http://developer.appcelerator.com/question/174462/image-not-uploading-from-iphone#comment-224007
I have facing a exact same issue.could you please give me a solution.
i have found many questions like this (e.g. The 'Passive' connection '<appname>' access to protected services is denied).
the answer is always:
"This error is what's known as a "Red Herring". It's a clue that's misleading. The HID isn't a real error that affects your app. There should be other messages that may indicate what's going on."
so look if there is a other error massege which describes your problem.
for example try to escape the filename you are using within the sql statements:
$file_name = mysql_real_escape_string($data['file_name']);
Make sure your device is connected to the internet and then try it like this:
Titanium:
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info('IN ERROR ' + JSON.stringify(e));
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}else{
alert(this.responseText);
}
};
xhr.open('POST', url+"client/manager/at_manager_create_common_file.php");
xhr.send({
media: event.media,
manager_id: manager_id
});
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]*/
});
}
PHP:
<?php
//this function returns a random 5-char filename with the jpg extension
function randomFileName()
{
$length = 5;
$characters = 'abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string . '.jpg';
}
//create the random filename string and uploads target variables
$randomString = randomFileName();
$target = 'common_files/'.$randomString;
if(move_uploaded_file($_FILES['media']['tmp_name'], $target))
{
echo "success";
}
else
{
echo "moving to target failed";
}
?>
For more info check this link: http://code.tutsplus.com/tutorials/titanium-mobile-build-an-image-uploader--mobile-8860
If it works like this you will have to add your logic again (resizing and manager_id)
I would like to know how i can change or repeat certain elements in php.
Right now i am using a script to fetch what song is playing from a shout-cast info page.
And in JQuery i have a player with a playlist that switches stream.
Now the only thing it does right now is just switch to the stream and not display anything.
So how would i go about on calling an php part inside jQuery?
Gosh, i really hope im being clear enough in my explanation.
For those who are able to help me
What parts of my code do you want me to display?
i wil then go ahead and paste that for you Right away! :)
Greets,
Kus.
Code for Arjan:
JQUery
$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer",
cssSelectorAncestor: "#jp_container"
}, [
{
title: "test",
mp3: "http://178.156.201.212:8018/;stream/1",
<?php
$host = "178.156.201.212"; // ip or url of shoutcast server
$port = "8018";
?>
},
{
title: "test2",
mp3: "http://stream1.slowradio.com/;stream/1",
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
?>
},
{
title: "test3",
mp3: "http://108.61.73.119:8022/;stream/1",
<?php
$host = "108.61.73.119"; // ip or url of shoutcast server
$port = "8022";
?>
},
], {
swfPath: "js",
supplied: "oga, mp3",
wmode: "window"
});
$("#jquery_jplayer").bind($.jPlayer.event.play, function(event) {
//$('#fetch').html(jPlayerPlaylist.playlist[jPlayerPlaylist.current].title);
$('#fetch').empty();
$('#fetch').append(myPlaylist.playlist[myPlaylist.current].title);
});
});
PHP
<?php
$host = "178.156.201.212"; // ip or url of shoutcast server
$port = "8000"; // port of shoutcast server
$fp = #fsockopen("$host", $port, $errno, $errstr, 30);
if($fp)
{
fputs($fp,"GET /7.html HTTP/1.0\r\nUser-Agent: GET SEVEN (Mozilla Compatible)\r\n\r\n");
while(!feof($fp))
{
$data .= fgets($fp, 1000);
}
fclose($fp);
$data = ereg_replace(".*<body>", "", $data);
$data = ereg_replace("</body>.*", ",", $data);
$data_array = explode(",",$data);
$listeners = $data_array[0];
$status = $data_array[1];
$peak_listeners = $data_array[2];
$maximum_listeners = $data_array[3];
$unique_listeners = $data_array[4];
$bitrate = $data_array[5];
$track = $data_array[6];
}
$title = chop($track);
$select = explode(" - ",$title);
$artist = chop($select[0]);
$title = chop($select[1]);
?>
<?php
if($status == 1)
{
echo $artist. " - " .$title;
}
else
{
print 'document.getElementById("title").innerHTML = "Offline";';
}
?>
Calling PHP inside jquery is done by this code:
$.ajax({
type: "GET",
url: 'this_file.php',
success: function(html) {
var data = html.split(' ');
var host = data[0];
var port = data[1];
}
});
Your PHP would be:
if ( isset($_GET['update']) ) {
die($host.' '.$port);
}
This code loads html from the php file and puts it in the HTML body tag. Ofcourse you can change body to any element.
For more specific help, post some of your PHP and jQuery code please.
Edit: Full documentation on: http://api.jquery.com/jQuery.ajax/
Maybe this works:
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
?>
Has to be
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
echo 'host: '.$host;
echo 'port: '.$port;
?>
Next time, make sure you give your code right away. That saves a lot of time and downvotes I guess.
I am using javascript to connect websocket:
<script>
var socket;
var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);
</script>
I got the error:
Can't establish a connection to the server at
var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);
How can I solve this issue?
NOTE : I enabled websocket in mozilla to support web socket application.
and when i run in chrome i got error:
can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
Apparently firefox 4 has websockets disabled because of vulnerabilities. To quote From this article:
WebSocket disabled in Firefox 4
Recent discoveries found that the protocol that Websocket works with is vulnerable to attacks. Adam Barth demonstrated some serious attacks against the protocol that could be used by an attacker to poison caches that sit in between the browser and the Internet.
I solved my error by following code through this link
http://www.flynsarmy.com/2010/05/php-web-socket-chat-application/
and created socketWebSocketTrigger.class.php file for response message where code as
class socketWebSocketTrigger
{
function responseMessage($param)
{
$a = 'Unknown parameter';
if($param == 'age'){
$a = "Oh dear, I'm 152";
}
if($param == 'hello'){
$a = 'hello, how are you?';
}
if($param == 'name'){
$a = 'my name is Mr. websocket';
}
if($param == 'today'){
$a = date('Y-m-d');
}
if($param == 'hi'){
$a = 'hi there';
}
return $a;
}
}
and added code in send function of 'WebSocketServer.php' for calling 'responseMessage' function which response request message
public function send($client, $msg){
$this->say("> ".$msg);
$messageRequest = json_decode($msg,true);
// $action=$messageRequest[0];
$action = 'responseMessage';
$param = $messageRequest[1]['data'];
if( method_exists('socketWebSocketTrigger',$action) ){
$response = socketWebSocketTrigger::$action($param);
}
$msg = json_encode(
array(
'message',
array('data' => $response)
)
);
$msg = $this->wrap($msg);
socket_write($client, $msg, strlen($msg));
}
it's working great.
Are you trying to run the client in Firefox? According to the documentation:
As of Feb/10 the only browsers that
support websockets are Google Chrome
and Webkit Nightlies. Get it from here
http://www.google.com/chrome
Try running it in Chrome and see if that works for you.
First of all your mistake is using php function with javascript require_once 'WebSocket.php'; and secondly go through the tutorial as in the link below.
http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
it's working fine.
Thanks,