PHP populate drop box with jquery - javascript

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);

Related

PHP array to seperate JavaScript file via AJAX

I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...
You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().

AJAX post jQuery to PHP $_POST

I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;
If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)

PHP: How to compare/save different ARRAYS from different WHILE loops and send data to AJAX?

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>";
}
}
}

Accessing JSON results from jQuery Ajax

I'm working on a web application to maintain the administration for a restaurant kind of type. The idea is to make new orders, put order items in that, check finance overviews etc...
I've also got a function to see all the orders in a list, when you select one of them, the order data (such as the name, emailadress, location of the customer) shows up in a another element inside the document.
I'm doing that with this function, every tr inside the has been given a custom attribute; the order_id. When selecting that, a class is given, called selectedRow.
function select_order(order) {
var item = $(order);
if (!item.hasClass("selectedRow")) {
if (!selectedOrderInformation.is(":visible")) {
switchScreen(selectedOrderInformation, financeOverview);
}
item.parent().find(".selectedRow").removeClass("selectedRow");
item.addClass("selectedRow");
selectedOrderInformation.html("loading......");
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data);
$("#delete-order-btn").prop("disabled", false);
}
});
} else {
console.log("DEBUG: Row is already selected");
}
}
The usage of that function is by doing this:
$("#list tbody tr").click(function () {
select_order(this);
});
At the first place, i was deploying all the HTML data via PHP. This took a pretty long time, it could take from 500ms to about 1 second. In my opinion thats pretty long.
I was doing that like this (select-order.php):
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
while ($row = mysqli_fetch_array($order_data)) {
echo "<h1>Klant informatie</h1>";
echo "<p>Voornaam: " . $row['first_name'] . "</p>";
echo "<p>Achternaam: " . $row['last_name'] . "</p>";
echo "<p>Emailadres: " . $row['email_adress'] . "</p>";
echo "<p>Klant informatie: " . $row['customer_info'] . "</p>";
echo "<br>";
echo "<h1>Bestellingsinformatie</h1>";
echo "<p>Order informatie: " . $row['order_info'] . "</p>";
echo "<p>Locatie: " . $row['location'] . "</p>";
echo "<p>Gemaakt op: " . $row['created'] . "</p>";
}
echo "<br>";
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Product naam</th>";
echo "<th>Hoeveelheid</th>";
echo "</tr>";
echo "</thead>";
while ($row = mysqli_fetch_array($order_items)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
exit;
}
This goes together with the Database class with all the functions:
class Database extends mysqli
{
// single instance of self shared among all instances
private static $instance = null;
private $databaseHost = "";
private $databaseUser = "";
private $databasePassword = "";
private $databaseName = "";
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
function __construct() {
parent::__construct($this->databaseHost, $this->databaseUser, $this->databasePassword, $this->databaseName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
parent::set_charset('utf-8');
}
function get_all_data_by_order_id($order_id) {
$query = "SELECT customers.first_name,
customers.last_name,
customers.email_adress,
customers.customer_info,
orders.order_info,
orders.total_price,
orders.location,
orders.created
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
WHERE orders.id = {$order_id}";
return $this->query($query);
}
function get_order_items_by_order_id($order_id) {
$query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`\n" . "INNER JOIN `products`ON `orders-items`.`products_id` = `products`.`id`\n" . "WHERE order_id=" . $order_id;
return $this->query($query);
}
}
Now someone told me i could better translate the data into json and return that, so i did this:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$rows = array();
while ($row = mysqli_fetch_array($order_data)) {
$rows[] = $row;
}
return json_encode($rows);
exit;
}
But as expected, nothing really happened. So i tried changing the javascript to this (trying it as a array because i'm returning it that way?), to deploy one piece of data:
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data['first_name']);
}
});
But that didn't work aswell.
Problems
The previous PHP code was to slow, so i had to find another way.
When trying to deploy HTML into the other screen, it doesnt do anything. It stays on the 'loading...' screen, so the success function was'nt reached.
Question
How can my piece of code be changed so it will actually deploy parts of the data from the mysql database?
In your $.ajax() call you should define what type your response data is expected to be, by adding the following parameter to the call:
dataType: 'json'
Also, you should try echo json_encode($rows); your data instead of returning it.
**Edit: you are receiving an array of arrays, so your original referencing in the success callback won't suffice. Having another look at your MySQL part, If you are only expecting one row to be returned by your query, then you can change your PHP to:
$row = mysqli_fetch_array($order_data);
echo json_encode($row); // instead of $rows
instead of the while loop. That way your selectedOrderInformation.html(data['first_name']); will most likely work.
To clean your query up a bit:
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = " . $order_id;
You could also switch your INNER JOIN to a LEFT JOIN in your "get order data" function. An inner join is absolutely useless here, as you'll have all your data paired based on the foreign keys anyways.
I would try secluding some of the codebase: try commenting out the Database::getInstance() calls, and supplementing some testdata into the processes. To put it short, fake a returned response, by declaring a $row = array('first_name' => 'Joe', 'order_date' => '2014-08-29 11:11:52', ...); and returning that. If its way faster, then your database server might be the bottleneck. If its still slow, then 500ms - 1000ms is actually argueably code related, it might be other hardware aspects that cause the problem. Or for example, do you have your jQuery library loaded from a CDN, or locally?
**Edit: As #Debflav pointed out (and I've also touched upon the matter), that your queries could benefit from not being executed as simple queries, but transforming them into prepared statements. For the full story you could start checking out PHP.net : Prepared Statements, or to keep it short:
Prepared statements look almost just like your everyday query, however variables are not just concatenated into the query string, rather bindings are used.
You use the database handler's prepare function instead of query - with this method, you are requesting the MySQL server to inspect your query and optimize it for later use (which will come handy if you're doing the same query over and over again, just with a few varying values).
For more detailed insights on the mechanics of prepared statements and how to get the hang of it for efficiently utilizing it in your projects I recommend you research the topic a bit, but as a quick conversion for your example at hand, it would look like this:
function get_all_data_by_order_id($order_id) {
$query = "SELECT c.first_name, c.last_name, c.email_adress, c.customer_info,
o.order_info, o.total_price, o.location, o.created
FROM customers AS c
LEFT JOIN orders AS o ON c.id = o.customer_id
WHERE o.id = :order_id";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
and
function get_order_items_by_order_id($order_id) {
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = :order_id;";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
And to reflect on how you would build up your JSON response with data including the order headers and the connected order-items would be:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$orderObject = array();
$orderObject['header'] = mysqli_fetch_array($order_data);
$orderObject['items'] = array();
while ($orderedItem = mysqli_fetch_array($order_items)){
$orderObject['items'][] = $orderedItem;
}
echo json_encode($orderObject);
}
This way your jQuery could look something as follows:
....
success: function (data) {
selectedOrderInformation.html('<h3>' + data['header']['first_name'] + '</h3><ul>');
$.each(data['items'], function(i, item) {
selectedOrderInformation.append('<li>' + item['name'] + ' x ' + item['quantity'] + '</li>');
});
selectedOrderInformation.append('</ul>');
}
....

How to export javascript ajax data to csv? [duplicate]

This question already has answers here:
Download file through an ajax call php
(6 answers)
Closed 8 years ago.
What I want to do:
1,use Javascript ajax POST array to PHP;
2,use POST array to search result from mysql with PHP;
3,return search results with csv format, so user can save the file.
I have accomplished part 1 and part 2, but I can't get csv file returned
I use ajax to POST array data to PHP like this:
$(document).ready(function(){
$('#export').click(function(){
var list = JSON.stringify(count);
$.ajax({
type: "POST",
url: "exportDataColoniesNumber.php",
data: {'data': list},
success: function(response){
alert(response);
}
});
});
});
And process the data in exportDataColoniesNumber.php, and the page is to return a csv file:
<?php
$data = json_decode($_POST['data']);
$last_key = end(array_keys($data));
$sql = "SELECT * FROM coloniesNumber WHERE ";
foreach ($data as $key => $value) {
$sql .= "num='" . $value . ($key == $last_key ? "';" : "' OR ");
}
$con = DatabaseConnection::get()->connect();
mysql_query('set names utf8');
mysql_select_db('fish') or die('Could not select database');
$result = mysql_query($sql);
$lines = '';
while($row = mysql_fetch_array($result)) {
$line = '';
for($i = 0; $i < $fields; $i++) {
$line .= $row[$i] . ",";
}
$lines .= trim($line) . "\n";
}
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:csv".date("Y-m-d").".csv");
header("Content-disposition:filename=test.csv");
print "$lines";
?>
The alert(response) return csv data:
8,4008,11.267,fat,1,,
9,4009,12.022,thin,1,,
10,4010,11.356,thin,1,,
11,4011,10.873,thin,1,,
12,4012,11.017,thin,1,,
13,4013,11.301,thin,1,,
How can I get csv file returned ?
Personally i've created a PHP handler that exports to csv, make sure you have these headers
header("Content-Disposition: attachment; filename=report.csv");
header("Content-Type: text/csv");
Then just echo your data, csv-formatted or use one of the many free csv classes that does that for you (just call a function with an Array as a parameter)
Then make your form (asuming you have one) post to a hidden iframe of 1x1 pixels and set offscreen with css
iframe { position: absolute; left: -9999px; }
You should be all set, and the export will pop up - however, make sure the file is not big or your script takes a lot of time to complete - until then, the download won't show up.

Categories