I'm tapping into the Twitter firehose to store some tweets based on some set filters for analytic purposes.
I have written a PHP script that opens a connection to the Twitter stream, and keeps it open while(!eof)...so this basically stays open indefinitely.
However, I have it set so that it stops after 5 seconds. I want to use AJAX to call this script ever 5.5 seconds (offset to make sure they don't collide), and then re-loop on success etc...
The problem is that my function doesn't seem to be receiving a "success" signal. What's going on here?
Here are the relevant portions of my code:
$(function() {
makeRequest();
});
function makeRequest(){
console.log("Getting tweets...");
$.ajax({
url: "./php/store_tweets.php",
success: function(){
console.log("Success!");
makeRequest();
}
});
}
The Script:
<?php
$start = time();
$expAddress = "HOSTNAME";
$expUser = "USERNAME";
$expPwd = "PASSWORD";
$database = "DBNAME";
$opts = array(
'http' => array(
'method' => "POST",
'content' => 'keywords,go,here'
)
);
// Open connection to stream
$db = mysql_connect($expAddress, $expUser, $expPwd);
mysql_select_db($database, $db);
$context = stream_context_create($opts);
$instream = fopen('https://USERNAME:PASSWORD#stream.twitter.com/1/statuses/filter.json', 'r', false, $context);
while (!feof($instream)) {
if (time() - $start > 5) { // break after 5 seconds
break;
}
if (!($line = stream_get_line($instream, 100000, "\n"))) {
continue;
} else {
$tweet = json_decode($line);
// Clean before storing
// LOTS OF VARIABLES FOR BELOW...REMOVED FOR READABILITY
// Send to database
$ok = mysql_query("INSERT INTO tweets
(created_at, from_user, from_user_id, latitude, longitude, tweet_id, language_code,
place_name, profile_img_url, source, text, retweet_count, followers_count,
friends_count, listed_count, favorites_count)
VALUES
(NOW(), '$from_user', '$from_user_id', '$latitude', '$longitude', '$tweet_id', '$language_code',
'$place_name', '$profile_img_url', '$source', '$text', '$retweet_count', '$followers_count',
'$friends_count', '$listed_count', '$favorites_count')");
if (!$ok) {
echo "Mysql Error: " . mysql_error();
}
flush();
}
}
?>
You should try javascript function setInterval.
<script type="text/javascript">
var myVar=setInterval(function(){makeRequest()},5000);
function myStopFunction()
{
clearInterval(myVar);
}
</script>
Related
I am creating simple request for GET a "message" with title etc from MySQL server.
So, I've got something like this in my AngularJS:
$http({
url: 'http://localhost/webpack/downloadMessage.php',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response){
console.log("CHECKED");
console.log(response.data);
}, function(response) {
alert('something wrong');
})
})
}
Just a request for data. But I'm confused with my php code, because I'm a beginner, can you help me what's wrong? I want just whole table where section = 3.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
if(!isset($_POST)) die();
session_start();
$response = [];
$con = mysqli_connect('localhost', 'root', '', 'projekt');
$query = "SELECT * FROM messages WHERE section='3'";
$result = mysqli_query($con, $query);
echo json_encode($result);
It's without errors, but in my console i've got this:
CHECKED {current_field: null, field_count: null, lengths: null,
num_rows: null, type: null}
According to a manual result of mysqli_query is either a mysql_result or false if query fails.
To get data from mysqli_result you need to fetch it, for example with fetch_assoc:
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
echo json_encode($row);
Also, there can be cases when you have no results ($row will be empty) or your query fails ($result will be false). These cases should be checked in your script and appropriate response should be returned.
I am working on a project to send sensor data to phpmyadmin table using GET request.
I am not able to see sensor data in the table when I consider my Arduino to be the client, but when I use this URL on my Google chrome browser it shows the result (ex. 40).
It seems the problem is with the Arduino code.
int samples[NUMSAMPLES];
void loop() {
// Thermistor
uint8_t i;
float average;
// take N samples in a row, with a slight delay
for (i=0; i< NUMSAMPLES; i++) {
samples[i] = analogRead(THERMISTORPIN);
delay(10);
}
// average all the samples out
average = 0;
for (i=0; i< NUMSAMPLES; i++) {
average += samples[i];
}
average /= NUMSAMPLES;
// convert the value to resistance
average = 1023 / average - 1;
average = SERIESRESISTOR / average;
float Steinhart;
Steinhart = average / THERMISTORNOMINAL; // (R/Ro)
Steinhart = log(Steinhart); // ln(R/Ro)
Steinhart /= BCOEFFICIENT; // 1/B * ln(R/Ro)
Steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
Steinhart = 1.0 / Steinhart; // Invert
Steinhart -= 273.15; // convert to C
Serial.print("Temperature ");
Serial.print(Steinhart);
Serial.println(" *C");
delay(5000);
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected to server");
// Make a HTTP request:
client.println("GET /add.php?");
client.print("Steinhart=");
client.print(Steinhart);
}
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
}
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
} // end of void setup()
And here is my PHP code: add.php file
<?php
include("connect.php");
$link=Connection();
$Steinhart = ""; // or null !!
$timeStamp="";
$Steinhart = isset($_GET['Steinhart']) ? $_GET['Steinhart'] : '';
date_default_timezone_set("Asia/Dubai");
$timeStamp = date('Y-m-d H:i:s', time());
$query= "INSERT INTO `time` (`id`, `timeStamp`, `Steinhart`) VALUES (NULL, '$timeStamp','$Steinhart')";
mysqli_query($link, $query);
mysqli_close($link);
?>
I Usually send data from the Arduino board to PhpmyAdmin(Wamp Server or XXamp) with the help of NodeJS. It is pretty easy to send data with the help of NodeJS.
Here i attach the code.
var request = require('request');
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var serialPort = new SerialPort("COM5", {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log(data);
});
});
serialPort.on('data', sendSerialData);
function sendSerialData(data) {
request({
uri: "http://127.0.0.1/write_data.php?value="+data,
method: "GET",
timeout: 10000,
followRedirect: true,
maxRedirects: 10
}, function(error, response, body) {
console.log(body);
});
}
By this you can easily send the data. Also you can just follow this link
http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/
Hope it will help
Using basic Google Chart php/mysql/javascript/html setup, where php used to retrieve data from mysql, javascript to setup chart, and then html and div pull chart in html.
But I want to change the datasource based on a user input. So i thought i would use a php variable sent via url.
I thought I would watch for the variable in my 'dbconnect.php' file, which is included in the php file that retrieves mysql data, using $_GET['var'], to change datasource based on the variable sent in url eg php?var (using a switch statement). This works fine, I can see var sent in url with an echo.
However, I expected that the javascript url: "getDataUsers.php" part would run the getDataUsers.php file to get the data from different datasource based on url passed variable. But instead nothing happens.
What am i missing? Thanks.
My index.php file:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
//added javascript variable for site from php url
**var vsite = "<?php echo $_GET['site']; ?>";**
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChartUsers);
function drawChartUsers() {
var jsonDataUsers = $.ajax({
url: "getDataUsers.php",
dataType:"json",
async: false**,
//added data value for site from js variable vsite
data: {site: vsite }**
}).responseText;
// Create our data table out of JSON data loaded from server.
var dataUsers = new google.visualization.DataTable(jsonDataUsers);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('users_chart_div'));
chart.draw(dataUsers, {
title:'# New Registered Users',
width: 1000,
height: 300,
legend : 'none',
vAxis:{title:'# users',textStyle:{color: '#005500',fontSize: '10', paddingRight: '100',marginRight: '100'}},
hAxis: { title: 'Date', textStyle: { color: '#005500', fontSize: '10', paddingRight: '100', marginRight: '100'} }});
}
</script>
</head>
<body>
<p>
a-details a</br>
b-details b</br>
c-details c</br>
d-details d</br>
</p>
<!--Div that will hold the charts-->
<div id="users_chart_div"></div>
</body>
</html>
My dbconnect.php file:
<?php
$site = $_GET['site'];
//echo "<p>I connected. The variable is: " . $site . "</p>";
switch ($site)
{
case 'a':
$server = 'server.com';
$username='a';
$password='a';
$database='a';
break;
case 'b':
$server = 'server.com';
$username='b';
$password='b';
$database='b';
break;
case 'c':
$server = 'server.com';
$username='c';
$password='c';
$database='c';
break;
case 'd':
$server = 'server.com';
$username='d';
$password='d';
$database='d';
break;
default:
echo "No database selected";
}
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( 'Unable to select database');
php?>
My 'getDataUsers.php' file:
<?php
include 'dbconnect.php';
$query =mysql_query("SELECT
YEAR(created) AS Created_Year,
MONTH(created) AS Created_Month,
DAY(created) AS Created_Day,
count(id) AS NumUsers
FROM users
Group by
YEAR(created),
MONTH(created),
DAY(created)
ORDER BY
YEAR(created) ASC,
MONTH(created) ASC,
DAY(created) ASC");
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
array('label' => 'Date', 'type' => 'string'),
array('label' => '# Users', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['Created_Year'] . '-' . $r['Created_Month']. '-' . $r['Created_Day']);
$temp[] = array('v' => (int) $r['NumUsers']);
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
You aren't passing any data with the AJAX call. You need to set the data parameter of the AJAX call to include a site parameter:
var jsonDataUsers = $.ajax({
url: "getDataUsers.php",
dataType:"json",
async: false,
data: {
site: 'a' // set the site parameter here as appropriate
}
}).responseText;
I found software called mecab that basically read a string and categorize the words into noun, verb, etc. What I'm trying to do is using a Google Search API to put the search function on my page so whenever I look up a location, e.g. Oxford street, a number of results will be displayed and mecab will take each of these result individually and do its job.
What I'm stuck at is I don't know how to feed these results to mecab.
Here are the codes:
<html>
<head></head>
<body>
<script type="text/javascript" src="http://www.google.com/jsapi?key=AIzaSyBX85AAhYSkh66lk8i2VBSqVJSY_462zGM"></script>
<script type="text/javascript">
function OnLoad()
{
// Create Search Control
var searchControl = new google.search.SearchControl();
// Add searcher to Search Control
searchControl.addSearcher( new google.search.WebSearch() );
searchControl.draw( document.getElementById( 'content' ) );
// Execute search
searchControl.execute( '新宿' );
}
// Load Google Search API
google.load( 'search', '1' );
google.setOnLoadCallback( OnLoad );
</script>
<div id="content">Loading...</div>
<?php
define('Mecab_Encoding', 'SJIS');
define('Mecab_ResultEncoding', 'UTF-8');
define('MeCab_Path', 'mecab.exe');
function morph_analysis($text) {
$text = mb_convert_encoding($text, Mecab_Encoding, Mecab_ResultEncoding);
$descriptorspec = array (
0 => array ("pipe", "r"), // stdin
1 => array ("pipe", "w") // stdout
);
$process = proc_open(MeCab_Path, $descriptorspec, $pipes);
if (is_resource($process)) {
// Feed string to macab
fwrite($pipes[0], $text);
fclose($pipes[0]);
// Read the string
while (!feof($pipes[1])) {
$result .= fread($pipes[1], 4096);
}
fclose($pipes[1]);
proc_close($process);
$result = mb_convert_encoding($result, Mecab_ResultEncoding, Mecab_Encoding);
$lines = explode("\r\n", $result);
$res = array();
foreach($lines as $line) {
if(in_array(trim($line), array('EOS', ''))) {continue;}
$s = explode("\t", $line);
$word = $s[0];
$words = explode(',', $s[1]);
if ($words[0] == "名詞"){
$res[] = array(
'word' => $word,
'class' => $words[0],
'detail1' => $words[1],
'detail2' => $words[2],
'detail3' => $words[3],
'conjugation1' => $words[4],
'conjugation2' => $words[5]
);
}
}
return $res;
} else {
return false;
}
}
$text ="今日はいい天気です。";
$result = morph_analysis($text);
echo "<pre>";
print_r($result);
echo "</pre>";
?>
</body>
</html>
So you basically have a div which populates with content from your javascript API that you want to hand to PHP. The easiest way to do this is by making an ajax call to your PHP script from javascript the same way your API is doing to populate your page. Except here you will be handing the content to PHP and getting back a result that you can then put anywhere in your page like say another div that you want.
<div id="content">Loading...</div>
You can access this content by using the getElementById property of the document with javascript.
<script>
$.ajax({
type: "POST",
data: {"text": document.getElementById('content').innerHTML },
url: "http://www.example.com/your-php-script.php", // put the URL to your PHP script here
}).done(function ( data ) {
document.getElementById('myOutPutDiv').innerHTML = data;
});
</script>
Then your HTML will have the appropriate div for output
<div id="myOutPutDiv">Output goes here...</div>
Then in your PHP script you receive the data in the $_POST/$_REQUEST super global...
<?php
$text = $_POST['text']; // This is the stuff you got from your javascript
/* Work with $text here */
Just be sure to separate the PHP from the javascript stuff as they will act independently.
I need call and pass parameter to NodeJS socket server.
I confirmed the server works well. and now I need to create PHP script to call the function.
My NodeJS code is like this,
var user = {};
socket.sockets.on("connection", function(client){
client.on("messageToClient", function(uid, msg){ // I need to call this method
user[uid].send(msg);
});
});
PHP ::
$fp = fsockopen("10.0.111.10","3000",$errno,$errstr, 30);
if(!$fp){
echo "{$errno} ({$errstr}) <br />";
}else{
$uid_parameter = 'ABC';
$msg_parameter = 'HELLO';
$out = "HOW TO CALL NodeJS messageToClient Method AND PASS PARAMETER?";
fwrite($fp,$out);
fclose($fp);
}
The more elegant solution would be just do it all in Nodejs or all in PHP. DB interaction as well. NodeJS can interact with almost every type of commonly used database. It would save you having to implement what will be a quite hacky code.
I know this question is old, but hasn't content on the internet, so I will leave the answer here for future users.
PHP:
function sio_message($message, $data) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 9501);
if(!$result) {
die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
}
$bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" =>
$data)));
socket_close($socket);
}
NODE.JS:
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
server.on("connection", function(s) {
//If connection is from our server (localhost)
if(s.remoteAddress == "::ffff:127.0.0.1") {
s.on('data', function(buf) {
console.log('data arrive');
var js = JSON.parse(buf);
console.log(js.data); //Done
});
}
});
Now you can send data from node with only sio_message('anything', 'more data');