PHP Array Length always 5 - javascript

I am querying MS SQL Server and storing the results in a json array, then passing the results to Javascript. My issue is that based off if a variable isset the array length SHOULD be either 4 or 5 length. However, the array is ALWAYS showing a length of 5.
This is the php that I am using.
<?php
$sql = "Select ";
if (isset($_GET['namepull'])) {
$sql .= "name,";
}
$sql .= " address, city, state, zip from employeefile";
$db->setQuery($sql);
$rows = $db->loadRowList();
$output = array();
foreach ($rows as $row) {
array_push($output, $row);
}
echo $sql;
$jsondata = json_encode($output[0]);
?>
Which to me the below query strings should show an array length of
4 = Select address, city, state, zip from employeefile
5 = Select name, address, city, state, zip from employeefile
Now the issue that I have is when it hits the below <script> a length of 5 is always produced, regardless of the query. How should I modify the <script> so that an accurate count is returned?
<script>
var arrayfromphp = <?php echo $jsondata; ?>;
alert (arrayfromphp.length);
</script>
If I perform a console.log(arrayfromphp) the last element when the count should be 4 is always undefined x 1
Edit
If I use var_dump below is the output I get (which is what I expect)
Array ( [0] => XXXXXXXXX [1] => New York [2] => New York [3] => 33333 )
Array ( [0] => Jackie [1] => XXXXXXXXX [2] => New York [3] => New York [4] => 33333 )
Edit Again
It appears the issue is stemming from how I am populating a Javascript array from the php array. See edit below with notes above lines
var arrayfromphp = <?php echo $jsondata; ?>;
//Shows accurate count of 4
console.log(arrayfromphp);
var values = [];
if (arrayfromphp.length = 5) {
for (var i = 1; i < arrayfromphp.length; i++) {
values.push(arrayfromphp[i]);
}
} else if (arrayfromphp.length = 4) {
for (var i = 0; i < arrayfromphp.length; i++) {
values.push(arrayfromphp[i]);
}
}
//Shows 5
alert(arrayfromphp.length);
//Shows 5 with undefined x 1
console.log(arrayfromphp);

Related

Sending PHP Array data to javascript

I have a PHP function that I am querying mySQL database and I need to send the data from that query over to a javascript function so that the data can be used in plotly graph. I am able to query the data in PHP and get the information I need but when I try to get the information in my javascript file it says NULL. Here's my code with comments about what I am getting.
PHP function:
function getCourses() {
$conn = getDBConn();
$query = "SELECT course_id FROM TraineeEventCourses GROUP BY course_id;";
$result = mysqli_query($conn, $query) or die('Error connecting to mysql');
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $courseID) {
$course = $courseID;
print_r($course);
echo "<br>"; // Print's 1 2 3 4 8 9 10 as expected
// return $course;
}
}
// print_r($course);
// echo "<br>"; // When not commented out this goes with the return statement but it only returns 10 for some reason instead of returning the whole array.
}
Javascript:
var courses = "<?php echo json_encode($course, JSON_PRETTY_PRINT) ?>";
console.log(courses); // Returns NULL but should be returning 12348910
TESTER = document.getElementById('tester');
Plotly.plot( TESTER, [{
x: [courses],
y: [courses] }],
{ margin: { t: 0 } } );
You need to put all the course IDs into an array, and return it from the function.
There's also no need for the foreach loop. $row is an array with a single element, you can access it directly with an array index.
function getCourses() {
$conn = getDBConn();
$query = "SELECT course_id FROM TraineeEventCourses GROUP BY course_id;";
$result = mysqli_query($conn, $query) or die('Error connecting to mysql');
$courses = array();
while ($row = mysqli_fetch_assoc($result)) {
$course = $row['course_id'];
print_r($course);
echo "<br>"; // Print's 1 2 3 4 8 9 10 as expected
$courses[] = $course;
}
return $courses;
}
$course = getCourses();
?>
<script>
var courses = "<?php echo json_encode($course, JSON_PRETTY_PRINT) ?>";
console.log(courses); // Returns NULL but should be returning 12348910
TESTER = document.getElementById('tester');
Plotly.plot( TESTER, [{
x: [courses],
y: [courses] }],
{ margin: { t: 0 } } );
Why dont you get your results of your query into an array, going blind here:
while($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
$data[] = $row;
}
return $data; as its a function you wrapped it around and json_encode($data_variable) based on the variable you assign when you call function getCourse() into your javascript?

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

How to properly format JSON

I asked a question earlier, which all revolved around a JSON formatting problem. I have a PHP page, which just grabs rows from a MYSQL database, and returns them. However, i'm unsure how to format them so all the columns I get are a set, and for each row, it creates a new set. I'm not sure what is common practice to do to encode things like this.
e.g. this is what I want (if it is even correct):
{ "message": [
{
"chat":"Hello, world!",
"time":"2014-05-09 17:32:00",
"username":"Josue"
},
{
"chat":"This is my second message.",
"time":"2014-05-09 17:32:05",
"username":"Josue"
}
]
}
That way, I can parse using $.parseAJAX, and get access to my data like: data.message[0].chat, and it would return "Hello world!".
Here is what I am currently doing:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = 'chat';
$messages[] = $row['chat'];
$messages[] = 'time';
$messages[] = $row['time_sent'];
$messages[] = 'username';
$messages[] = $row['username'];
}
$loopCount = count($chats);
if(count($messages) > 0){
/*
$sexyJSON = '{message: [';
for($i = 0; $i < $loopCount; $i++){
$sexyJSON .= '{"chat":"'.$chats[$i].'","time":"'.$times[$i].'","username":"'.$usernames[$i].'"},';
}
$sexyJSON = substr($sexyJSON,0,strlen($sexyJSON)-1);
$sexyJSON .= ']}';
$newMessages = $sexyJSON;
echo $sexyJSON;
*/
echo json_encode($messages);
}
When I simply encode my array, it returns something like this:
["chat","Hello, world!","time","2014-05-09 17:32:00","username","Josue","chat","hmmm","time","2014-05-09 17:48:34","username","asdf"]
What would I have to do to group chat with the message, date with the date, and username with the username in a key-value pair?
The format of the mysql_fetch_assoc should be
array('chat'=>'Some chat', 'time_sent'=>'123456', 'username'=>'abcdefg')
json_encode would directly translate this to
{"chat":"Some chat", "time_sent":"123456", "username":"abcdefg"}
So in your loop, if you simply do $mesages[] = $row; and leave your json_encode call as-is, it should work as shown above. However, you can alter your SQL statement to give the columns an alias so that time_sent simply shows as the property time
This is what i would do:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
$loopCount = count($chats);
if(count($messages) > 0){
echo json_encode($messages);
}
This will output if not encoded:
Array
(
[0] => Array
(
[chat] => chat_0
[time] => time_sent_0
[username] => username_0
)
[1] => Array
(
[chat] => chat_1
[time] => time_sent_1
[username] => username_1
)
[2] => Array
(
[chat] => chat_2
[time] => time_sent_2
[username] => username_2
)
[3] => Array
(
[chat] => chat_3
[time] => time_sent_3
[username] => username_3
)
)
And this if encoded:
[{"chat":"chat_0","time":"time_sent_0","username":"username_0"},
{"chat":"chat_1","time":"time_sent_1","username":"username_1"},
{"chat":"chat_2","time":"time_sent_2","username":"username_2"},
{"chat":"chat_3","time":"time_sent_3","username":"username_3"}]
To parse the JSON
lets say you have your JSON results in a data var
var obj = $.parseJSON(data);
$.each(obj, function(i, value){
console.log(value.chat);
});
You need to work with multi-dimensional arrays in order to get this to work. The code below has been edited to assign values to named indexes and append these to the 2nd level to the $messages array.
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
The while cycle should be like this:
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
Save a little time by getting the field names correct within the SQL.
$SQL = sprintf('SELECT time_sent as `time`, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ($row = mysql_fetch_assoc($result)) {
$messages[] = $row;
}
echo json_encode($messages);
IMO returning an empty array when there are no messages is better than returning nothing, as now you have a way to differentiate if your php worked vs if you had no messages, from within your JavaScript code.

Creating a JSON array starting with index 1

I need to create a JSON array starting with index 1
Here is my code which picks the images from the websites
$image_urls = array();
//get all images URLs in the content
foreach($get_content->find('img') as $element)
{
/* check image URL is valid and name isn't blank.gif/blank.png etc..
you can also use other methods to check if image really exist */
if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
{
$image_urls[] = $element->src;
}
}
//prepare for JSON
$output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
data.images gives the array bu it starts with 0
Try
$output = array();
$output['1'] = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
Output would be:
{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}}
Try using array_unshift
$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index
unset($image_urls[0]);//remove the zero index
An single line solution to the image_url array:-
$arr=array(1,2,3,4,5,6);
$arr = array_combine(range(1, count($arr)), $arr);
echo '<pre>';print_r($arr);
Output :
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

Uncaught Error: Not a valid 2D array

I am creating a multidimensional array via an Ajax call to populate a Google Chart (Column). However the Array that is getting returned is causing this error:
Uncaught Error: Not a valid 2D array.
This is the code that generates the array to send back:
$chartData = array();
$i = 0;
foreach ($hourVal as $value) {
if($i <= 9){
$chartData[] = array(
"0" . $i => (int) $value
);
} else {
$chartData[] = array(
$i => (int) $value
);
}
$i++;
}
This is the array when I console.log:
[
[
"Terms",
"Visits"
],
{
00: 88
},
{
01: 30
},
{
02: 44
},
{
03: 20
}
]
EDIT: I add a row at the beginning of the array and also json_encode:
array_unshift($chartData, array("Terms","Visits"));
echo json_encode($chartData);
Any ideas what is going on and how I can fix this?
That's not a 2D array. it's an array of objects (and one array). When you do json_encode, you only get an array if your PHP array is a numeric one (indexed starting at 0). Otherwise you get an object (since JavaScript/JSON doesn't have "associative arrays").
You need to make sure your array is numeric and indexed starting from 0.
$chartData = array();
$i = 0;
foreach ($hourVal as $value) {
$chartData[] = array(
$i => (int) $value
);
$i++;
}
I don't know why you were doing "0" . $i, but that's what was causing your problem. That was creating an "associative array", which encodes as an object.
I have solved it, its because I was sending them through with a prefix of 0 and then it was making them the index of the array. Had to cut that bit out and send as string. Not desired but a fix :(

Categories

Resources