So I'm trying to populate a select box within my html with array objects using JSON results, I've been looking at all this code so long I don't think I'm seeing the simple solution to my problem. This is my callback function where I'm populating the select box. The JSON request has went through fine but I am stuck with a blank select box everytime.
function getArtistsCallBack()
{
if (req.readyState == 4) {
if (req.status == 200) {
// TO DO: populate artistlist select box using JSON
var response = req.responseText.parseJSON();
var artistSelect = document.getElementById("artistlist");
for (i=0;i<response.artistsarray.length;i++){
var artist_id = response.artistsarray[i].artist;
var artist = response.artistsarray[i].artist;
artistSelect.options[artistSelect.options.length] = new Option(artist, artist_id, false, true);
}
}
}
}
Here is the select box within the HTML for reference just in case;
<div id="artistscontent">
<select id="artistlist"></select>
</div>
This is artists.php where a database is queried for an array of objects, the array that is used previously;
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
$artistsarray = Collection::GetArtists();
print json_encode($artistsarray);
$jsonresponse='{"artistsarray":[';
foreach($artistsarray as $artist => $row)
{
$artist_id=$artist+1;
$artist=$row['artist'];
$jsonresponse .= '"artist_id":"' . $artist_id . '"},';
$jsonresponse .= '"artist:"' . $artist . '"},';
}
$jsonresponse .= ']}';
echo $jsonresponse;
?>
Any help would be much appreciated! Thanks!
You need to use the json length for the options array and do it outside of the for loop. Then use options.add
var json = [{key:'1', value:'value1'},{key:'2', value:'value2'}]
var artistSelect = document.getElementById("artistlist");
artistSelect.options[json.length];
$.each(json, function(key, value){
console.debug(value);
artistSelect.options.add(new Option(value.key, value.value));
});
Check out this plunker:
http://plnkr.co/edit/i3A6mo672CskXvbstWsu?p=preview
The artistSelect.options is not an array, you need to use the add method:
var opt = new Option(artist, artist_id);
artistSelect.options.add(opt);
Related
I'm a 'newbie' on stackoverflow but it is a source that I keep coming to regularly for tips.
I've picked up some code from the simple.html file accompanying the jsPDF auto-table plug-in but as it doesn't appear to pick up data from a php generated table.
I am trying to get the data into a format that can be transformed into a nice pdf report - 'with all the trimmings' - ie; page-breaks, headers on each page, alternate row-colours etc.
I've tried to get the data into a form that can be used by the jsPDF autotable but I'm going wrong in that it is just going through the array and keeping the last record and printing that in pdf format. Code shown below.
<button onclick="generate()">Generate pdf</button>
<script src="/js//jspdf.debug.js"></script>
<script src="/js/jspdf.plugin.autotable.js"></script>
<?php
$link = mysqli_connect('localhost','user','password','database');
if(!$link)
{
echo 'Database Error: ' . mysqli_connect_error() ;
exit;
}
$results=array();
$sql_staff = "SELECT staff_id, staff_firstname, staff_lastname, staff_username, staff_chargerate, staff_lastlogin FROM tblstaff ORDER BY staff_lastname ASC, staff_firstname ASC ";
$result_staff = mysqli_query($link,$sql_staff);
while($row = mysqli_fetch_array($result_staff)){
$results[0] = $row['staff_id'];
$results[1] = $row['staff_firstname'] . " " . $row['staff_lastname'];
$results[2] = $row['staff_username'];
$results[3] = $row['staff_chargerate'];
$results[4] = $row['staff_lastlogin'];
echo json_encode($results);
$data = json_encode($results);
}
?>
<script>
function generate() {
var head = [["ID", "Staff Name", "Username", "Charge-rate", "Last Log-in"]];
var body = [
<?echo $data;?>
];
var doc = new jsPDF();
doc.autoTable({head: head, body: body});
doc.output("dataurlnewwindow");
}
</script>
I think that the problem lays around the line $data = json_encode($results); but I don't know enough about either PHP or Javascript to determine how the code needs to be altered to produce a full PDF report. Can anyone assist please?
Your issue is probably related to overwriting the values in the $results array which means you will get one item instead of an array of items. You probably want something like this:
$results = array();
while($row = mysqli_fetch_array($result_staff)){
$dataRow = array();
array_push($dataRow, $row['staff_id']);
array_push($dataRow, $row['staff_firstname'] . " " . $row['staff_lastname']);
// etc
array_push($results, $dataRow);
}
$data = json_encode($results);
i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>
I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>
Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}
I am working with two different tables that are in different servers.
I am trying to compare the USERNAME field values from table "workstation_userlogged" and
the MEMO_CODE field value (they are usernames) from table "telephony". I get the "memo_code" values with the use of a Stored Procedure as you will see in the code below.
How can I save all the results returned from both tables, loop through them to match all usernames and then save the data so it can be returned with AJAX? This script will only run when an AJAX request button is clicked. So, I need to bring the data back and display it like so:
If matching usernames from both tables:
user: JOE time: 300
If no matching usernames:
user: MARC time: N/A
Some usernames from "workstation_userlogged" do not exist in the other table and vice versa.
I know it has to do with handling arrays and all but I've been stuck for hours and wasn't able to accomplish it.I need to clarify things please ask.
Thanks in advance!
map.php HTML/AJAX: How do I fix this?
<!-- Show the results here-->
<div id="resultdiv" class="resultdiv" style="display:none"> </div>
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: { }, // pass data here
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
show_aht.php: when AJAX request is sent
<?php
Stored PRocedure just to show what I did:
//get the StoredProcedure from the "query" field in the overlay table
//and store it as a variable for later use for the AHT button
if($row = mysqli_fetch_assoc($query_overlay_result)){
$sp_value = $row['query'];
}
Table workstation_userlogged:
The results from this WHILE LOOP need to be matched with the results of the StoredProcedure below
//the displayed users values will have to be matched with memo_code
$user_data = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user_data[] = "user: " .$row['username'];
}
This is where I am trying to compare both usernames and bring the data back
to map.php but had no luck.
/****************************************************
Execute the sp_value query when AHT button is clicked
/****************************************************/
//loop the result set
$memo_data = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo_data[] = $row['memo_code'] . " " . $row['avg_handle_time'];
}
/*THIS ISNT WORKING*/
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m['username'])
echo " user: " .$m['username']. " time: " . $v['avg_handle_time'] . "<br>";
}
}
?>
So the first mistake is your use of json_encode($user_data) json encode is a function which converts an array into a string in the format of javascript object notation. It's to be used in conjecture with something like echo json_encode($obj); and recieved in javascript obj = JSON.parse(json);
Now since you have 2 arrays what you need to do is loop through both to find the matching names:
I'm not sure what memo_code is but it needs to be a username.
Your query is incorrect change it to something like.
$result = $sql->query("SELECT username FROM `$table1`;");
for ($user_data= array (); $row = $result->fetch_assoc(); $set[] = $row);
$result2 = $sql->query("SELECT memo_code FROM `$table2`;");
for ($memo_data= array (); $row = $result2->fetch_assoc(); $set[] = $row);
Now you can finally use the loop correctly:
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m['username '])
echo " user: " .$m['username ']. " time: " . $v['avg_handle_time'] . "<br>";
}
}
I found the solution basically I wasnt`t comparing arrays properly so here below is the new comparison.
$user_data = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user_data[] = $row['username'];
}
/****************************************************/
//loop the result set
$memo_data = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo_data[] = array("memo_code" => $row['memo_code'],
"avg_handle_time" => $row['avg_handle_time']);
}
/**comparing usernames from both arrays*/
foreach($memo_data as $v){
foreach($user_data as $m){
//echo 'mem code is:'.$v['memo_code'].'username is:'.$m['username'];
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo " User: " . $m . " Time: N/A <br>";
}
}
}
I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);