Character data is not passing from php to jquery - javascript

Html file
The values for the sub combobox is retrieved by a php select query and the values are characters.
i have tried with integers values are perfectly passed.
<select name="sub" id="sub">
<option value="">Select semester first</option>
</select>
<select name="staff" id="staff">
<option value="">Select sub first</option>
</select>
Javascript
$('#sub').on('change',function(){
var SUB = $(this).val();
if(1){
$.ajax({
type:'POST',
url:'sta.php',
data:'sub='+SUB,//character is not passing.
success:function(html){
$('#staff').html(html);
}
});
}else{
$('#staff').html('<option value="">Select sub first</option>');
}
});
php file
if(isset($_POST["sub"]) && !empty($_POST["sub"]))
{
//Get all city data
$query = mysql_query("SELECT staff_name FROM subject WHERE course_name = ".$_POST['sub']);
//Count total number of rows
$rowCount = mysql_num_rows($query);//It always shows 0
//Display cities list
if($rowCount > 0){
echo '<option value="">Select staff</option>';
while($row = mysql_fetch_assoc($query)){
echo '<option value='.$row['staff_name'].'>'.$row['staff_name'].'</option>';
}
}else{
echo '<option value="">staff not available</option>';//when i tried to execute it comes here
}
}

There is simple syntactical error in your query in php just rewrite it as:
$query = mysql_query("SELECT staff_name FROM subject WHERE course_name = '".$_POST['sub']."'");
wherever you pass the data other than numbers always use single inverted comma such as'myData' to surround the values.

Related

How to get multiple data from select item in jquery

I am trying to get multiple value from multiple select textbox and use the same value in PHP for adding the SUM.
My code is:
function get_amount() {
var x = $('#work').val();;
alert(x);
$.ajax({
type: "POST",
url: "get-sum.php",
data: 'id=' + x,
success: function(data) {
alert(data);
//$('#html').load(document.URL + ' #html');
}
});
}
<select class="select2 select2-multiple" multiple="multiple" data-placeholder="Choose" name="work[]" id="work" onchange="get_amount()">
<option value="1" >option 1</option>
<option value="2"> OPtion 2 </option>
<option value="3"> OPtion 3</option>
</select>
And My php file as :
$id = $_POST['id'];
function getAmount($id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT
(amount)
FROM work
WHERE id = ?
");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $amount;
}
$sql = getAmount($id);
echo $sql;
Error which i am getting is the data which i am getting from multiple select is like 5,6,7 and its always hitting the php file at id 5. And the second problem how i will be able to add all $sql data.
I have done some changes in my PHP code :
$id = $_POST['id'];
$sum = 0;
for($i = 0; $i<count($id); $i++) {
$sum = $sum + getAmount($id[$i]);
}
echo $sum;
function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->fetch();
return $amount['total'];
}

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

Option select get value without reloading page

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.

How to make <select> <option> related to another <select>'s <option>?

I'm working on a form. There are select elements and their options are from a database.
When i choose the first (for example a school class) the second have to show only those names who are in the class selected at first, from database too.
I'm rookie at Javascript and JQuery so I'm okay with page refreshing PHP solutions but I can't figure it out on my own. Can you please give me some instructions or advices how to start to work on this?
You can achieve this with ajax using preferably jquery and json.
javascript/ajax:
function fillSecondSelect()
{
$.get("ajaxFill.php?id=" + $("#class").val(),"",function(data) {
var selectData = "<option value=''> - Choose Student - </option>";
data = JSON.parse(data);
for(i=0;i<data.length;i++)
{
selectData += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#students").html(selectData);
});
}
html:
<select id="class" name="class" onchange="fillSecondSelect()">
<option value=""> - Choose Class - </option>
<option value='1'>Class A</option>
<option value='2'>Class B</option>
</select>
<select id="students" name="students"></select>
ajaxFill.php (which should get the student data according the class id sent from mysql and serve it as JSON):
$result = mysqli_query($link,"SELECT * FROM students WHERE class_id = '" . $_GET['id'] . "'") or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result))
{
$students[] = array("id" => $row['student_id'], "name" => $row['student_name']);
}
echo json_encode($students);
You use Jquery and Ajax to fetch the Students in a class based on the Class selected and load the student list into a Select element without refreshing the page.
HTML
<select id="selectedclass" onBlur="loadstudent();">
<option>class 1</option>
<option>class 2</option>
<option>class 1</option>
</select>
<select id="students" ></select>
Javascript
function loadstudent(){
var selectedclass = $('selectedclass').val();//user id
$.ajax({
type:'POST',
url: your php script,
data: 'selectedclass='+selectedclass,
dataType: 'json',
success: function(data)
{
var classlist='', html;
for(var i = 0; i < data.length; i++) {
classlist = data[i];
html+=classlist.students
}
//get number of outbox
$('#students').html(html);
},
error: function(jqXHR, exception) {
alert('Error');
}
});
}
PHP
<?php
include "config.php";//database connection file
//database using PDO
$db = pdoDB::getConnection();
//data from html
$student_class=$_POST['selectedclass'];
$query = "SELECT student_lastName,student_firstName
FROM student_table WHERE student_class='student_class'";
$result = $dbase->query($query) or die("failed!");
while ($row = $result->fetch(PDO::FETCH_BOTH)){
//credits info
$studentlist="<option>".$row['student_lastName']." ".$row['student_firstName']."</option>";
$results[] = array("students"=>$studentlist);
}
header('Content-type:application/json');
exit (json_encode($results));
?>
The data sent from the PHP script should be encoded with JSON
Modern websites use ajax to do this.
After the first item is selected an ajax request is sent which delivers the data for the second select.
There are many ways to build the second select. The ajax response could contain a json array with all the data and then you build the select field with js.
Or the response delivers complete html and all you have to do is to insert it.
I think this is exactly that you mean: http://codepen.io/man/pen/oBFlE
Put the js code in your file. You can have as many levels as you want. Explaining:
<select name="level1"><!--this is the "main" select-->
<option value="level2A">Level2A</option>
<option value="level2A">Level2B</option>
</select>
<select name="level2A"><!--this shows when the user selects the option with name ""level2A"-->
<option value="level3"></option>
</select>
<select name="level2B">
<!--options...-->
</select>
<select name="level3"></select>

redirect to different URL with same form

i am new to PHP and trying to arrive with similar functionality given in URL.
i have a form with four select options, result will be retrived when last option selected.
my current code is :
{
$result = mysql_query($query,$con);
if(!$result)
echo mysql_error();
$option = "";
while($row = mysql_fetch_assoc($result)) {
$option .= '<option value = "'.str_replace(' ', '_', $row['bankname']).'">'.$row['bankname'].'</option>';
}
str_replace(' ', '_', $row['bankname'])
?>
<form method = "POST" action = "">
<select name = "bank" onChange="document.location.href=bank[selectedIndex].value">
<?php echo $option; ?>
</select>
</form>
}
Probably i am asking very high level question, but please help.
Regards,
Anitha
You can send the first time using ajax, and whem the ajax is sucess you can change the submit the form again returning true.
If I got the question right, you are not looking for loading options into select box, but trying to look for a solution where the last select box have values:
<select id = 'finalSelect'>
<option value='http://aaaa.com'>A<option>
<option value='http://bbbb.com'>B<option>
<option value='http://cccc.com'>C<option>
</select>
and based on the user selection your page should redirect to aaaa.com, bbbb.com or cccc.com.
If I am right about your requirement, all you have to do is:
<select id = 'finalSelect' ONCHANGE="location = this.options[this.selectedIndex].value;>
<option value='http://aaaa.com'>A<option>
<option value='http://bbbb.com'>B<option>
<option value='http://cccc.com'>C<option>
</select>

Categories