PHP echoing full file, not JSON data - javascript

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);
?>

Related

Live check user availability LDAP

I have a form in LDAP where i can add a user and a password, what can i do to have a live check of the username using php and ajax, is not mysql and i don't know how to compare and switch commands like sqlquery or sql_num_rows used in mysql and move it to LDAP, i read LDAP manual on php and is different than mysql how can i replace this commands in LDAP so i can have my username checked live?? using javascript (everything uspposed to be in one page)
http://www.developphp.com/video/PHP/Check-User-Sign-Up-Name-Ajax-PHP-Social-Network-Tutorial
https://www.webslesson.info/2016/02/how-to-check-username-availability-in.html
and other web pages tried and working with mysql
i used ldap_connect, ldap_bind_ ldap_search, ldap get entries and is working printing out everythng in funny way, so using php i cleaned out everything and is printing in a nice manner everything, my question is how can i check live the username??? Like is happening (tested) i this link above???
<label for="name"><b>name</b></label>
<input type="text" name="name" onBlur="checkusername() "maxlength="15"value="">
<span id="namestatus"></span>
<script>
function checkusername(){
var status = document.getElementById("namestatus");
var u = document.getElementById("name").value;
if(u != ""){
status.innerHTML = 'checking...';
var hr = new XMLHttpRequest();
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "name="+u;
hr.send(v);
}
}
</script>
$user = 'cn=Manager,dc=mydc ,dc=it';
$password = 'mypass';
$host = 'my_numeric_IP';
$basedn = 'ou=sistem,ou=thinks,dc=mydc,dc=it';
$ds = ldap_connect("ldap://{$host}") or die('Could not connect to LDAP server.');
if($ldapbind){
$filter='(&(objectClass=inetOrgPerson)(uid=*))'; // single filter
$attributes=array('dn','uid','sn', 'displayName');
$search = ldap_search($ds,$basedn,$filter,$attributes); // search
ldap_sort($ds, $search, 'sn');
print_r($info = ldap_get_entries($ds, $search));
$info = ldap_get_entries($ds, $search);
$ldaprecord['cn'] = $_POST['name'];
$_dn = "uid=".$_POST[value'].",ou=".$_POST['othervalue'].",ou=VOIP,ou=sistem,dc=something,dc=it";
$r = ldap_add($ds, $_dn, $ldaprecord);
}else {
echo "LDAP bind failed";
}
I think it is a little bit more difficult than only replace the mysql functions because of the mysql (or other SQL server) is not similar to LDAP.
I suggest to use an existing PHP package for LDAP. For example Adldap2 looks good for me. And there is many code snippets. For example the authentication

How to retrieve Data from Php while in Node.js

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);

getting JSON into d3.js file

I have a chart created using d3.js where if you hover over the months,the weekly scores are found.
Fiddle link to the chart I am talking about here : https://jsfiddle.net/qp7L1hob/1/
I also have a table in my DB where I maintain the record of the scores of the Employees every week.What you see here is only for four weeks - (week1 to week4) but in my DB I have record for all the weeks of the months.This is just for reference .
Table pointsScored :
After the user logs in,I want to display only that person's relevant scores.Lets say if Rob logs in,his score for week1 is 47 , week2 is 44, week3 is 44 and week4 is 43.
Issue : I am Using php to extract json from SQL server . Below PHP file does that.
The problem is that how do I get the JSON into the d3.js file, i.e the above fiddle.
please help.
json file (lets name it as data.php) :I understand that I need to include this data.php in the above d3.js file.But not sure how.
<?php
session_start();
$servername="xxxxxxx";
$connectioninfo=array('Database'=>'xxxxxx');
$conn=sqlsrv_connect($servername,$connectioninfo);
if($conn)
{
echo 'connection established';
}
else
{
echo 'connection failure';
die(print_r(sqlsrv_errors(),TRUE));
}
$q1="SELECT WeekNumber,pointsRewarded,EmployeeID FROM pointsBadgeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt=sqlsrv_query($conn,$q1);
if($stmt==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
echo json_encode($result); //You will get the encoded array variable
?>
Let me give you the direction to understand, you can use AJAX to call your php file and get data
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var dataObj = JSON.parse(response.responseText); // parse data into JSON object
chartDrawFunction(dataObj); // call draw here, to load chart only when you have data
}
};
xhttp.open("GET", "data-url-to-be-passed", true); // pass the URL here
xhttp.send();
Update
As i understood the question other way if PHP file was separate from the view. In view you can echo the data in a JavaScript variable like
var data = <?php echo data; ?>;

Updating javascript array with click when new mysql data comes in

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/

I am unable to pass on the value to a PHP script from a javascript using JSON

What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];

Categories

Resources