Can't get xml from php - javascript

I've been trying to get data from my database into a table on my website using js/php but I can't get the php to give a valid xml to the script.
This is the php code:
<?php
$serverName = "localhost";
$userName = "***";
$password = "***";
$DBName = "DataBase1";
// Connect to DB
$connection = mysqli_connect($serverName, $userName, $password, $DBName);
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
} else {
//echo "Connected to DB<br>";
}
// Collect data
$selectionSD = $connection->query("SELECT * FROM `SensorData`");
$selectionSL = $connection->query("SELECT * FROM `SensorLog`");
// Generating XML file
//$xmlSD = new XMLWriter();
//$xmlSD->openUri("php://output");
//$xmlSD->startDocument();
//$xmlSD->setIndent(true);
//$xmlSD->startElement("SensorDataTable");
//while ($row = mysqli_fetch_assoc($selectionSD))
//{
// $xmlSD->startElement("SensorData");
// $xmlSD->startElement("ID");
// $xmlSD->writeRaw($row["ID"]);
// $xmlSD->endElement();
// $xmlSD->startElement("SID");
// $xmlSD->writeRaw($row["SID"]);
// $xmlSD->endElement();
// $xmlSD->startElement("Value");
// $xmlSD->writeRaw($row["Value"]);
// $xmlSD->endElement();
// $xmlSD->startElement("Comment");
// $xmlSD->writeRaw($row["Comment"]);
// $xmlSD->endElement();
// $xmlSD->startElement("DateTime");
// $xmlSD->writeRaw($row["DateTime"]);
// $xmlSD->endElement();
// $xmlSD->endElement();
//}
//$xmlSD->endElement();
//header("Content-type: text/xml");
//$xmlSD->flush();
//$xmlSD->endDocument();
// Test code
$document = new DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$root = $document->createElement('SensorDataTable');
$root = $document->appendChild($root);
while ($row = mysqli_fetch_assoc($selectionSD))
{
$node = $document->createElement('SensorData');
$node = $root->appendChild($node);
// ID
$dataNode = $document->createElement('ID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["ID"]);
$data = $dataNode->appendChild($data);
// SID
$dataNode = $document->createElement('SID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["SID"]);
$data = $dataNode->appendChild($data);
// Value
$dataNode = $document->createElement('Value');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Value"]);
$data = $dataNode->appendChild($data);
// Comment
$dataNode = $document->createElement('Comment');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Comment"]);
$data = $dataNode->appendChild($data);
// DateTime
$dataNode = $document->createElement('DateTime');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["DateTime"]);
$data = $dataNode->appendChild($data);
}
echo $document->saveXML();
// Close DB connection
$connection->close();
?>
I've tried to generate the xml a different way but no luck (the commented lines was what I tried first).
To get the xml into a table I use js with this code:
console.log(xml);
let i;
const xmlDoc = xml.responseXML;
if (xmlDoc === null) {
console.log("Failed to get response.");
}
let table = "<tr><th>SID</th><th>Value</th></tr>";
const x = xmlDoc.getElementsByTagName("SensorData");
for (i = 0; i < x.length; i++) {
table += "<tr><td class='center'>" +
x[i].getElementsByTagName("SID")[0].childNodes[0].nodeValue +
"</td><td class='center'>" +
x[i].getElementsByTagName("Value")[0].childNodes[0].nodeValue +
"</td></tr>";
}
console.log("Changing DB display");
document.getElementById("DB").innerHTML = table;
Where xml = the path to the php file.
When trying to run this it gives an error that xmlDoc is null. If I run this using an actual xml file on my drive it works fine.
If I call the php file directly and inspect the source it shows this:
<?xml version="1.0" encoding="utf-8"?>
<SensorDataTable>
<SensorData>
<ID>1</ID>
<SID>1</SID>
<Value>19.50</Value>
<Comment>DHT_Temp</Comment>
<DateTime>2021-10-04 12:57:51</DateTime>
</SensorData>
<SensorData>
<ID>2</ID>
<SID>2</SID>
<Value>57.50</Value>
<Comment>DHT_Humi</Comment>
<DateTime>2021-10-04 12:57:55</DateTime>
</SensorData>
<SensorData>
<ID>3</ID>
<SID>1</SID>
<Value>19.60</Value>
<Comment>DHT_Temp</Comment>
<DateTime>2021-10-04 12:58:29</DateTime>
</SensorData>
<SensorData>
<ID>4</ID>
<SID>2</SID>
<Value>57.20</Value>
<Comment>DHT_Humi</Comment>
<DateTime>2021-10-04 12:58:32</DateTime>
</SensorData>
</SensorDataTable>
How can I fix this issue, I’ve searched the web but the solutions I've come across did not work (creating the xml in a different way for example).
Fixed: change in the php code, added header("Content-type: text/xml"); back:
<?php
$serverName = "localhost";
$userName = "***";
$password = "***";
$DBName = "LIDAc";
// Connect to DB
$connection = mysqli_connect($serverName, $userName, $password, $DBName);
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
// Collect data
$selectionSD = $connection->query("SELECT * FROM `SensorData`");
$selectionSL = $connection->query("SELECT * FROM `SensorLog`");
// Generate XML file
$document = new DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$root = $document->createElement('SensorDataTable');
$root = $document->appendChild($root);
while ($row = mysqli_fetch_assoc($selectionSD))
{
$node = $document->createElement('SensorData');
$node = $root->appendChild($node);
// ID
$dataNode = $document->createElement('ID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["ID"]);
$data = $dataNode->appendChild($data);
// SID
$dataNode = $document->createElement('SID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["SID"]);
$data = $dataNode->appendChild($data);
// Value
$dataNode = $document->createElement('Value');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Value"]);
$data = $dataNode->appendChild($data);
// Comment
$dataNode = $document->createElement('Comment');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Comment"]);
$data = $dataNode->appendChild($data);
// DateTime
$dataNode = $document->createElement('DateTime');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["DateTime"]);
$data = $dataNode->appendChild($data);
}
header("Content-type: text/xml");
echo $document->saveXML();
// Close DB connection
$connection->close();
?>

Related

I want to display the following data in table

I want to display the following data in a table.
I have tried fetching data from database but only one column is visible
# AJAX CODE
$.ajax({
url:'process/getState.php',
method:'GET',
success:function(response){
res = JSON.parse(response);
console.log(res);
$.each(res,function(k,v){
var t = $('.template > table > tbody > tr').clone();
t.find('.state').html(v.state);
t.find('.count').html(v.count);
$('#tbody').append(t);
console.log(v);
});
}
})
# PROCESS FILE
<?php
include('connection.php');
$conn = connection();
$sql = "SELECT * FROM statedistribution";
$result = $conn->query($sql);
$state = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($state,$row);
}
die(json_encode($state));
} else {
echo "0 results";
}
$conn->close();
?>
I am only getting the data in the state column but the count column is turning out to be blank
You are seeing one column or row because your $state is not declared properly as an array
Simply edit your process file to look like this:
include('connection.php');
$conn = connection();
$sql = "SELECT * FROM statedistribution";
$result = $conn->query($sql) or die ("Error :".mysql_error());
$state = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$state[] = $row;
}
$output = json_encode($state);
} else $output = "0 results";
$conn->close();
echo $output;

JSON array accent display

I'm trying to display a json array with contents from my database but when their is accents in the database the json array doesn't want to be displayed, their is my code:
<?php
include 'connect.php';
header('Content-Type: text/plain; charset=UTF-8') ;
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = $by;
$response["type"] = $type;
$response["lesson"] = $lesson;
$response["description"] = $description;
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = $question;
}
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Thank you for your answers
I found a good code but thank you for your help,
<?php
include 'connect.php';
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
function utf8_encode_all(&$value)
{
if (is_string($value)) return utf8_encode($value);
if (!is_array($value)) return $value;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
return $ret;
}
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = utf8_encode_all($by);
$response["type"] = utf8_encode_all($type);
$response["lesson"] = utf8_encode_all($lesson);
$response["description"] = utf8_encode_all($description);
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = utf8_encode_all($question);
}
}
}
$array = array_map('htmlentities',$response);
$json = html_entity_decode(json_encode($array));
echo $json;
?>

Passing PHP Array to Javascript with Json_encode

I am trying to pass a php array to a javascript variable as an object to use in google maps on the same page/file. I am not able to send out an alert when testing the array in javascript.
PHP
while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];
$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
/* Each row is added as a new array */
$locations = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
JS
var map;
var Markers = {};
var infowindow;
var locations = '<?php echo json_encode($locations); ?>';
var location = JSON.parse(loactions);
alert(locations[0]);
I am getting this error
Uncaught ReferenceError: loactions is not defined
at account:299
#Ghost is right. I did not notice that the $locations is inside while loop. So You should define $locations = []; before while loop.
And then keep adding multiple records from while loop. So the updated code should be like:
$locations = [];
while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];
$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
/* Each row is added as a new array [] */
$locations[] = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
}
And after this, you should put the JS code snippet.
And use it like this:
JS cpde:
var map;
var Markers = {};
var infowindow;
var locations = <?php echo json_encode($locations); ?>;
var location = JSON.parse(loactions);
alert(location.streetAddress);

Add captcha to form php/mysql

I want to add Google captcha to my php form. The form adds data to my mysql database. How can I add the two parts of code together so the form checks first the captcha and after it's checked, then send it.
$servername = "";
$username = "";
$password = "";
$database = "";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = $_SESSION['userName'];
$contact = $_POST['naar'];
$address = $_POST['bericht'];
$sql = "INSERT INTO messages (to_user, from_user, message)
VALUES ('".$contact."', '".$email."', '".$address."')";
$conn->close();
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "xxxxxxxxxxxxxx";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
echo "Logged In Successfully";
}
else
{
echo "You are a robot";
}
}
As #Dagon and #Marc B have suggested in the comments above, try this:
$servername = "";
$username = "";
$password = "";
$database = "";
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "xxxxxxxxxxxxxx";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
//$conn = new mysqli($servername, $username, $password, $database);
try{
$db = new PDO('mysql:host='.$servername.';dbname='.$database,$username,$password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Error connecting to DB";
echo $e->getMessage();
exit();
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = $_SESSION['userName'];
$contact = $_POST['naar'];
$address = $_POST['bericht'];
$sql_pdo = "INSERT INTO messages (to_user, from_user, message)
VALUES (:contact, :email, :address)";
$stmt = $conn->prepare($sql_pdo);
try {
$result = $stmt->execute( array(
':contact' => $contact,
':email' => $email,
':address' => $address
));
if ( count($result) > 0 ) {
// Insert has gone well. Do your things here.
echo "Logged In Successfully";
}
else {
// Insert error. Report, check, ...
}
}
catch(PDOException $e){
echo 'could not insert in DB';
echo 'Error: ' . $e->getMessage();
return false;
}
$conn->close();
}
else
{
echo "You are a robot";
}
}

PHP Post to mysql with multiple parameters

So i'm trying to execute a Insert Statement using PHP, but when i call the part of the code that should do it, nothing happends...
Already checked it up to see what's going wrong, but could't find out.
Here's the JavaScript function that calls the PHP code.
function comparaSenhas(){
var pass = document.getElementById("pwd1").value;
var pass2 = document.getElementById("pwd2").value;
if(pass !== pass2){
return false;
}else{
return true;
}
}
function postData(){
var hr = new XMLHttpRequest();
var url = "../mysql.php";
var fstnm = document.getElementById("fn").value;
var lstnm = document.getElementById("ln").value;
var dtnasc = document.getElementById("dn").value;
var email = document.getElementById("em").value;
var senha = document.getElementById("pwd1").value;
var vars = "fname="+fstnm+"&lname="+lstnm+"&dt_nasc="+dtnasc+"&email="+email+"&senha="+senha;
if(comparaSenhas()){
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(vars);
}
}
And here's the PHP code that i'm using.
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "godienski";
$dbname = "web";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("insert into usuarios(first_name, last_name, data_nascimento, email, senha) values (?,?,?,?,?);");
$stmt->bind_param("sssss",$firstname,$lastname,$dtnascimento,$mail,$password);
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$dtnascimento = $_POST['dt_nasc'];
$mail = $_POST['email'];
$password = $_POST['senha'];
$stmt->execute();
$stmt->close();
$conn->close();
?>
</body>
</html>
Can anyone help?

Categories