Trying to prepopulate a certain input field in a form with latest data from the db, but the data returned is undefined. SQL query works perfectly. I’m using a similar script to generate the table. So no problem there.
the PHP code to generate json
<?php
include('db.php');
include('function.php');
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
$compressor_hours = '';
//get the last read runtime hours of each compressor
//return one row of plant_readings_id | runtime_hours1 | runtime_hours2 | runtime_hours3
$compressor_hours .= "SELECT MAX(r.id),
MAX(CASE c.compressor_name WHEN 'CM101' THEN c_r.runtime_hours END) AS runtime_hours1,
MAX(CASE c.compressor_name WHEN 'CM201' THEN c_r.runtime_hours END) AS runtime_hours2,
MAX(CASE c.compressor_name WHEN 'CM301' THEN c_r.runtime_hours END) AS runtime_hours3
FROM plant_readings r
LEFT JOIN compressor_readings c_r ON c_r.plant_readings_id = r.id
LEFT JOIN compressors c ON c_r.compressor_id = c.id;";
$statement = $connection->prepare($compressor_hours);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["runtime_hours1"];
$sub_array[] = $row["runtime_hours2"];
$sub_array[] = $row["runtime_hours3"];
$data[] = $sub_array;
}
$output = array(
"data" => $data
);
echo json_encode($output);
?>
Then the JS
$(document).ready(function(){
$('#add_button').click(function(){
//$('#plant_readings_form')[0].reset();
$('.modal-title').text("Add New Readings");
$('#action').val("Add");
$('#operation').val("Add");
var runtime_hours1 = $(this).attr("runtime_hours1");
var runtime_hours2 = $(this).attr("runtime_hours2");
var runtime_hours3 = $(this).attr("runtime_hours3");
$.ajax({
url:"fetch_prefill_data.php",
method:"POST",
data:{runtime_hours1: runtime_hours1,
runtime_hours2: runtime_hours2,
runtime_hours3: runtime_hours3},
dataType:"json",
success:function(data)
{
$('#runtime_hours1').attr('value',data.runtime_hours1);
$('#runtime_hours2').attr('value',data.runtime_hours2);
$('#runtime_hours3').attr('value',data.runtime_hours3);
$('#plant_readings_form')[0].reset();
}
})
});
Hardcoding will set the value in the field.
$('#runtime_hours1').attr('value',1);
I debug by with document.write to get the following
$('#runtime_hours1').attr('value',document.write(data.runtime_hours1));
$('#runtime_hours1').attr('value',document.write(data));
...
undefined
[object Object]
The code looks fine, sql query returns exactly what I’m expecting, so I don’t understand why its returning undefined in the JS?
Thanks in advance