Turning PHP into JSON array when parsed in Javascript - javascript

So, in order to create a page that has dynamic HTML, the following Javscript code was used:
function add0(Text, Value){
var x = document.getElementById("thingy");
var option = document.createElement("option");
option.text = Text;
option.value = Value;
x.add(option);}
function add(Text, Value){
var x = document.getElementById("stuff");
var option = document.createElement("option");
option.text = Text;
option.value = Value;
x.add(option);}
var c = 0;
var value =<?php echo json_encode($ToAndFromR); ?>;
var formula = <?php echo json_encode($FormulaR); ?>;
while(c < <?php echo $countr ?>){
add0(value[c], formula[c]);
add(value[c], formula[c]);
c++;
}
This was done after recieving $ToAndFromR and $Formula from a SQL Query, in which the code is :
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//declare variables
$countr = null;
$sql = "SELECT * FROM `convert`";
$drippage = mysqli_query($conn, $sql);
//this counts the number of rows
if (mysqli_num_rows($drippage)) {
$countr = mysqli_num_rows($drippage);
}
$ToAndFrom = mysqli_query($conn, "SELECT ToAndFrom FROM `convert`");
$ToAndFromR = null;
$ToAndFromR = mysqli_fetch_all($ToAndFrom, MYSQLI_BOTH);
$FormulaR = null;
$Formula = mysqli_query($conn, "SELECT Formula FROM `convert`");
$FormulaR = mysqli_fetch_all($Formula, MYSQLI_BOTH);
However, the HTML gets shown as [object Object] in the dropdown list, as opposed to their actual values when a regular PHP array is used. Is there a way to fix this?

Each Text and Value passed to your JavaScript functions will be an object with two properties (because you're using MYSQLI_BOTH fetch mode), eg
{"0": "some value", "ToAndFrom": "some value"}
You're attempting to assign this to the option's text and value properties.
You also appear to be running three queries when you should be running one.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');
$result = $conn->query('SELECT `ToAndFrom` AS `text`, `Formula` AS `value` FROM `convert`');
$options = $result->fetch_all(MYSQLI_ASSOC);
and in your JavaScript
var options = <?= json_encode($options) ?>;
for (var i = 0, l = options.length; i < l; i++) {
add0(options[i].text, options[i].value);
add(options[i].text, options[i].value);
}
Also, you could cut down on the almost identical JavaScript functions add0 and add by simply passing the <select> ID, eg
function add(selectId, text, value) {
var x = document.getElementById(selectId);
// and so on
}
with
add('thingy', options[i].text, options[i].value);
add('stuff', options[i].text, options[i].value);

I think you should write a separate PHP script which echo the JSON.
Then in the javascript, you should call this PHP and parse the JSON. A simple code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "sql.php", true);
var htmltext= '';
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var jsoninfo = xhr.responseText;
var obj = JSON.parse(jsoninfo);
// text = obj.attribute;
// add0(text,formula[c])
}
}
}

Related

displaying data from mysql where if value is in database show true if its not show false

My overall goal is if there is a Value pull in ID then change the cell where ID matches the number
e.g. the below data has been pulled in change cell 1,120,17,40,61,69,70,81,82,9 green and the rest of them red.
if there is something i need to change mysql side then let me know i did try it so that it got entered into the database from node red to say if where number between 1-100 is present in mqtt feed add value present to column present if it isnt in the feed add value false but i couldnt get that to work.
Data
[{"id":"1","present":"present","date":"2018-07-17","time":"10:53:20"},
{"id":"120","present":"present","date":"2018-07-17","time":"10:54:24"},
{"id":"17","present":"present","date":"2018-07-17","time":"10:53:40"},
{"id":"40","present":"present","date":"2018-07-17","time":"10:53:27"},
{"id":"61","present":"present","date":"2018-07-17","time":"10:53:14"},
{"id":"69","present":"present","date":"2018-07-17","time":"11:02:01"},
{"id":"70","present":"present","date":"2018-07-17","time":"10:53:17"},
{"id":"81","present":"present","date":"2018-07-17","time":"10:56:50"},
{"id":"82","present":"present","date":"2018-07-17","time":"10:59:28"},
{"id":"9","present":"present","date":"2018-07-17","time":"10:53:15"}]
PHP
<?php
header('Content-type: application/json');
$servername = "localhost:3306";
$username = "user";
$password = "password!";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = 'SELECT
*
FROM test.test where time > NOW() - interval 30 minute group by id';
$result = $conn->query($sql);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$conn->close();
?>
HTML side
<script>
$(document).ready(function() {
for (var i = 0; i < 12; i++) {
var row = $('<tr>').appendTo("#zoning tbody");
for (var j = 1; j < 11; j++) {
$(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
}
}
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
if (item.id == "notNULL") {
return $('td.coloured').css('background-color','green').toggleClass('coloured');
} else {
return $('td.coloured').css('background-color','red').toggleClass('coloured');
} });
});
function updateTable() {
//console.log('function called');
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$.get('php/test.php', function(response) {
response.forEach(function(item, index) {
console.log(item.beacon);
//$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
if (item.id == "notNULL") {
return $('td.coloured').css('background-color','green').toggleClass('coloured');
} else {
return $('td.coloured').css('background-color','red').toggleClass('coloured');
}
});
});
}
var updateTableInterval = setInterval(updateTable, 40000);
});
</script>
</head>
<body>
<table id='zoning'>
<tbody></tbody>
</table>
</body>
</html>
You shlould change the if (item.id = present) to if(item.id == present) in the first one you are setting the item.id to present and that is wrong you need to test . It is just a Syntax error

passing multiple values using xmlhttp.send

I am trying to pass two different values into an XMLHttpRequestObject.send but cannot seem to get the php script to read them both, it will only read the first value passed. How can I get the PHP to read both the values, here is the sample code:
HTML
<select id="mes" onchange="callCourseYards(this);">
<option>-</option>
</select>
Javascript
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function callCourseYards(selectObject){
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", "php/CourseChoiceTeeOff.php");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var returnData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('tee');
messageDiv.innerHTML = returnData;
}
}
var data = selectObject.value;
var course = selectObject.value;
XMLHttpRequestObject.send("data=" + data + "course=" + course);
}
return false;
}
PHP
<?php
$pdo_dsn='localhost';
$dbname ='XXX';
$mysql_user='XXX';
$mysql_pass='XXX';
$db = mysqli_connect($pdo_dsn, $mysql_user, $mysql_pass, $dbname);
if(!$db){
print "Unable to connect to MySQL";
}
$myData = $_POST['data'];
$myData1 = $_POST['course'];
$sql_state = "SELECT * FROM ".$myData1." WHERE CourseCode = '".$myData."' ORDER BY CourseCode";
$result = mysqli_query($db, $sql_state);
$out = "";
$myrowcount = 0;
if(!$result){
$out = "Error";
}else{
$out = "<option>Selecciona un campo</option><br/ >";
$numresults = mysqli_num_rows($result);
for ($i = 0; $i < $numresults; $i++){
$row = mysqli_fetch_array($result);
$teeOff = $row['TeeOff'];
$out .= "<option id='".$myData."' value='".$teeOff."'> ".$teeOff."</option>";
}
$out .= "<br/ >";
}
print $out;
?>
I cannot seem to get the values through the XMLHttpRequestObject to go through into the PHP. I am not sure if its the syntax or how they should get past into the PHP.
I have tried using the & and the + symbols to concatenate both values, but I am not sure if this is possible. Does anyone know how I can fix this problem? I need both values to be able to do the mySQL search in the database.
Any help would be greatly appreciated. Thanks

Returning multiple ajax response on dropdown change

Im trying to have my ajax respond multiple values based on the dropdown I selected.
Here's my JS updated
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$('#student_infor').change(function()
{
var first = $('#student_infor').val();
var req = $.get('frm_get_stud_record.php', {dd: first,action: 'ajax'});
req.done(function(row)
{
var whatever = JSON.parse(row);
$('#studen_title').val(whatever.stu_title);
$('#student_first_name').val(whatever.stu_first_name);
});
});
</script>
And here's my ajax php
<?php
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if(isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd']))
{
$dbValue = intval( $_GET['dd'] );
$ajax = true;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college_school_system";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT distinct a.stu_unique_id,
a.stu_title,
a.stu_first_name,
a.stu_middle_name,
a.stu_last_name,
a.stu_gender,
a.stu_email_id,
a.stu_mobile_no,
a.stu_dob,
b.stu_course_id,
b.stu_batch_id,
b.stu_section_id,
c.course_name,
d.batch_name,
e.section_name
from stu_info a INNER JOIN stu_academics b
ON
a.stu_unique_id = b.stu_acad_stu_info_id
inner join courses c
ON
b.stu_course_id = c.course_id
INNER JOIN batches d
ON
b.stu_batch_id = d.batch_id
INNER JOIN section e
ON
b.stu_section_id = e.section_id
where a.stu_unique_id = $dbValue
ORDER BY d.batch_name DESC";//die($sql);
$res = mysqli_query($conn,$sql);
$title = '';
$f_name = '';
while ($row = mysqli_fetch_array($res)){
$f_name = $row['stu_first_name'];
$m_name = $row['stu_middle_name'];
$l_name = $row['stu_last_name'];
$title = $row['stu_title'];
$gender = $row['stu_gender'];
$email = $row['stu_email_id'];
$mobile = $row['stu_mobile_no'];
$birth = $row['stu_dob'];
//$title = "$title";
if($ajax) echo $title;
if($ajax) echo $f_name;
}
//die($dataTable);
?>
What I'm trying to achieve here is to have the Ajax return multiple values so i can insert those returned values in their respective input type text boxes.

Why am I not able to fetch property of the object that I get from PHP?

I am trying to receive data from database based on the name entered by user, everything works fine I do see the value on screen and no error Here is the php code :
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
$user ="mon";
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;
mysql_close();
?>
JavaScript code :
var loadingFunc=function()
{
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsonData= "";
xhr.onreadystatechange =function()
{
if(xhr.readyState==4)
{
if(xhr.success =200)
{
jsonData = xhr.responseText;
document.getElementById("dvID").innerHTML = jsonData;
//var parsejson = JSON.parse(jsonData);
//document.getElementById("dvIDO").innerHTML = parsejson.age;
document.getElementById("dvIDO").innerHTML = jsonData[0].age;
}
else
{
document.getElementIdById("dvID").innerHTML = "it's not success ";
}
}
else
{
console.log("error is here");
console.log(xhr.readyState);
}
}
var element1 = document.getElementById("dvID") ;
xhr.open("POST","index.php");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var sendD = document.getElementById("data_found").value;
var data = "data_found=" + sendD;
var element = document.getElementById("btn") ;
if(element)
{
element.addEventListener('click',function(){
console.log("just clicked")
xhr.send(data);
})
}
};
window.onload = loadingFunc();
but the output that I see on the html div is :
[{"id":"1","Name":"mon","Age":"26","Gender":"F"}]
undefined
I am getting the whole object but whenever I am trying to fetch any property of the object like age here (parsejson.age or jsonData[0].age) it's showing undefined , Could anyone help me how do I fetch any property of the object?
Kindly let me know what am I doing wrong ?
First transform the cleartext response into a javascript object. You have the line already there but commented out it seems, after that:
alert(jsonData["Age"]); //Age
alert(jsonData.Age); //Age

php returns empty JSON array

I created an array for town name, "Auckland" and "Hamilton", but the response from php is always empty, any idea?
UPDATE:
after debugging, I found that the problem is in php query
" where town = '$town' ", once i deleted this line, the rest works perfectly.
But I still can't figure out why :<
javascript:
var _addNewTowntoList = function(){
if (_request.readyState == 4) {
if (_request.status == 200) {
var data = JSON.parse(_request.responseText);
if(data.length == 0){
alert("No such town");
return;
}
var t = data[0].town;
var o = data[0].outlook;
var min = data[0].min_temp;
var max = data[0].max_temp;
var witem = new WLine(t,o,min,max);
console.log(t+" "+o+" "+min+" "+max);
_list.push(witem);
}
}
}
here is the php
$town = $POST_['town'];
$query = "Select * From weather WHERE town = '$town'";
$result = mysqli_query($conn, $query);
//create array for data
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data);
change this
$town = $POST_['town'];
> $query = "Select * From weather WHERE town = '$town'";
to
$town = $_POST['town'];
$query = "Select * From weather WHERE town = '".$town."'";
Remember to properly escape the query string
$town = mysqli_real_escape_strin($conn, $_POST['town']);
Because else your script is opened to SQL Injection attack
The other thing to mention here other than correct name for the $_POST is that you can use mysqli_fetch_all function to fetch all results at once and avoid the loop. For example
echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));

Categories

Resources