Ajax dropdown call to function can't show me all values - javascript

Hello I'm using ajax to call on-change drop-down list and select all value from database into table row format but it only show me the last record from database into table row.
I have three rows in database related to one select from drop-down list and I want to show all three rows into table row format. My code is
$(document).ready(function(){
$('#location').change(function(){
$.ajax({
url:'location.php?location=' + $(this).val(),
type: "get",
timeout:10000,
dataType: 'json',
success: function(data){
document.getElementById("material_name").value=data.material_name;
document.getElementById("material_quantity").value=data.product_quantity;
},
error:function(){
}
});
});
and location.php page is as:-
<?php
require_once("shine_class.php");
$s = new shine;
$s->connection();
$location = $_REQUEST['location'];
$query ="SELECT * from material_used where product_name = '$location' ";
$query1=mysql_query($query);
while($row = mysql_fetch_array($query1))
{
$result1=$row['material_name'];
$result2=$row['product_quantity'];
}
echo json_encode(array("material_name"=>$result1,"product_quantity"=>$result2));
?>

Related

ajax to change content from dropdown not working

I have created a website. I have created a dropdown in it for displaying different data while the user selects different dropdown, my code is as below
$(document).ready(function(){
// code to get all records from table via select box
$("#course_title").change(function() {
var tid = $(this).find(":selected").val();
var dataString = 'tid='+ tid;
$.ajax({
url: 'mycourses.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#heading").show();
$("#no_records").hide();
$("#emp_name").text(employeeData.tid);
$("#emp_age").text(employeeData.training_name);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
<select class="form-control sel" name="trainings" id="trainings" >
<option value="select options" selected disabled>Select Training Course</option>
<? $sql_trainings = "SELECT * FROM tbl_data";
$trainings_data = mysqli_query($con,$sql_trainings);
while($row = mysqli_fetch_assoc($trainings_data) ){
$trainingid = $row['tid'];
$training_name = $row['training_name'];
echo "<option value='".$trainingid."' >".$training_name."</option>";
}
?>
</select>
i have another page as getcourses.php as below
<?php
include "config.php";
$trainingid = $_POST['tid']; // department id
$sql = "SELECT tid,training_name FROM tbl_data WHERE id=".$departid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['tid'];
$name = $row['training_name'];
$users_arr[] = array("tid" => $userid, "training_name" => $name);
}
// encoding array to json format
echo json_encode($users_arr);
The dropdown is first displayed in a page, then when the user clicks the dropdown, they are taken to different page showing the content of the dropdown they selected, it's showing the content the first time when the user clicks the dropdown and is being taken to the different page to show content, but when the user clicks different dropdown from the result page the dropdown doesn't work, nothing happens, I want to display the content of dropdown which the user selects in the resulting page, whenever user changes dropdown it should be appearing. my table name is tbl_data and my columns are tid and training_name.
Can anyone tell me what is wrong with my code?
$("#course_title").change(function() {
should be,
$("#trainings").change(function() {
So your js code should be like,
$(document).ready(function() {
// code to get all records from table via select box
$("#trainings").change(function() {
var tid = $(this).val(); // this is enough to get selected value
$.ajax({
url: 'mycourses.php',
type: 'POST', // you forgot type
data: {tid : tid},
success: function(employeeData) {
// same as your code
}
});
})
});

How to Display Categories in Select Box to Update the Record?

Hey Everyone Please help me, I want to update the record, but the problem is I can't see more than 1 categories in the select box. I have been using Php/MySQLi and Also Ajax.
Total Categories Stored in the Database Three
So, Please Look at that:
Here is Php Function
function get_product_record()
{
global $con;
$Pro_Update_Id = $_POST['Pro_Update_ID'];
$query = "SELECT Product.Product_ID, categories.cat_name, categories.cat_id, product.Product_Name,product.Product_Qty,product.Price,product.Description from product INNER JOIN categories on product.Category_ID=categories.cat_id where product.Product_ID='$Pro_Update_Id'";
$result = mysqli_query($con,$query);
while($row=mysqli_fetch_assoc($result))
{
$data = "";
$data[0]=$row['Product_ID'];
$data[1]=$row['cat_name'];
$data[2]=$row['Product_Name'];
$data[3]=$row['Product_Qty'];
$data[4]=$row['Price'];
$data[5]=$row['Description'];
$data[6]=$row['cat_id'];
}
echo json_encode($data);
}
Here is jQuery File
function get_pro_record()
{
$(document).on('click','#p_btn_edit',function()
{
var GetPID = $(this).attr('data-id');
$.ajax(
{
url: 'includes/products/get_pro_record.php',
method: 'post',
data:{Pro_Update_ID:GetPID},
dataType: 'JSON',
success:function(data)
{
$('#product_id').val(data[0]);
$('#cat_up_name').html('<option id="p_update_id" value='+(data[6])+'>'+(data[1])+'<option>');
$('#product_up_name').val(data[2]);
$('#up_Qty').val(data[3]);
$('#up_Price').val(data[4]);
$('#up_description').val(data[5]);
$('#products_update').modal('show');
}
})
})
}
Here is a Screenshot of the Project:

How to toggle the data fetched from AJAX?

I have this code in which I am trying to show and hide the data on clicking a product number and the data is being fetched from database through AJAX. I want the data to be shown beneath the desired row. I want to put the data in tbody and show it on clicking its product number.
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<tr><td align="center"><?php echo $row['FONumber']; ?></td></tr>
<tbody id='sd'<?php echo $p; $p++; ?>></tbody>
<?php }
}
Javascript and AJAX:
$(function(){
$('#hover1').on({
mouseenter:function(){$(this).css("background","grey")},
mouseleave:function(){$(this).css("background","white")}},'tr');
});
// number of tds
var c = $('#hover1').find('td').length;
var id = document.getElementById("hover1");
for(var i = 0; i < c; i++){
id.rows[i].onclick=(function(){
var a = $(this).find('td:eq(0)').text();
$.ajax({
url: 'printpo1.php',
type: 'post',
data: {fo:a},
success: function(data){
$('#name').html(data);
}
});
$('#sd'+i).toggle();
alert('#sd'+i);
});
}
So far the data I am trying to fetch is showing in the tbody of the first row. Any help will be really appreciated.

How can I save a DropDown into a Database with AJAX

I've looked really hard on this but I can't get my head around AJAX working with PHP.
This is what I have and when a user clicks on the dropdown I would like it to save into my database
<select>
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
And this is the query i'd like to run:
INSERT INTO snagging (taskstatus, updated_at)
WHERE ID = 1234
VALUES taskStatusRow['name'], $now);
I'll give you a overall flow of AJAX here. I tried to provide comments so as to show the control flow.
<select id="selectOption"> //******* Assign an ID
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
jQuery + AJAX
$(document).ready(function() {
$("#selectOption").change(function(){ //** on selecting an option based on ID you assigned
var optionVal = $("#selectOption option:selected").val(); //** get the selected option's value
$.ajax({
type: "POST", //**how data is send
url: "MYPROCESSPAGE.php", //** where to send the option data so that it can be saved in DB
data: {optionVal: optionVal }, //** send the selected option's value to above page
dataType: "json",
success: function(data){
//** what should do after value is saved to DB and returned from above URL page.
}
});
});
});
Inside your MYPROCESSPAGE.php, you can access the data passed via AJAX like:
<?php
$selectedOptionVal = $_POST['optionVal'];
//DB CONNECTION STEPS
.
.
.
// You are trying to "UPDATE" a table data based on some ID and not inserting. Included both operations
// If you are INSERTING A new table entry, use below code.
//INSERT INTO snagging (taskstatus, updated_at) VALUES ('$selectedOptionVal', 'Now()');
// If you are UPDATING an existing table entry, use below code.
//UPDATE snagging SET taskstatus = '$selectedOptionVal', updated_at = 'Now()' WHERE ID = 1234;
?>
Hope it's helpful.

DIV not being created from PHP when doing AJAX call

I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});

Categories

Resources