I work on a web interface which receives and send informations to a distant PostGreSQL database.
From what I found on the internet it seems that the best way is to create a small php script in an external .php file.
I followed that idea,
so I have that script pg_connection.php which tests the connectivity to my database (with a pg_connect) in that style :
$db = pg_connect("host=localhost port=5432 dbname=**** user=**** password=****")
or die("Not Connected");
if ($db) {echo (Connected);} else {echo (Not Connected);}
If I launch only that pg_connection.php in my webbrowser, it works fine (I just have wrotten Connected with the correct login infos entered in my script or Not connected if I put a random ip address).
Then in my .js(+jquery) external script I use :
$(document).ready(function(){
$("#dbstatus").load("php-services/pg_connection.php");
var dbstatus = new String();
dbstatus = $("#dbstatus").val();
if (dbstatus == "Connected")
{ /*jquery code to show a green light on a section in my html page*/}
else { /*jquery code to show a red light*/}
}
And that works partially :
In my $("#dbstatus") object it will replace the default text by Connected or Not Connected,
But it doesn't produce any effect on the green/red light in my conditionnal
Then I went in my Chrome console and type dbstatus, and I realized that the content of my var is
<div id="dbstatus" class="span3">Connected</div>
when I expected it to be just "Connected".
Any idea on how to clean that var from all these extra html stuffs ?
Is there more simple method implemented in js or Jquery to check a postgreSQL database status ?
Try to modify your code to:
$db = pg_connect("host=localhost port=5432 dbname=**** user=**** password=****") or die("0");
if ($db) {echo "1";} else {echo "0"}
And in JS:
$(document).ready(function(){
$.ajax({
url: "http://fullpathto/php-services/pg_connection.php",
cache: false
}).done(function( result ) {
if(result=="1") {
/*jquery code to show a green light on a section in my html page*/
}
else
{
/*jquery code to show a red light*/}
}
});
});
Instead of $("#dbstatus").val(); use $("#dbstatus").html();.
Related
I'll try to give a brief summary of the project and then the current code approach.
I have a RPi all set up with the latest Stretch OS.
I have installed MySQL, PHP, APahce and PhpMyAdmin and it working correctly.
I have it booting up to the default (locally hosted) webpage and in full screen (KIOSK) mode.
DB created, tables populated, queries in place.. and the webpage (drink menu) is displaying correctly as expected.
I have my Arduino UNO connected to the RPI via USB
The webpage displays a bunch of menu options.. each with its own 'order' button.
When any order button is clicked.. I save this button data to a hidden field, and use jQuery to submit/post the form (to itself)
Upon $_POST I grab this submitted data, and send it out via PHP over serial comm 1.
And here is where I am currently.
Since my Arduino is connected via USB to the RPi. I can not use the serial monitor to debug things.... do I have any other options here?
When I submit the webpage.. I -do- see the RX/TX lights on the Arduino blinking (leading me to believe it is receiving the serial data).. I can/will check if it is correct tonight by hooking up the stepper motor again and see if ti moves to the correct position(s)...
Here is where I am stuck/stumped a bit.. and could use some discussion to get me on the right path.
So after the Arduino 'does its magic'.. it is supposed to send a confirmation message back to the RPi.. saying the drink is complete.. and I can go back to the main drink menu awaiting another order
Because the webpage has already $_POSTed..and the serial data sent to the connected Arduino.. .. I then leave the page displaying a 'please wait' message... but because the page is already parse on the server side of things, I am left with the need on how to 'listen' to the serial posrt via PHP now.
I figured.. I could use some AJAX to call/load an external php script.. that will just wait/listen to the serial port.. and return the data to the AJAX 'success' callback.
But as I have never done this before.. I'm kind of leery if this will work.. or if this is even the correct way to do so.
Also random questions about the best place(s) to open and close the port.. especially if there is 2 separate scripts? (ie: can I open the port in one script.. and still access it in another? or does that file accessing it.. need to be the one that opens it?)
Here is my current snippet to handle the sending and waiting/listening of the serial port:
[code]
<?
if ($mode == 'submit') {
//grab posted data (save to var)
$drinkRecipe = $_POST['selectedDrink'];
//set-up com port
exec("mode /dev/ttyACM0 BAUD=9600 PARITY=N data=8 stop=1 xon=off");
//saw this on several RPi posts? (but not sure of the difference? or why one would be used over the other?)
//stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
//open serial port
$fp = fopen("/dev/ttyACM0", "w+"); //w = write w+ = read/write
//check if open
if (!$fp) {
echo "Not open";
//die();
} else {
//if open send data (via PHP) to connected Arduino on serial comm port 1 (ttyACM0)
fwrite($fp, '<' . $drinkRecipe . '>');
//arduino takes serial data, parsed it.. does it duty,
//and is supposed to reply back via serial to the awaiting (listening)
//PHP script executed via AJAX, since the front end needs to display
//a 'waiting' type message.. and the callback 'success' will
//re-direct back to menu/initial state
?>
<script type="text/JavaScript" language="JavaScript">
$.ajax({
//async: false,
//type: "POST",
url: "serial_listener.php",
//define success handler actions
success: function(response) {
//alert("PHP RETURN CHECK: "+response);
if($.trim(response) == 'complete'){
alert("Drink making is complete... return to main menu");
//do redirect here
}else{
alert("Some value other than 'complete' was returned... look into it!");
//not sure what to do? (back to main menu anyways?)
}
},
//define error handler actions
error: function(response) {
alert("PHP SERIAL READ FAIL: "+ 'Ready State: '+ response.readyState + ' Status: ' + response.status);
}
});
</script>
<?
//close connection
fclose($fp); //needed? //should this go in the external php script instead now?
}
}
Not even sure what should go into the: serial_listener.php script yet... just a while loop or something? Waiting for data? or end of file or something? (not sure how that works using fread() on serial port?)
Any suggestions to try and wrap my head around this is appreciated.
Update: I'm not sure if I am not explaining things correctly/clearly?
But when the page submits (to itself).. that is when the OUTGOING serial data is sent to the connected (via USB to the RPi) Arduino....
When the page 'posts' it sends the above data OUT.. and then displays a 'please wait' type of message.
At this point (as far as I understand it).. the server side script/parse is now COMPLETE... and I am left with a page saying 'please wait'...
There is no more parsing/server side ANYTHING going at this point..
That is why I thought/brought up the use an AJAX call to an external script that can sit and 'wait' (listen) to the serial port (un-clear as to how best going about this... a while() loop or something?)...
and then when the data eventually comes back...
*
(which there is no telling how long it will take for this 'serial
feedback' from the Arduino.. as each drink takes different amounts of
time to create).........
*
it will use the AJAX 'success' callback function to then update the page.. and ultimately just re-direct it back to the main drink menu page again.. to start all over.
I dont feel the use of timeout() or delay() on the Arduino is not only bad advice (ie: never use delay() if can help it)..... but I dont even see where/why that makes any sense?
Update:
And the contents of the serial_listener.php script: (script the AJAX snippet calls)
//set-up com port
exec("mode /dev/ttyACM0 BAUD=9600 PARITY=N data=8 stop=1 xon=off");
//open serial port
$fp = fopen("/dev/ttyACM0", "w+"); //w = write w+ = read/write
//check if open
if (!$fp) {
echo "Not open";
//die();
} else {
while(!feof($fp)){
$response = fread($fp, 10);
}
echo $response;
fclose($fp);
}
Final update:
I re-wrote things to use the AJAX call to SEND my data.. and also wait for the response.
The external php script the AJAX call executes is the ONLY place the port gets opened now (and I am not closing it)
Here is the SUBMIT state of the PHP form that has the AJAX call:
The sending of data works 100% of the time.. but I can NOT read my response.
if ($mode == 'submit') {
//grab posted data (save to var)
$drinkRecipe = $_POST['selectedDrink'];
?>
<div id="waitingContainer">
<p>Please wait, your brink is being made.</p>
</div>
<script type="text/JavaScript" language="JavaScript">
console.log("ajax routine hit");
//var drinkRecipe = "<?php echo $drinkRecipe ?>";
var drinkRecipe = "<?=$drinkRecipe?>";
var xhr = $.ajax({
//async: false,
type: "POST",
url: "serial_listener.php",
//datatype: "html",
datatype: "text",
data:({"drinkData":drinkRecipe}),
//define success handler actions
success:function(response) {
//alert("PHP RETURN CHECK: "+response);
if($.trim(response) == 'complete'){
console.log("Drink making is complete... return to main menu");
//do redirect here
}else{
console.log("Some value other than 'complete' was returned... look into it!");
console.log("RESPONSE SENT WAS: " + response);
//not sure what to do? (back to main menu anyways?)
}
//kill the request
xhr.abort();
},
//define error handler actions
error: function(response) {
console.log("PHP SERIAL READ FAIL: "+ 'Ready State: '+ response.readyState + ' Status: ' + response.status);
//kill the request
xhr.abort();
}
});
</script>
<?
}
Here are the contents of the serial_listener.php script the AJAX call executes:
//data sent from AJAX call (works)
$drinkData = $_POST['drinkData'];
//open serial port
$fp = fopen("/dev/ttyACM0", "w+"); //w = write w+ = read/write (works)
//$fp = fopen("/dev/ttyUSB0", "w+"); //w = write w+ = read/write //tried with USB-TTL cable too.. couldnt even send data)
//check if open
if (!$fp) {
echo "Not open";
//die();
} else {
if($drinkData != ''){
//send drink data
fwrite($fp, '<' . $drinkData . '>');
//wait for response
$chars = "";
do{
$char = fread($fp, 1);
$chars .= $char;
}while(strlen($char) < 1);
echo $char;
}else{
echo 'drink recipe is empty';
}
}
Can't comment to make a suggestion (no reputation)
I have no knowledge on Ajax , jquery, Raspberry Pi or PHP but...
If you have a Serial to USB TTL device like this you can use the SoftwareSerial library. Set up SoftwareSerial on a couple of unused digital pins on the arduino and send debugging info out there.
Not an answer, but a suggestion.
*********Edit***********
Come to think of it, doesn't the Raspberry Pi have a serial port?
If so you don't need the USB converter. Just set up a softwareSerial port on the Arduino and use that to connect to the Pi. Taht way you can use the USB port to send debug coms to your computer.
First, I dont have expirience with Raspberry nor Arduino, but do have played with serial communication in the past.
You are making things waay too complicated. Serial communication is not some strange animal from history channel - take it as a data layer. You would easely create needed front- and backend IF data would come from/go to database? Now, implement your system exactly same way, just instead of database connection use Serial communication.
Your serial_listener is simple:
create/configure port
send data
read data
close port
So, whole case:
frontend --post(d)--> serial_listener::COM1::send(d) ... COM1::read('OK') -->reply 'success'
PS.
with those small controllers... timeout() is your real friend ;)
And for serial communication I would suggest to use some library (e.g. php_serial.class)
I try to clarify with a code. I try to keep it as simple, just to illustrate the system as a whole.
Frontend, pure js/html and AJAX request:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body onLoad="$('#loading-image').hide();">
<div width="100%" style="text-align: center;">
<div id="demo">
<h2>Content: forms/scripts/...</h2>
</div>
<div>
<button type="button"
onclick="makeSerialCall('serial.php')">order (send AJAX call to php script)
</button>
</div>
</div>
<img id='loading-image' src='https://media.tenor.com/images/011ebf9c192d1c9b26f242d526ee24bb/tenor.gif'></img>
<script>
var string = 'data which is collected from content above';
function makeSerialCall(url) {
$('#loading-image').show();
$.ajax({
type: "POST",
url: url,
data: string,
cache: false,
success: function(response){
$('#loading-image').hide();
console.log(JSON.stringify(response['info']));
//and whatever else you want to do afterwards...
}
});
}
</script>
</body>
Serverside:
<?php
if(!empty($_POST))
$data = $_POST["data"];
include "php_serial.class.php";
$serial = new phpSerial();
$serial->deviceSet("/dev/ttyUSB0");
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");
$serial->deviceOpen();
$serial->sendMessage($data);
$read = $serial->readPort();
$serial->deviceClose();
header('Content-type: application/json');
$response_array['status'] = 'success';
$response_array['info'] = 'some additional info:'.$read;
echo json_encode($response_array);
?>
This way you have "loading.." image on the screen until response. Initial rendered page is there all the time. Ofcourse, you need alot of (error)checking, solution when there's no response from serial etc.etc. But basic system is not "rocket science".
I am trying to get the output of a remote server's text file to display on my website. I am using an AJAX call to call my PHP script, and in the PHP script I am using file_get_contents to output the text, however, it immediately says connection refused.
So my question is, what is the reason I am getting connection refused when trying to output text from my remote server?
app.js:
$(document).ready(function(){
$("button").on('click', function() {
console.log("im in here now!");
$.get("../lib/getoutput.php", function(data){
console.log("Here is the output: " + data);
});
});
});
getOutput.php
<?php //getoutput.php
$user = 'user';
$password = 'pass';
$path = '/my/path';
$gateway = '10.139.X.X';
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
echo "get request received!";
$report = file_get_contents("ftp://$user:$password#$gateway/$path");
echo $report;
}
?>
Not the recommended way, instead use curl.
If you still wants to use this function, enable few php directives: http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
I am having a bizarre problem that I cannot figure out. It is quite possible that I just do not know something fundamental which is the cause. I really have no idea. Anyway; I have a function on a page that uses mysql to look up divisions; then it has buttons for each division; and when you click each button; a team list for each division appears within a div container. the buttons send a "div_id" value to the container. The container then uses ajax to go back to mysql and then look up the teams for that division and output information on them. This is all working. But when I try and have the php file which is called from ajax list a simple href link for each team; the links do not appear. It really seems that I cannot have href links present in the php file that is called by ajax.
I do not think I need to post all of the code for all the buttons and all that, if so please let me know; here is the script that does the ajax call on the php file:
<script>
function MyRadFunction(DivId) {
var answer = DivId;
$.ajax({
cache: false,
type: 'GET',
url: 'http://jba.gtdsites.com/gscript3_links.php',
data: 'answer=' + answer,
dataType: 'html',
success: function(response) {
$('#ajax_content').html(response);
}
});
}
</script>
and here is the php file that is called:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
/* Connect to a mysql database using driver invocation */
$dsn = 'mysql:dbname=gtdtables;host=gtdtables.db.1567753.hostedresource.com';
$user = 'username';
$password = 'password';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT * FROM teams WHERE div_id=$div_id";
foreach ($dbh->query($sql) as $resultsg1)
{
$team_id=$resultsg1[team_id];
$team_name=$resultsg1[team_name];
echo "<a href='/team-schedules/?gc_start=2&team_id=<?php echo $team_id; ?>'><?php echo $team_name; ?></a><br/>";
echo $team_name . "<br/>";
echo $team_id . "<br/>";
?>
Teams Page not link
Final Exam 1
<?php echo $team_name; ?><br/>
<?php
}
}
?>
I echoes the team name and team id just fine; and where i just have it print text that works as well; but all of the html hyperlink stuff just does not appear; I tried a few different ways. Can anyone tell me why this is happening?
Your error is kinda funny, but here it is, upon examining the site, on the network tab the markup built from PHP is rendered correctly. But the thing is:
The CSS is the problem:
a { color: #fff; }
Your text color on the links are white. Therefore its not seen, but its there, just change it accordingly.
a { color: #000; } /** or which color you want **/
And in your PHP, properly concatenate the values:
echo "<a href='/team-schedules/?gc_start=2&team_id=".$team_id."'>".$team_name."</a><br/>";
Important note: Don't just directly use variables inside your statements, use prepared statements to produce safer queries. Here is a tutorial for that.
Background: I am attempting to run some AJAX on keyup in a search box that will go to the database for a lookup, then return the results without refreshing the page.
The Problem: I'm not confident that it's actually connecting to my database. I've tested the connection using THIS METHOD, and it says that it's successful for the credentials I'm using. However, I can change the host from locahost to www.MYDOMAINNAME.com OR the server name from my cPanel, and it still says it's a successful connection. If it's successful, then why isn't it running my SQL?
The Question: Is there something wrong with my code below, and if not, is there a better way for me to test what's happening?
Notes: The output in my console is "Error [object Object]". It's hitting search.php successfully, so I don't think it's a file path issue. I also ran the PHP on page load instead of doing it through AJAX and everything seemed to work just fine. I was able to get some results back when I hard-coded a value for $query.
File Structure:
(ROOT FOLDER)
index.php (where the form is)
(PHP FOLDER)
search.php
(JS FOLDER)
search.js
HTML:
<form action="php/search.php" method="post">
<input type="search" class="main-search" name="query" />
<div class="btn btn-lg btn-primary">Search</div></form>
</form>
jQuery:
$(function() {
$(".main-search").keyup(function() {
search($(this).val());
});
});
function search(query) {
$.ajax({
url:"./php/search.php",
type:"POST",
dataType:"json",
data: { query:query },
success: function(data) {
$(".result").html(data);
},
error: function(data) {
$(".result").html(data);
}
});
}
PHP:
<?php
$query = $_POST["query"];
$link = mysqli_connect('localhost', 'USER', 'PASS') or die ('Error connecting to mysql: ' . mysqli_error($link));
mysqli_select_db($link, 'DB_NAME');
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT actual FROM icons WHERE synonym = '$query'")) {
$row = mysqli_fetch_array($result);
echo $row["actual"];
mysqli_free_result($result);
}
else {
echo "No results found.";
}
mysqli_close($con);
?>
Try changing the AJAX call data paramenter to this
data: { 'query':query }
I think this should work
Just navigate and run the php code directly instead of relying on an AJAX call to test. If there is a connection error then it should be displayed in your echo statement in the browser.
Make sure you have php error reporting running.
I'm trying to learn some javascript and i'm having trouble figuring out why my code is incorrect (i'm sure i'm doing something wrong lol), but anyways I am trying to create a login page so that when the form is submitted javascript will call a function that checks if the login is in a mysql database and then checks the validity of the password for the user if they exist. however I am getting an error (Illegally Formed XML Syntax) i cannot resolve. I'm really confused, mostly because netbeans is saying it is a xml syntax error and i'm not using xml. here is the code in question:
function validateLogin(login){
login.addEventListener("input", function() {
$value = login.value;
if (<?php
//connect to mysql
mysql_connect(host, user, pass) or die(mysql_error());
echo("<script type='text/javascript'>");
echo("alert('MYSQL Connected.');");
echo("</script>");
//select db
mysql_select_db() or die(mysql_error());
echo("<script type='text/javascript'>");
echo("alert('MYSQL Database Selected.');");
echo("</script>");
//query
$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
//check results against given login
while($row = mysql_fetch_array($result)){
if($row[login] == $value){
echo("true");
exit(0);
}
}
echo("false");
exit(0);
?>) {
login.setCustomValidity("Invalid Login. Please Click 'Register' Below.")
} else {
login.setCustomValidity("")
}
});
}
the code is in an external js file and the error throws on the last line. Also from reading i understand best practices is to not mix js and php so how would i got about separating them but maintaining the functionality i need?
thanks!
You can't mix PHP and JavaScript in this way as all of your PHP has already executed on the server before any of your JavaScript executes on the client.
The error is because the client is receiving and failing to execute this as JavaScript:
function validateLogin(login){
login.addEventListener("input", function() {
$value = login.value;
if (<script type='text/javascript'>alert('MYSQL Connected.');</script>...
// etc.
To interact with PHP from the client, you'll have to make another HTTP request -- either by <a> click, <form> submit, or Ajax request (using jQuery.post for brevity; see Using XMLHttpRequest for further details):
function validateLogin(login){
login.addEventListener("input", function() {
$.post('/validateLogin.php', { login: login }, function (result) {
if (result === "true") {
login.setCustomValidity("Invalid Login. Please Click 'Register' Below.")
} else {
login.setCustomValidity("")
}
});
});
}
Adjust the URL, /validateLogin.php, as needed; but create a PHP file for this URL similar to:
<?php
$value = $_POST['login'];
mysql_connect(host, user, pass) or die(mysql_error());
mysql_select_db() or die(mysql_error());
$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row[login] == $value){
echo("true");
exit(0);
}
}
echo("false");
exit(0);
?>
What is wrong? You simply break your JavaScript by inserting <script> parts to your if condition. So you get if (<script type='text/javascript'>alert('MYSQL Connected.');</script>... and so on... Next thing: you're trying to match $value, which is JavaScript variable, with $row[login] in PHP loop - you don't have $value there! These are separated codes. It's all wrong.
Jonathan Lonowski explained it very good how you should do this.