jquerymobile selectmenu not populating - php

I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!

So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);

Related

php how to return JSON for jQuery .get() or .post() request, parse it and output to browser

Edit:
I can output the table now but the strange thing is, trying to parse the JSON returned from PHP using JS or jQuery methods results in skipping all remaining lines in the debugger with zero output to the browser. Where as not parsing and using it to construct at table works.
Also, trying to .append() the JSON using the parse methods or not to a ` does not work.
I'm so confused right now.
Anyways, the jQuery that worked looks like this making a .post() request, notice I added the 'json' fourth parameter although it might work without it.
$(document).ready(function(){
$('#disease_btn').click(function(){
showDisease();
});
});
function showDisease(){
//var disease = $("#disease-dropdown:selected").text();
//var disease = $("#disease-dropdown:selected").val();
var disease_dropdown = document.getElementById("disease-dropdown")
var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
var controller = 'controller.php';
$.post(controller, //url, data, callback, dataype=Json
{
page: 'SpaPage',
command: 'search-disease',
search_term: disease
},
function(disease_json, status){
//#search-results display table
//var disease_obj = JSON.parse(disease_json); this did not work
//var disease_obj = jQuery.parseJSON(disease_json); //this did not work
var disease_obj = disease_json;
//$('#test-out').append(disease_obj); /this did not work
var table = $.makeTable(disease_obj);
$('#search-results').append(table); //this worked!
}, 'json');
//https://stackoverflow.com/a/27814032/13865853
$.makeTable = function(disease_obj){
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
$(tblHeader).appendTo(table);
$.each(disease_obj, function(index, value){
var tblRows = "<tr>";
$.each(value, function (key, val){
tblRows += "<td>" + val + "</td>";
});
tblRows += "</tr>";
$(table).append(tblRows);
});
return ($(table));
}
};
That table code I mimicked what I saw here: https://stackoverflow.com/a/27814032/13865853
I sort of get it but still not crystal clear on all of it. I guess it's outputting HTML so I can throw in a class for the table to take advantage of bootstrap.
On the PHP side I do this:
case 'search-disease':
$matches_arr = [];
$disease = $_POST['search_term'];
$matches_arr = search_disease($disease);
//todo: decide to use session or returned arr
if(isset($_SESSION['disease-matches_arr'])){
$matches_arr = $_SESSION['disease-matches_arr'];
}
if(count($matches_arr) > 0) {
//jsonify array here to send back
//https://stackoverflow.com/a/7064478/13865853
//https://stackoverflow.com/a/58133952/13865853
header('Content-Type: application/json');
$disease_json = json_encode($matches_arr);
echo $disease_json;
exit;
}
and then the model.php interaction with database looks like this:
function search_disease($disease_option){
// search DB for substring of question
//add results to an array of strings
//return array of strings or empty array
//
$user_id = -1;
$matches_arr = array();
$sql = "SELECT * FROM diseases
WHERE disease LIKE '%$disease_option%'";
$result = mysqli_query(Db::$conn, $sql);
if (mysqli_num_rows($result) > 0) {
//iterate
while($row = mysqli_fetch_assoc($result)){
//get username
$disease = $row['disease'];
$food = $row['food'];
$en_name = $row['en_name'];
$health_effect = $row['healthEffect'];
$metabollite = $row['metabollite'];
$citation = $row['citation'];
$next_row = array("Disease"=>$disease, "Food"=>$food,
"Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
"Sources"=>$citation);
$matches_arr[] = $next_row;
}
}
$_SESSION['disease-matches_arr'] = $matches_arr;
return $matches_arr;
//https://stackoverflow.com/questions/1548159/php-how-to-sen
So I set a session variable and also return it, still have to decide which way but they are both working.
My questions still remaining are:
Why do the parse methods cause this strange behavior?
How can I just output the JSON to a testing <div>?
If you have to return data from PHP to javascript you must have use json_encode() if data type is array otherwise just return.
To take action with array type data by javascript you have to decode this json data by JSON.parse() function.
Array example
$data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
echo json_encode($data);
exit;
String example
echo 'lorem ipsum is a simple text';
exit;

Pass array data inside value="" separated with ':' using AJAX/JSON | PHP, HTML

Is it possible to pass data in aray using AJAX/JSON? Like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."?
This is the sample code.
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
echo "<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
I understand that this can work using AJAX, but I don't know how to set it up for array that is only separated with ":"
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select_title.php",
data:{accounttitleselector:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accounttitleselector").html(resp);
}
});
}
else {
$("#accounttitleselector").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Thank you.
Add the row data in new array results and return the results in json format using json_encode
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
$array[] ="<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
echo json_encode($array);
In jquery after ajax success parse the response with JSON.parse(), and the data becomes a JavaScript object.
//use each loop to get the option data from response
success:function(response) {
var data = JSON.parse(response);
$("#accounttitleselector").html($.each(data, function(index, value) {
value
}))
}
});

AJAX Response and PHP Loop

I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.
However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?
AJAX:
$.ajax({
type: "POST",
url: 'feed.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
$.each(data, function(key, value) {
// here I want to loop through the returned results - for example
$("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
});
}
});
feed.php
if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
$query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
// this query returns approx. 20 results
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data["Direction"] = $row['Direction'];
$data["CardNo"] = $row['CardNo'];
$data["SerialNo"] = $row['SerialNo'];
}
echo json_encode($data);
}
Also in my PHP, should I be using a while or if statement?
You're using a single $data object and resetting its contents each time. You want to build an array of objects:
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = array(
"Direction" => $row['Direction'],
"CardNo" => $row['CardNo'],
"SerialNo" => $row['SerialNo']
);
}
echo json_encode($data);
Followed by:
success: function(data) {
$.each(data, function(key, value) {
$("#transactionTable").prepend(
'<tr><td>' + value.SerialNo + '</td>' +
'<td>' + value.CardNo + '</td>' +
'<td>'+ value.Direction +'</td></tr>');
});
}
In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.
Many solutions exist, but you have to do something like
$data["Direction"][] = $row['Direction'];
$data["CardNo"][] = $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];
or better:
$data[] = $row;
Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo
note: not tested

Google Maps API 3 - extracting markers from MySQL DB using PHP

<?
$query = mysql_query("SELECT * FROM poi_example");
while ($row = mysql_fetch_array($query)){
$name=$row['name'];
$lat=$row['lat'];
$lon=$row['lon'];
$desc=$row['desc'];
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");
}
?>
this code (echo) shows the table data in HTML source code.. is there another way (which does not shows the data) to extract markers from table?
thank you.
tutorial & demo page
I prefer to render them as a JSON. You can either do that in-page as you have done above.
<?php
// do database connection here
// run query to fetch your results
$rows = array();
while ($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
echo "<script>var items = '".json_encode($rows)."';</script>";
You can iterate over your items array in JavaScript.
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
I presume your addMarker() function creates a standard Google Map marker.
Alternative, you can have a PHP script that fetches your items from the database as echoes them as a JSON string, and then just call that via AJAX with jQuery.
So your PHP script would simply be:
<?php
header('Content-Type: application/json');
// connect to database
// do query
$rows = array();
while ($row = mysql_fetch_array($res)) {
$rows[] = $row;
}
echo json_encode($rows);
exit;
And then in your JavaScript file:
$.getJSON('script.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
});
Hope this helps.

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

Categories