I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!
Related
I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.
i'm still fresh in using AJAX and i'm having hard time with it.can you please help me with this? i actually have a dropdown and when i select an item in that dropdown a table of queries should print to the tbody.here's my code:
the PHP code:
<select id="proj_id" name="proj_id" onchange="myFunction(this.value)">
<option value="none">---select project---</option>
<?php
//Projects
$r = #mysql_query("SELECT `proj_id`, `proj_name` FROM `projects`");
while($rows = mysql_fetch_assoc($r)) {
$proj_id = $rows['proj_id'];
$proj_name = $rows['proj_name'];
echo '<option value='.$proj_id.'>'.$proj_name.'</option>';
}
?>
</select>
<table>
<thead>
<tr>
<th>Project Name</th>
<th>Material Name</th>
<th>Quantity</th>
<th>Status</th>
</tr>
</thead>
<tbody id="project_estmat">
<?php
//Display Requests
$r = #mysql_query("SELECT `proj_name`, `mat_name`, `req_qty`, `stat_desc` FROM `requests` JOIN `projects` USING(`proj_id`) JOIN `materials` USING(`mat_id`) JOIN `status` ON(requests.stat_id = status.stat_id)");
while ($row = mysql_fetch_array($r)) {
echo '<tr>';
echo '<td>'.$row['proj_name'].'</td>';
echo '<td>'.$row['mat_name'].'</td>';
echo '<td>'.$row['req_qty'].'</td>';
echo '<td>'.$row['stat_desc'].'</td>';
echo '</tr>';
}
?>
</tbody>
</table>
jS CODE:
function myFunction(value){
if(value!="none")
{
$.ajax(
{
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
success: function(data) {
$('#project_estmat').html(data);
}
});
}
else
{
$('#project_estmat').html("select an item");
}
}
and I have this PHP code that should be in the #project_estmat which is a table. And I think this is where the problem lies. Because everytime I select an item, nothing is printing in the table. It shows empty data.
<?php
if (isset($_POST['proj_id'])) {
$r = #mysql_query("SELECT `proj_name`, `mat_name`, `req_qty`, `stat_desc` FROM `requests` JOIN `projects` USING(`proj_id`) JOIN `materials` USING(`mat_id`) JOIN `status` ON(requests.stat_id = status.stat_id)");
if($r){
while ($row = mysql_fetch_array($r)) {
echo '<tr>';
echo '<td>'.$row['proj_name'].'</td>';
echo '<td>'.$row['mat_name'].'</td>';
echo '<td>'.$row['req_qty'].'</td>';
echo '<td>'.$row['stat_desc'].'</td>';
echo '</tr>';
}
}
exit;
}
?>
you have wrapped $.ajax function with, ${
it should be like the following, and try using change, and remove the inline function calling when you do this,
$('#proj_id').change(function() {
var value = $(this).val();
if(value!="none"){
$.ajax({
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
success: function(data) {
$('#project_estmat').html(data);
alert(data);//check whats coming from the server side
}
});
}
});
tested out with a simplified php code to the server end such as the following,
<?php
if (isset($_POST['proj_id'])) {
echo '<tr>';
echo '<td>A</td>';
echo '<td>B</td>';
echo '<td>C</td>';
echo '<td>D</td>';
echo '</tr>';
}
?>
everything looks fine except you have a '$' extra in your if condition
if(value!="none")
${ //here
removing the '$' sign should work...
You shouldn't use the function mysql_query since its deprecated as of PHP 5.5.0 and will be removed (http://php.net/manual/en/function.mysql-query.php). You better use the PHP PDO class (http://php.net/manual/en/book.pdo.php).
Dont suppress your error using '#' error_compression operator. Remove the # symbol from mysql_query and try debugging your code.
Try building a string and sending it back.
$str = '';
if($r){
while ($row = mysql_fetch_array($r)) {
$str .= '<tr>';
$str .= '<td>'.$row['proj_name'].'</td>';
$str .= '<td>'.$row['mat_name'].'</td>';
$str .= '<td>'.$row['req_qty'].'</td>';
$str .= '<td>'.$row['stat_desc'].'</td>';
$str .= '</tr>';
}
return $str;
}
Then when the loop is done we can send the string back. While the dataType property .ajax() uses intelligent parsing to decide what type of data is being sent back and how to construct the returned object, you should just declare it.
$.ajax({
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
dataType:'html',
success: function(data) {
$('#project_estmat').html(data);
}
});
I have another question:
Ajax Forms are working well. Most of them need to do mysql stuff and only return values if the entry could be written or not. I used just echo statements. For example echo "1"; if the values could be written and echo "2"; if the values could not be written.
Now I need to call back 3 variables. I know that I can write them in an array. My problem is just, that I can't return this variable into my visible site.
This is my JavaScript Code:
//Show statistic
$('.statistic_submit').click(function(){
if ($('#month').val() == 'none' || $('#year').val() == 'none') {
$("#dialog_empty").dialog( "open" );
return false;
}
var form = $('#statistic_view');
var data = form.serialize();
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
success: function (reqCode) {
if (reqCode == 1) {
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});
return false;
});
This is my html code:
<div>
<form id="statistic_view" action="include/scripts/user_statistic.php" method="post">
<select name="month" id="month">
<option value="none" class="bold italic">Monat</option>
<?php
for($i=1; $i<=12; $i++){
if($i == $month)
echo "<option value=\"".$i."\" selected>".$month_name[$i]."</option>\n";
else
echo "<option value=\"".$i."\">".$month_name[$i]."</option>\n";
}
?>
</select>
<select name="year" id="year">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2012; $i<=$year; $i++){
if($i == $year)
echo "<option value=\"".$i."\" selected>".$i."</option>\n";
else
echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<br/><br/>
<div id="user_statistic">
<input type="submit" id="small" class="statistic_submit" value="Daten anzeigen">
</div>
</form>
<br />
<div class="done">
<p class="bold center"><?php echo "Besucher ".$month_name[$month]." ".$year; ?></p>
<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>
<script>
chart = new RGraph.Line('cvs', <?php print($data_string) ?>);
chart.Set('chart.tooltips', <?php print($labels_tooltip) ?>);
chart.Set('chart.tooltips.effect', 'expand');
chart.Set('chart.background.grid.autofit', true);
chart.Set('chart.gutter.left', 35);
chart.Set('chart.gutter.right', 5);
chart.Set('chart.hmargin', 10);
chart.Set('chart.tickmarks', 'circle');
chart.Set('chart.labels', <?php print($labels_string) ?>);
chart.Draw();
</script>
</div>
</div>
And this my user_statistic.php:
... (mysql stuff)
/******************************/
/** Create diagram
/******************************/
$labels = array();
$data = array();
for ($j=1; $j<=$days; $j++) {
$labels[$j] =$j;
$data[$j] = $day_value[$j];
}
// Aggregate all the data into one string
$data_string = "[" . join(", ", $data) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
$labels_tooltip = "['" . join("', '", $data) . "']";
//data written
echo "1";
So echo "1"; tells my script that everything is fine. But now I need $data_string, $labels_string and $labels_tooltip. So how can I return these values from user_statistic.php into my side?
Avoid converting arrays to strings on your own. If you need to pass a PHP array back to your jQuery, you should do so with the json_encode function:
echo json_encode( $array );
This will come through as a JSON object which you can then handle client-side. Your JSON string will be returned into the callback of your $.ajax method:
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: 'json',
success: function ( response ) {
/* response is your array, in JSON form */
}
});
For instance, if our PHP script did the following:
$response = array(
'message' => 'Success',
'allData' => array( 'Jonathan', 'Mariah', 'Samuel', 'Sally' )
);
echo json_encode( $response );
We could alert the message from our jQuery like this:
success: function ( response ) {
alert( response.message );
}
The best approach here would be to return a json object. Create an array on server side -
$response['error_code'] = '1'; //everything ok. 0 if not ok
$response['data_string'] = 'this will have some data';
$response['labels_string'] = 'labels';
$response['labels_tooltip' = 'here goes the tooltips';
echo json_encode($response);
and in your javascript code, mention the return datatype as json -
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: json,
success: function (reqCode) {
if (reqCode.error_code == 1) {
alert('this is the data string '+resCode.data_string);
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode.error_code == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});
I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.
I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )