I just wanted to retrieve some PHP/Mysql stuff at the beginning of my app (authentication and x and y data) from the users which I later plan to emit to the app.js (one time at the beginning and once the user disconnects update x - y values).
So basically I have set up Nodes.js and understood that some stuff is not possible like before (e.g with plain php)
Where I already have a problem is the AJAX php request in the index.html of my nodes Server
Schema:
app.js: pull Data from the /Client/index.html (I think need to do it via sockets)
index.html: get or post data via Ajax to a php file and get the values of the database back to the index.html(JavaScript)
then send that data via sockets to the app.js
php: select mysql database
retrieve values from mysql
parse them via Json and make them available in the index.html file Nodes.js (Client)
Maybe somebody of you have a solution
Nodes.js /Client/index.html:
function checkuser(username, password) {
var myObj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myObj = xhttp.responseText;
var i = 0;
while (i <= myObj.length) {
//console.log("ASQL found and Auth Username:"+ myObj[i].username) ;
console.log(myObj.username);
i++;
}
}
};
xhttp.open("GET", "/client/is_user.php?username333=" + username + "&password333=" + password, true);
xhttp.send();
}
is_user.php:
<?php
require('config_sql.php');
$email = stripslashes($_GET['username333']);
$email = mysqli_real_escape_string($con,$email);
$password369 = stripslashes($_GET['password333']);
$password369 = mysqli_real_escape_string($con,$password369);
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password369)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$response = array();
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
echo $jsonData;
mysqli_close($con);
?>
atm is not retrieving the username form the created json on the php side.
If I console.log(myObj); it's showing the me complete php.file data as plain text if I want to retrieve the username from MySql its saying undefined.
Is the php Interpreter actually working when I post/get via Ajax in a Node.js environment?
Normally when I was programming with pure php all the request worked well.
Thank you in advance.
Check you code for recieving result from query:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
Should be so:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row_user;
}
$jsonData = json_encode($response);
Related
I have been spending lots of time trying to figure out the issue. Nothing is working though. It continues to send the PHP file as text.
This is my javascript file with the ajax request.
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "http://localhost:8000/createTable.PHP";
//send ajax request
ajax.open(method, url, true);
ajax.send();
//retrieve table data
ajax.onreadystatechange = function () {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
//convert data to array
alert(this.responseText);
var data = JSON.parse(this.responseText);
}
and this is my php file which is alerted as is on my website.
//connect to MYSQL
require_once('../connectSQL.php');
//query
$result = mysqli_query("SELECT * FROM fitness");
//
$to_encode = array();
while ($row = mysqul_fetch_assoc($result)){
$to_encode[] = row;
}
echo json_encode($to_encode);
mysqli_close($dbc);
//fclose($myfile);
My php file work fine when I'm sending json from javascript file to php for storing in database. However, now that I'm retrieving data from database, seems like the PHP file is not being read as PHP.
I have tried changing all sorts of things in httpd.conf. Using apache 7 and mac osx.
You must insert PHP tags, so the server understands this code as PHP
in this case it would look like this:
<?php
//connect to MYSQL
require_once('../connectSQL.php');
//query
$result = mysqli_query("SELECT * FROM fitness");
//
$to_encode = array();
while ($row = mysqul_fetch_assoc($result)){
$to_encode[] = row;
}
echo json_encode($to_encode);
mysqli_close($dbc);
//fclose($myfile);
?>
I am attempting to use JavaScript and Jquery to search a database. I have set up a generic query.php file so that I can pass in the database and query and have it return an array. For some reason, when I try to select all using the *, my PHP server crashes with:
I am using the built in server with PHP 7.0.2. I am attempting to retrieve information from a Oracle database.
Here is the post statement:
$.post(DB1.filename,
{sid: DB1.sid,
username: DB1.username,
password: DB1.password,
host: DB1.host,
port: DB1.port,
sql: query},
function(res){
if(res == -1){
res = errorCode(DATABASE_CONNECTION_ERROR);
} else {
var a = parseObject(res);
var t = parseTable(a);
elements[TABLE].element.innerHTML = t;
}
log(FILE_NAME, "RETRIEVED query ");
}
);
Here is the query.php:
<?php
/* This script will connect to a database and search the given SQL string.
If the connection cannot be established, it will return -1. Otherwise, it will return a JSON array.
*/
//Parameters
$sql = $_POST["sql"];
//Database Information
$user = $_POST["username"];
$pass = $_POST["password"];
$host = $_POST["host"];
$port = $_POST["port"];
$sid = $_POST["sid"];
$connection = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host .")(PORT = " . $port . ")) (CONNECT_DATA = (SID = " . $sid . ")))";
//Establish connection
$conn = oci_connect($user, $pass, $connection);
//Check connection
if(!$conn){
echo -1;
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
oci_fetch_all($stRows, $res); //This is where the everything actually crashes
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
So if I set the query as:
query = "select TABLE_NAME from ALL_TABLES";
everything works just fine. A table with a single column will be printed to the screen.
However, if I run:
query = "select * from ALL_TABLES";
I get the error above.
This happens regardless of which table I am attempting to connect to. My credentials are correct and I have tried different credentials as well. Any ideas why this is happening?
--UPDATE--
I tried hard coding the column names. I can select up to 8 columns before it crashes.There are 152 rows.
I circumvented the error by swapping the oci_fetch_all for oci_fetch_array as follows:
<?php
...
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
$res = array();
while($row = oci_fetch_array($stRows, OCI_NUM)){
$res[] = $row;
}
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
This meant drastic changes to the function used to decode the JSON object array, but it does work. I will not mark this answer as correct though because I would very much like to know why my original code wasn't working...
I am using the following code to send mysql database content into a javascript array. This works fine when I start the page, but when the database gets a new entry, the new entries are not added to the array when I rerun this bit of code - unless I reload the entire page.
<p><button onclick="save_image()">Send image</button></p>
<script type="text/javascript">
function save_image(){
var userName =
<?php
$conn = new mysqli(.........."); //connect to database
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
console.log(userName)
}
</script>
I realize there are other pages about this topic, but I didn't know how to apply them to my case. If you have some ideas. Thanks.
If you want to get information from the database without reloading the page, you'd need to do an Ajax request to retrieve the information.
Something like this would work:
PHP - ajaxendpoint.php
<?php
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>
JavaScript
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //log the response from the database
//if the PHP is returning a JSON object, you can parse that:
var myArray = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "ajaxendpoint.php", true);
xhttp.send();
}
HTML - index.html
<button onclick="getData()">
Load Data via Ajax
</button>
Here is another example Ajax request in this JS Fiddle: https://jsfiddle.net/igor_9000/77xynchz/1/
Recently I am learning single page application, but I got a problem, the project I am working on is inside a folder that contain many folders, php js are folders in side the main folder, and each contain its type of files, the problem is that one of the php file called getmax.php gives me the maximum id ,I want to use this max(id) in a js file called module.js in order to give the new module the next id , the module.js should gives this id to another php file called insert.php ,the connection between the module.js and insert.php is working properly if I set the id manually . but I could not figure out how can I make it use the max(id) from the getmax.php file.
note: I noticed lately I'm using MySQL and I should used mysqli I will fix it later.
the getmax.php is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id, create_user FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$max = mysql_fetch_assoc($qur);
}
if ($max){
$json["max"] = $max;
if ($max["password"] == $password){
$json["username"] = $username;
$json["id"] = $max["id"];
$json["create_user"] = $max["create_user"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
if ( $table == 'module' ){
$statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;
//$statement .= ' GROUP BY create_user' ;
$statement .= ' WHERE create_user = 19 ' ;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
PHP and JS are run on the server and client respectively, and as such you cannot call methods/functions of one from the other. AJAX exists to pass values between JS and serverside code.
This is my js script :
$.getJSON(riceviPaginaPrincipale, {tipo: "Principale"}).done(function(data) {
$("#contenitorePaginePrincipali").empty();
$.each(data.risultato, function(){
$("#contenitorePaginePrincipali").append('<button class="btnMenu">'+this['Nome']+'</button>');
});
$("#contenitorePaginePrincipali").append('<button class="btnMenu" onclick="creaPagina()"> Crea nuova pagina </button>');
});
and this is my php script :
<?php
//It includes session script php and global variables
include('../../sessione.php');
$tipo = $_POST['tipo'];
if(!$conn){
mysqli_close($conn);
$_SESSION['error'] = "Connessione al database pagine fallita.";
}
else{
$comando = "select * from Pagine where Tipo='$tipo'";
$result = mysqli_query($conn, $comando);
$res = array();
while($row = mysqli_fetch_array($result)) {
array_push($res, array('Nome' => $row[2]));
}
$_SESSION['error'] = "Connessione al DataBase pagine riuscita, pagine recuperate.";
}
echo json_encode(array("risultato" => $res));
?>
but it doesn't work. I'm not receiving anything.
You are currently sending the server a GET request. Id imagine that this is then causing some error due to the lack of validation on the $tipo = $_POST['tipo'] line.
You should look into using the POST from jquery http://api.jquery.com/jquery.post/ and also ensure you validate your code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// post handling
}
Is a basic starting point.
You should also be checking your query you are sending to MySQL its open to SQL Injection. Look into using http://php.net/manual/en/book.pdo.php