Option select get value without reloading page - javascript

I want to sort my page content with select option, but how can I prevent reloading page?
I know that it can't be done in PHP, so I need help, how to do this in javascript or maybe in ajax.
This is my code
<select name="quantity">
<option value="1"></option>
<option value="2"></option>
</select>
<?php
$redirect_url = "example.com/process.php?&quantity=" . $_POST['quantity'];
header("Location: " . $redirect_url);
?>
UPDATED
This is code what I want to sort:
$sql = '';
if(isset($_POST['search'])){
$search = sanitize($_POST['search']);
$cat = sanitize($_POST['category']);
if(!empty($search)){
$search_query = mysql_query("SELECT * FROM products WHERE `product_name` LIKE '%$search%' OR `category` LIKE '%$cat%'".$sql);
while ($results_row = mysql_fetch_assoc($search_query)){
echo '<div class="product"><img style="border:1px solid black;" src="'.$results_row['img_path'].'/'.$results_row['img_name'].'" width="230px" height="230px"/><br><div class="br"></div><strong>'.$results_row['product_name'].'</strong><br>Cijena: '.$results_row['price'].'kn</div>';
}
}
}else{
}
I sorted it like this:
$sql = '';
if(isset($_GET['sort'])){
if ($_GET['sort'] == 'year')
{
$sql = " ORDER BY year";
}
elseif ($_GET['sort'] == 'IMDBrating')
{
$sql = " ORDER BY IMDBrating";
}
elseif ($_GET['sort'] == 'userrating')
{
$sql = " ORDER BY userrating";
}
}
?>
<th>Year</th>
<th>IMDB rating</th>
<th>user rating</th>
But I wanto to sort it with <select><option> not with`

Did't clear out what you want by sort my page content with select option, but for reload functionality use jQuery ajax for this.
Html
<select name="quantity" id="quantity">
<option value="1"></option>
<option value="2"></option>
</select>
JS
<script>
$(function(){
$('#quantity').change(function(){
var value = $(this).val();
$.ajax({
type: "POST",
url: "example.com/process.php", // url to request
data: {
quantity: value // send data
},
success : function(data){
// populate data here
}
});
});
});
</script>
process.php
$quantity = $_POST['quantity'];
echo $quantity // this value will available in success callback function

you can sort it when an event takes place eg:
document.getElementsByName('quantity').onclick=function(){
//then put here what you want to be executed
}
then the whole page will not be reloaded.only that piece of code will run.

Related

How to fetch mutiple values on select option and display in input type using ajax?

I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research

How do I pass MySQL rows to a specific div in html using PHP?

Good day to everyone. So I am trying to get the value of a select option and getting a set of rows in MySql depending on the column name in the database. So here is the HTML code:
<html>
<body>
<select name = "FilterDoc" onchange = "filterby(this);">
<option disabled>Filter By</option>
<option value="document_type">Document Type</option>
<option value="date">Date</option>
<option value="hei">HEI</option>
<option value="other">Other Govt.</option>
<option value="person">Person</option>
</select>
<div class="panel-body" id="container">
</div>
Here is code for Ajax:
<script type="text/javascript">
function filterby(sel){
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {FilterDoc: $(sel).val()},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response)
{
$("#responsecontainer").html(response);
}
console.log(reply);
});} </script>
Now the value of the select option will pass to the PHP file. I dont know if "if statement" is the right one for this since I haven't had that much background about getting values on html and such and I'm trying to find a better way to get the rows from MySql and display them into the container.
Here's the PHP code:
<?php echo"<div class='panel panel-primary' id='container'>";
if($_POST["FilterDoc"]=="document_type")
{
echo "<script type='text/javascript'>$('container').html('""');</script>";
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY document_type ASC");
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="date")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY date_received DESC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="hei")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY hei ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Other")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY other_govt ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Person")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY contact_person ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}echo"</div>"; ?>
I'm also not entirely sure if using javascript to clear the container is the proper way before putting contents into the div container.
I would really appreciate your help. Thank you!
At first i would simplify the code like :
<?php
echo "<div class='panel panel-primary' id='container'>";
// Set Variable
$filter = $_POST["FilterDoc"]; // This needs proper escaping
$result = mysqli_query($conn,"SELECT * FROM records ORDER BY $filter ASC");
while($data = json_encode(mysql_fetch_assoc($result)) {
echo json_encode($data);
}
echo "</div>";
Thats the PHP part, now i would rewrite the javascript.
function filterby(sel) {
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {
FilterDoc: $(sel).val()
},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#container").empty().html(response);
}
});
}
But maybe your whole filtering process may be inefficient. You could fetch all the data with one SQL call and do the filtering with JS / data-attributes.

getting select box to display selected value in different select box

I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.

update echo "select option " on mysql

I have a form that updates the adds to the table. This table is retrieved live. which means once submitting the form you can view the content on the table. I added a select option drop down on the table content. I am not sure how to get this info in back to mysql once the user chooses his option. As seen in the code my file is a PHP file.
my select option is updates by javascript but it does not update mysql.
Kindly guide me. Thank you
while($row = mysqli_fetch_assoc($resultset))
{
echo "<tr id=\"row\">
<td class=\"fname\" data-id1=".$row["contact_id"]." contenteditable>" . $row['fname'] ." </td>
<td class=\"lname\" data-id2=".$row["contact_id"]." contenteditable>" . $row['lname']. "</td>
<td>" . $row['contact']."</td>
<td>
<select id4=".$row['contact_id']." name=\"rsvp\" onchange = \"fetch_select(this.value)\">
<option name=\"not-done\" value=\"not-done\">Not done</option>
<option name=\"attending\" value=\"attending\">Attending</option>
<option name=\"not-attending\" value=\"not-attending\">Not-attending</option>
<option name=\"maybe\" value=\"maybe\" selected>Maybe</option>
</select>
</td>
<td><button id3=".$row['contact_id']." name=\"button\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>
<tr>";
}
echo "</table>";
mysqli_close($con);
?>
$('select').on('change', function()
{
// Show an alert
alert( "The new value of the select is " + $(this).val() );
var id=$(this).attr("id4");
var val=$(this).val();
function fetch_select(val ,id)
{
$.ajax({
url:"updateselect.php",
method:"POST",
data:{rsvp:val , id:id},
dataType:"text",
success:function(data){
alert(data);
}
});
}
});
<?php
$connect = mysqli_connect("localhost", "root", "", "registration");
$id = $_POST["id"];
$rsvp = $_POST["val"];
$sql = "UPDATE guestlist SET rsvp ='".$rsvp."' WHERE contact_id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
You want to create a form surrounding your dropbox; now you can either submit it using ajax or just submit it to a different page, your call.
It would look something like this:
Note: Add a name param to your select so you can actually get it using $_POST and handle the data.
<form method="post" action="rsvp_handler.php">
<?php
while($row = mysqli_fetch_assoc($resultset))
{
echo "<tr id=\"row\">
<td class=\"fname\" data-id1=".$row["contact_id"]." contenteditable>" . $row['fname'] ." </td>
<td class=\"lname\" data-id2=".$row["contact_id"]." contenteditable>" . $row['lname']. "</td>
<td>" . $row['contact']."</td>
<td>
<select name='rsvp' id='rsvp'>
<option value=\"not-done\">Not done</option>
<option value=\"attending\">Attending</option>
<option value=\"not-attending\">Not-attending</option>
<option value=\"maybe\" selected>Maybe</option>
</select>
</td>
<td><button id3=".$row['contact_id']." name=\"button\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>
<tr>";
}
echo "</table>";
mysqli_close($con);
?>
<button type="submit" name="submit">Submit</button>
</form>
Then for the rsvp_handler.php page just take the post result and then send the wanted data to your database:
if (isset($_POST['submit']))
{
$rsvp = $_POST['rsvp'];
//... any other elements
// create your query here
$sql = "INSERT INTO " . $table . " (rsvp, row2, row3) VALUES (?, ?, ?)";
// best way is to create prepared statements
if($stmt = $mysqli->prepare( $sql ))
{
// bind the params
$stmt->bind_param('sss', $rsvp, $val2, $val3);
// execute the query
$stmt->execute();
// close the connection
$stmt->close();
}
}
Hi I found the answer to the solutions.
My ajax need to have a separate function.

having issues while trying to populate second drop down-list dynamically using AJAX

i am trying to populate second dropdown based on the selected option of 1st dropdown but i am unable to do so i dont know what i am doing wrong but something is wrong all my endeavors to achieve my desired results are dashed to the ground cuz its not working kindly help me
so far i have done this....
<select name="ddl_company" size="1" class="form-control" id="ddl_company" onchange="getId(this.value);">
<option value="">Select Company</option>
<?php
//Getting Company name from mysql and displaying it in the 1st dropdown having id ddl_company
$query = mysql_query("select * from company where company_status='Active'order by company_name asc");
while ($r = mysql_fetch_array($query)) {
if ($r['company_id'] == $ddl_company) {
echo "<option selected value=$r[company_id]>$r[company_name]</option>" . "<BR>";
} else {
echo "<option value=$r[company_id]>$r[company_name]</option>";
}
// second drop down list which is going to fetch data from mysql db based on the selected option of 1st dropdown
?>
<select name="ddl_dept" size="1" class="form-control" id="ddl_dept">
<option value=""></option>
</select>
//ajax implementation of 2nd dropdown
<script type="text/javascript">
function getId(val)
{
$.ajax({
type:"POST",
url:"getdata.php",
data:"company_id="+val,
success:function(data)
{
$('#ddl_dept').html(data);
}
});
}
</script>
finally get_data.php file
<?php
include("../newconfig.php");
if (!empty($_POST['company_id'])) {
$company_id = $_POST['company_id'];
$query = "select * from department where department_status='Active'LIMIT 1 AND company_id='$company_id'LIMIT 1";
$sqlquery = mysql_query($query);
while ($r = mysql_fetch_array($sqlquery)) {
# code...
if ($r['company_id'] == $company_id) {
echo "<option selected value=$r[department_id]>$r[department_name]</option>" . "<BR>";
} else {
echo "<option value=$r[department_id]>$r[department_name]</option>";
}
}
}
}
?>
I have done all this yet its not working kindly help me i shall be very thankful. btw thats my output
click this to show the result
Try something like this : jquery
$("select#ddl_dept").on('change',function(){
var selected = $('#ddl_company option:selected').text();
getId(selected );
});

Categories