In my php code, I have two dropdowns which is the other one depends on the first one.
Here is the first dropdown:
<select class="form-control style" id="sel" >
<option style="color: black;" >Select...</option>
<?php foreach ($dtype as $row ) { ?>
<option style"color:black;" value="<?php echo $row['donations_type_id'];?>"> <?php echo $row['donations_type_name'];?></option>
<?php }?>
</select>
<tr>
<td>Available Donation:</td>
<td style="color: black; ">
<select name='avail' id='avail' class="form-control style" >
<option style="color:black;" value="">Select...</option>
</select>
</td>
</tr>
The second dropdown shows the data that corresponds whatever the user selects from the first dropdown.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
type: "POST",
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
success:function(data){
$("#avail").html(data);
}
});
});
});
</script>
In my controller:
public function showAvailable()
{
echo $id = $this->input->post('id', true);
$data['package'] = $this->Beneficiary_model->getDtype($id);
$output = null;
foreach ($data['package'] as $row ) {
$output.="<option value='".$row->package_id."'>".$row->package_name."</option>";
}
echo $output;
}
And in my model:
public function getDtype($id){
$this->db->select('package_id','package_name');
$this->db->from('package_table');
$this->db->where('package_type', $id);
$query = $this->db->get();
return $query->result();
}
When I tried to run the code and debug it through F12, it shows there that POST http://localhost:8999/samp/sampModule/showAvailable/2 404 (Not Found)
Why is it?
Can anyone help me with this error?
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
Take $(this) out of ajax object. It points now to ajax object itself. Try:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
**UPDATED**
Also, if the data is received from the server correctly but dropdown is still not rendered, the issue might be with the dataType property. There may be some problems with the response mime type, that cause the problem with the Intelligent Guess and data is treated as a json or xml string, so you can try to set it explicit:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
type: "POST",
dataType: 'html',
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
success:function(data){
$("#avail").html(data);
}
});
});
Related
I am getting a list of data from a mysql database which I add to a select list. When the user chooses an option I want to get the ID from the selected item, and use it to reference the index of my results array, like this:
echo $results[$id]['fruit'];
I retrieved the data from the database using $results = $stmt->fetchAll(PDO::FETCH_UNIQUE) so each id of the select list is the primary key of the record.
So I read that I can use AJAX to get the value of the selected item and send it back as a POST variable which I can then access in PHP. However when I go to print this variable I get nothing.
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //prints nothing
}
Here is my code:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
method: 'POST',
data: {'id' : recID},
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network
//the id will be used to reference a variable
//$results[$id]['fruit'] which I got
//from a database like this
//$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
//this value will set the text field myfruit
}
?>
</body>
</html>
I think you may try this
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
var fruitTect = $(this).text(); // for text i.e. Apple, Pear,...
// then now you can do ur ajax
$.ajax({
// Your Code For Post goes here
});
});
});
No need to call the onchange function in your html. Jquery will take care of the rest
Also your isset($_POST['id']) maybe isset($_POST['fruits'])
Rogers answer is right. and you miss the url parameter in your ajax call.
function listChange() {
var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
$.ajax({
url: '/myPhpFile.php',
method: 'POST',
data: {'id' : fruitValue},
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
if you realy want to call it in a single file you have to place the php code in top and do an exit after the condition is fullfilled..
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
you need to encode as ajax expect a json data
$results_array = array("Id" => $id):
$json=json_encode( $results_array );
header('Content-Type: application/json'); //tell the broswer JSON is coming
echo $json; //Just plain vanillat JSON output
do your things here an exit. Be aware that each echo "something" falsify the json data expected by the ajax call
exit();
}
?>
Try use this code in HMTL.
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange(obj) {
var recID = obj.value;
var recID = $("#fruits:selected").text();
$.ajax({
method: 'POST',
data: {'id' : recID},
url:'demo.php',(put url of php file and remove in this file make diffrent php file)
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange(this)">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network
//the id will be used to reference a variable
//$results[$id]['fruit'] which I got
//from a database like this
//$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
//this value will set the text field myfruit
}
?>
</body>
</html>
Ok I found a much simpler way of doing this. Just get Javascript to encode the value in the URL when the select is changed, then access it in PHP using GET.
Encoding the URL in Javascript:
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="ajax.php?id=" + fruitValue;
});
});
</script>
Echo the value in PHP:
if(isset($_GET['id']))
{
$id = $_GET['id'];
echo $id;
}
Print data via the different file.
Php return data send to another file and ajax response data print in html.
Action file
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //prints nothing
}
View file
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
url: 'action.php',
method: 'POST',
data: {'id' : recID},
dataType: "json",
success: function(response)
{
$('#your_id').html(response);
}
});
}
OR
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$("#your_id").html(recID);
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<div id="your_id"></div>
</body>
</html>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
url:'ajax.php'
method: 'POST',
data: {'id' : recID},
success: function(response)
{
console.log(response);
}
});
}
</script>
<?php
print_r($_POST);
?>
I was trying to get a dynamic dependent select list using AJAX, but unable to get the second list. Here is my code. gethint.php is working fine. I don't know where I am doing wrong.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"</script>
<script>
$(document).ready(function()
{
$('#brand').change(function()
{
var cid=$('#brand').val();
if(cid !=0)
{
$.ajax({
type:'post',
url: 'gethint.php',
data: {id:cid},
cache:false,
success: function(returndata)
{
$('#model').html(returndata);
}
});
}
})
})
</script>
</head>
<body>
<header>
<h1>Car Comparision </h1>
</header>
<form method="post" action="">
Brand 1:
<select id="brand" class="brand">
<?php
include "connect.php";
$query=$con->query("SELECT * FROM car");
while($brand=$query->fetch_assoc())
{
$brand_sel='<option value="'.$brand['id'].'"'.">".$brand['brand'].'</option>'."\n";
echo $brand_sel;
}
?>
</select>
Model 1:
<select id="model" class="model">
<option value="0">Please select a city</option>
<option></option>
</select>
<input type="submit" value="submit">
</form>
</body>
</html>
code for my gethint.php file
<?php
require ("connect.php");
$Query='SELECT * FROM model WHERE id='.$_POST['id'];
$sql=$con->query($Query) or die(mysql_error());
//print_r($Query);
while($row=$sql->fetch_array(MYSQLI_ASSOC)) {
?>
<option value="<?php echo $row["id"];?>"><?php echo $row['model_name'];?></option>
<?php
}
?>
Pls try this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('#brand').on('change', function() {
var cid=$('#brand').val();
if(cid !=0)
{
$.ajax({
type:'post',
url: 'gethint.php',
data: {id:cid},
cache:false,
success: function(returndata)
{
$('#model').html(returndata);
}
});
}
})
})
</script>
I would do it of a different a way:
<?php
require ("connect.php");
$Query='SELECT * FROM model WHERE id='.$_POST['id'];
$sql=$con->query($Query) or die(mysql_error());
//print_r($Query);
$elements = [];
while($row=$sql->fetch_array(MYSQLI_ASSOC)) {
$item = ["id" => $row['id'], "model_name" => $row['model_name']]
array_push($elements , $item)
}
echo $elements;
?>
I would send a associative array which contains all the items of your select. I would also modify your script to:
<script>
$(document).ready(function()
{
$('#brand').change(function()
{
var cid=$('#brand').val();
if(cid !=0)
{
$.ajax({
type:'post',
url: 'gethint.php',
data: {id:cid},
cache:false,
success: function(returndata)
{
returndata.each(data,function(){
$('#model').append("<option value="+data.id+">"+data.model_name+"</option>")
})
}
});
}
})
})
</script>
I worried about really you are passing the right value to the ajax.
See the data render for first select is:
$brand_sel='<option value="'.$brand['id'].'"'.">".$brand['brand'].'</option>'."\n";
It should be like this:
$brand_sel='<option value="'.$brand['id'].'">'.$brand['brand'].'</option>\n';
As per my above comment please let us know if any error showing related to jQuery or PHP.
Also, check the passing data to ajax is in correct format.
Hi I have a page that lets a user view results for a certain tournament and round
User will select sport then tournament is populated based on sport selection then user will select round which is populated based on tournament selection
When all is done user press Submit button which will look up the results for the result based on tournament and round selected
My code is working great:
mainPage.php
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
get_sport.php
<label>Sport :</label>
<form method="post">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
get_round.php
if($_POST['id'])
{
$id=$_POST['id'];
$sql="SELECT DISTINCT round FROM events WHERE tournament='$id'";
$result=mysql_query($sql);
?>
<option selected="selected">Select Round</option><?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['round'] ?>"><?php echo $row['round'] ?></option>
<?php
}
}
?>
EXAMPLE
Sport=>Football; Tournament=>EPL; Round=>5;
Assuming the above is selected when the user clicks submit the code will query select results from someTable Where sport='Football' AND...
My Problem
I get the data from the selectboxes by using a simple php isset() function
if(isset($_POST['submit'])){
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
:
:
Now my problem is when submit is clicked everything works BUT the form gets reloaded, which is what I don't want
Im looking for an AJAX equivalent of isset() or a way for the data to be submitted without the form reloading
Any ideas/help will greatly be appreciated
There is a different ways to avoid the reload of a submit form.
A solution would be to handle the submit action of the form and return 'false' ( Example here and here) or preventing the default action ( Example here )
You can also replace the input type submit for an input type button (or button), and handle the click button action instead of handling the form submit action. This would be an easy workaround to most of your 'form submit' problems, but is a worst solution in the semantic and valid code point of view.
You can do the form submission from JQuery as an AJAX request and do the resulting in the success.
jQuery(document).ready(function(){
jQuery('#form').submit(function(ev) {
$.ajax({
url : 'url',
type : 'POST',
dataType: 'json',
data : $('#form').serialiseArray(),
success : function( data ) {
// Populate the result
}
});
ev.preventDefault();
});
});
Initially load all the values in Sport: Dropdown
Then dynamically populate the Tournament and Round
// To Trigger Sport Change
$(".sport").change(function () {
var selected_sport = $(".sport").val();
var dataString = 'sport=' + selected_sport;
var urlAddress = "get_sport.php";
$.ajax({
url: urlAddress,
cache: false,
method: 'post',
data: dataString,
dataType: 'html',
success: function (result_data) {
$(".tournament").html(result_data);
// This will append the tournament drop-down dynamically
}
});
});
// To Trigger Tournament Change
$(".tournament").change(function () {
var selected_sport = $(".sport").val();
var selected_tournament = $(".tournament").val();
var dataString = 'sport=' + selected_sport + '&tournament=' + selected_tournament;
var urlAddress = "get_round.php";
$.ajax({
url: urlAddress,
cache: false,
method: 'post',
data: dataString,
dataType: 'html',
success: function (result_data) {
$(".round").html(result_data);
}
});
});
In your Corresponding PHP get_round.php
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
foreach ($row as $r) {
$round = $r['round'];
echo '<option value = "' . $round . '">' . $round . '</option>';
}
}
I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work
I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
Another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
View
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
Controller
function showCategory() {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
}
My category table contains: category_id, category_name, brand_id.
use ajax onchange. .in your view file..
<select name="brand" class="form-control" id="brand" required onchange="brand(this.value,'divid')">
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<div id="divid">
<select name="category" class="form-control" id="category" required>
<option>Select Category</option>
</select>
</div>
<script>
function brand(id,divid)
{
$.ajax({
type: "POST",
data: "pid="+id,
url: '<?php echo base_url(); ?>receiving/showCategory ?>',
success: function(html){
$('#'+divid).html(html);
}
});
}
</script>
in your function showCategory() :
<div id="divid">
<select name="category" class="form-control" id="category" required>
$brandid = $this->input->post('pid');
//you can pass this brand id to your query and echo the category in option value//
<option>//your result //</option>
</select>
</div>
You need to concat the all values in success function like
options += '<option>'+msg.category[i].category_name+'</option'>;
$('#category').html(options);
Look like your code is correct, but need to change a little bit in ajax request.
You need to parse the data return into parseJson first. The options variable in for loop should concatenate with += code. See example below:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var data = $.parseJSON(msg),options;
for(var i = 0; i<data.length; i++) {
options += '<option>'+data.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
In case you have a problem with this code, you should change variable in codeigniter part for the variable that hold the results. You can see my working code below as an example :
Js Code
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>controller/function_name',
dateType : 'json',
data : {depart_id : _depart_id.val()},
success : function(data){
var json_data = $.parseJSON(data),
options;
for(var i = 0; i<json_data.length; i++){
options += '<option value="'+json_data[i].destination_id+'">'+json_data[i].location+'</option>';
}
_destination_id.html(options);
}
});
Here is codeigniter code(php)
$destination = $this->custom_model->get_destination_distinct($table,$where);
echo json_encode($destination);