I have a Chrome extension which communicates with an Arduino Uno with a serial connection and i want to retrieve commands from an online mysql database. I'm a newbie in javascript programming and i can't figure how to access my database through the extension.
This is my php code (it shows the message stored in the database):
if (!empty($_POST)) {
if (empty($_POST['label'])) {
$response["success"] = 0;
$response["message"] = "Inserisci la pass!";
die(json_encode($response));
}
$pass = '***';
if ($_POST['label'] == $pass) {
$cn = mysql_connect("localhost", "***", "***");
mysql_select_db("***", $cn);
$result = mysql_query("SELECT Messaggio FROM tesinafrax ORDER BY numero DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$queried_mex = $row['Messaggio'];
echo json_encode($queried_mex);
} } else { $response["success"] = 0;
$response["message"] = "Inserisci la pass!";
die(json_encode($response));
}
exit;
}else{
?>
<h1>Inserisci pass</h1>
<form method="post" action="leggimex.php">
<input name = "label" type="text"><button name="vedi"
>vedi</button></form>
<?php
}
?>
So how do i open the php, write the password in the textbox and parse the json response in order to obtain a string variable on my local chrome extension?
You cant (directly) do that. What you can do is set up a REST API in PHP and use Ajax from within your Chrome extension to interact with your API.
From a high level the flow would be: (client side) Chrome extension needs string from your database -> send an Ajax request to your PHP API (eg. yourserver/getstring) -> (backend) Your API receives the request and gets the string from your DB -> PHP API returns a JSON response -> (client side) Ajax request completes and now you have the string as a javascript variable.
This might seem like a lot, but it is probably the best way. The good news is that REST API/Javascript is a hugely popular topic and so there are a LOT of great resources out there, it will just take some research.
For your PHP backend I would checkout SlimPHP. For the Ajax portion you could use jQuery or just vanilla Javascript.
Related
Let's say I want to create a web page where users can inputs information and the page will see if that information exists in a file and then displays it to the user. This information could be an email address or a password or anything. Can this be done just with Javascript?
The front-end side can be JavaScript AJAX requesting system which will contact the server and server will process the request and give the answer to the AJAX request and display the results in real time to the user.(just as search engines do)
Only using JavaScript would be hard,as the server side requires to do a search through the given text.
The server side can use some basic string searching.
/HTML and jQuery/
<input type="text" id="txtInputStr"/>
<button type="button" id="btnFind"/>
<script>
$("#btnFind").on("click",function(){
var postData = [];
postData.push({name:'inputstr',value:$("#txtInputStr").val()});
$.ajax({
type:'post',
url:'findMe.php',
data:postData,
success:function(json)
{
var obj = $.parseJSON(JSON.stringify(json));
console.log(obj.success);
}
})
});
</script>
/php findMe.php/
<?php
$contents = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $your_file_name);
$res = array("success"=>false;);
if(strpos($contents,$_POST['inputstr']) !== false)
{
$res['success'] = true;
}
echo json_encode($res);
where your_file_name is your file name where you want to search.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
Actually, I have a javascript variable I pass this to PHP variable and use this variable as a MySQL query when I submit the query the page gets reloaded and value of the javascript variable is finished and therefore query doesn't work
I just want a modification in my code or there is another relevant solution regarding my problem then kindly please help me.
Everything works fine when echo the PHP variable it shows me the variable only problem is in the query of my SQL that in the query the PHP variable which has javascript variable is not working.
<script>
var buttontext="esteem";
<?php
$ff ="<script>document.write(buttontext);</script>";
?>
</script>
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="beelist";
$conn=mysqli_connect($servername,$username,$password,$dbname);
error_reporting(0);
$connDB= mysqli_select_db($conn,'beelist');
if($_POST['sub'])
{
echo $ff;
$code=$_POST['Bid'];
if($code!=""){
$query="SELECT beaconid FROM `customer` WHERE `beaconid` = '$code' && name = '$ff'";
$data = mysqli_query($conn,$query);
$res1=mysqli_fetch_array($data);
if ($res1) {
echo '<script> alert("Beacon found")</script>';
echo '<script> showp();</script>';
}
else {
echo '<script> alert("Beacon ID is wrong!")</script>';}
}else{
echo '<script> alert("Beacon ID is required")</script>';
}
}
?>
As I said in the comments
Where do I start, Client and Server (JS and PHP) are separate. One runs on the server one runs on the clients computer. PHP goes first and as such only PHP can affect JS (as that is part of the output of the PHP) the JS's state cannot be known in PHP as it's on a entirely different computer. Basically you are left with making a request, either from a page reload (such as form submission) or AJAX where you can pass that data back to the server so it can work on it.
Basically what you have now is $ff literally is this text:
$ff ="<script>document.write(buttontext);</script>";
And because you don't echo it, it's actually never passed to the Client as part of the source.
Your query is like this:
$query="SELECT beaconid FROM `customer` WHERE `beaconid` = '$code' && name = '<script>document.write(buttontext);</script>'";
It's too broad of a topic for me to really give you a working answer, and there are plenty of tutorials out there that can do it better justice them me. But hopefully, you understand what is going on now.
PS. you can test this easily by doing echo $query; right after the query. Also be aware you should not put PHP variables directly in SQL, or you risk SQLInjection type attacks against your site. For example if $_POST['Bid']="' OR 1 -- your query would be this:
$query="SELECT beaconid FROM `customer` WHERE `beaconid` = '' OR 1 --' && name = '<script>document.write(buttontext);</script>'";
Where -- is the start of a comment in MySQL. So now I just selected your entire table by injecting SQL commands into your Query, which is a very bad thing.
Cheers!
I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.
I have been trying to look over an example to figure out how to connect to a server's SQL database from a client using JQuery, AJAX, and PHP, and though it is old it seems well done and straight forward: Example Link.A single folder contains all of my php files as well as the product version of jQuery (javascript-1.10.2.min.js).
Problem 3 - Fixed
JS console shows [Object, "parsererror", SyntaxError] at
var id = data.data[0]; //get id, data['data'][0] works here as well
in client.php. Object responseText shows ..."No Database Selected"... I have updated my client.php based on Daedalus' response and am still getting the same error.
Error was in mislabeling a variable ($link instead of $con) in server-api.php
-- Code --
db-connect.php:
<?php
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "password";
$databaseName = "server-db";
$tableName = "inventory";
?>
server-api.php:
<?php
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'db-connect-99k.php';
$con = mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db('zgc7009_99k_db', $con);
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
client.php
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
//dataType: 'json', //data format (comment out or get parsererror)
// Successful network connection
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
$('#error_code').html("Success!");
},
error: function() {
console.log(arguments);
}
});
});
</script>
</body>
</html>
Problem 1 - Fixed
Thanks to user help, I have managed to get rid of my original error of:
OPTIONS file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. jquery.js:8706
XMLHttpRequest cannot load file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Problem 2 - Fixed [now running on temporary web server (see link at bottom)]
Now I am running WAMP (including phpmyadmin and apache) as my webserver. I can run my php page with script (client.php) no problem, it runs, can't seem to find any errors in my logs. However, I still never seem to hit the success function of my script. I am assuming that I have inappropriately set something somewhere (eg localhost/"my site".php) but I am not sure where.
I also tried changing my AJAX function a bit, to include .done:
$.ajax({
url: 'localhost/server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
}
}).done(function() {
$('#output').html("AJAX complete");
});
but my output value never gets changed within the ajax call. I could be implementing .done incorrectly, but I just can't seem to figure out why I am not hitting anything and can't seem to find a log that is a help in finding the next step.
On previous edit I removed localhost from php calls ('localhost/server-api.php' returned a 404) and now I am stuck again. I get a 304 Not Modified from my jQuery call, but I thought that, as of jQuery 1.5 ajax handled this as a success so I should still be hitting my html text update (correct?) and I don't.
WAMP access Log:
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /client.php HTTP/1.1" 200 2146
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /server-api.php HTTP/1.1" 200 38
Note - this is the only log that updates when I refresh client.php in my browser. my js console stays blank. I have uploaded this to a temp site: zgc7009.99k.org/client-99k.php
Forgive me if the following is drawn out, but I wish to explain all that I can;
Firstly, as noted in comments, the error method of the jQuery .ajax() method only gets called if there is an error when the method attempts to load the requisite php page you(or it(if you don't specify a url, it uses the current page)) has specified. An error in this regard would be something like a 404(page not found), 500(server error), or what-have-you.
The current error you are experiencing is two-fold:
You are not running a server on your computer(or you are and aren't accessing the page via the correct url in your browser(it should be localhost/path/to/file.extension)
Same origin policy is preventing your page from even being loaded
In regards to problem #1, a php page needs to be processed by your php interpreter, which you need to have installed on your system. I would recommend something like xampp to suit this case, though there are plenty others available.
When accessing a server which is running on your machine, one uses the localhost url in the address bar, no protocol(http://,https://,ftp://,etc), and never a file:/// protocol. For example, if I were to visit the folder test's index.php file, it would be localhost/test/index.php.
In regards to problem #2, browsers have various restrictions in place in order to prevent malicious code from executing.. One of these restrictions is the Same Origin policy, a policy which restricts documents of a differing origin than the originating request from accepting that request. For example..
If we have a server at domain.website.com, and it makes a request to otherdomain.website.com, the request will fail as the endpoint of the request is on a different domain.
Likewise, the same exists for any requests made in regards to a file:/// protocol.. It is always1 treated as a different origin, and it will always1 fail. This behavior can be changed, but it is not recommended, as it is a security hole.
I also recommend you check out MDN's article on SOP.
Of course, to fix all this.. install a web server(like xampp or wamp) on your machine(depending on your OS) or use a hosted web server, never open your html file by double clicking it, but by visiting its url(according to your webserver's directory(it differs per server)), and always make sure your domains and ports match.
1: Except in certain cases, such as here
Edit 1:
Don't know why I didn't see this before; we could have avoided headaches.. anyway, firstly, change the error catching you do here:
$dbs = mysql_select_db($databaseName, $con);
echo mysql_errno($con) . ": " . mysql_error($con). "\n";
To:
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
And then, change your array set after your db handling to this:
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result);
To explain what I've changed, and why.. Your first echo was causing the json parser to fail when parsing your echoed json. If you didn't have your console open during your refresh, you wouldn't have seen that it did in fact execute the ajax request. You also do not define an error handler, so you would have never known. In order to parse the new json I just created above, modify your success handler's variable declarations above into this:
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
Of course, if your mysql causes any errors, you can then access those errors with the following:
console.log(data.mysql);
Again, in your success function. To see if you have any errors with the actual .ajax() method or such, you can just do this for your error handler:
error: function() {
console.log(arguments);
}
please you should start learning to PDO or Mysqli real fast, mysql_* will soon be depreciated, that is soonest, let me rewrite your query for you using PDO and prepared statements, you can kick it off from there.
$connectionStr = 'mysql:host='.$host.';dbname='.$databaseName.'';
$driverOptions = array();
$dbh = new PDO($connectionStr, $user, $pass, $driverOptions);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $dbh->prepare("SELECT * FROM $tableName");
$query->execute();
$array = fetch(PDO::FETCH_OBJ);
echo json_encode($array);
Hello fellow coders!
I have a php script that saves the url's passed from a form to a zipped archive, which works just fine.
The only trouble is when a user submits the form after selecting a lot of urls, the user has to wait a while whilst the php script does it's stuff.
I would like to use ajax to have a sort of verbose feedback after each url is added to the zip in it's foreach loop, and also flag up if it encountered a php error (it currently does this if one of the url's was a 404 page.)
I've tried a couple of tests with AJAX but gotten nowhere.
Would this even be possible?
My line of thought is that the foreach loop would run as an external php script via AJAX, and pass it's data back to this script on success... or there may be a better way of doing it.
Any help would be greatly appreciated!
<?php
$dir = "archive/";
$site = 'http://domain.com/';
$urls = array($site);
$zipfile = 'archive-'.date('Ymd_His').'.zip';
$zip = new ZipArchive;
$newzip = $zip->open($zipfile, ZipArchive::CREATE);
if (isset($_POST['urls'])){$urls = $_POST['urls'];}
if ($newzip === TRUE) {
foreach ($urls as $url) {
$file = file_get_contents($url);
$filename = "index.html";
$namer = str_replace($site, '', $url);
if ($namer != "") {$filename = $namer;}
$zip->addFromString($dir.$filename, $file);
}
$source = "assets/";
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
if (is_dir($file) === true){
$zip->addEmptyDir($dir.str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true){
$zip->addFromString($dir.str_replace($source . '/', '', $file), file_get_contents($file));
}
}
$zip->close();
echo "Generated <a href='$zipfile'>$zipfile</a>";
} else {
echo 'failed';
}
?>
For you to use ajax to receive feedback on the progress of your PHP script you can do the following:
Create a HTML page that calls your initial PHP script for ZIP file processing through an ajax call (or using JQuery).
Modify your initial script to add data to a database events table or append/edit information to a physical file (e.g. json).
Write javascript code to query a secondary PHP script (or file) that will provide the status of the ongoing operation.
In the case you use a database, your secondary script must query the database, and provide all new information to the client about how the zip file operations are going.
So summary:
HTML page containing javascript that calls initial php script
HTML page contains function called periodically through setInterval to query URL that provides status information.
PHP script that starts the process contains calls to add status to database or file.
PHP script that returns status/progress of algorithm while running.