Codeigniter cascading dropdown with data from database - php

I'm need help in making a cascading dropdown that contains data from the database
I found a tutorial about this
and
I've tried this
Controller:
function ajax_call() {
if(!empty($_POST['table'])){
if ($_POST) {
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
}
My view:
$options = array(
'' => 'Select',
'category_one' => 'Category 1',
'category_two' => 'Category 2',
);
echo form_error('table');
echo "<p>Category:<br> ";
echo form_dropdown('table', $options, $this->input->post('table'), 'id="table"');
echo "</p><br>";
Script inside my view:
<script type="text/javascript">
$(document).ready(function(){
$('#table').change(function(){
var selTable = $(this).val(); // selected name from dropdown #table
$.ajax({
url: "ajax_call", // or "resources/ajax_call" - url to fetch the next dropdown
async: false,
type: "POST", // post
data: "table="+selTable, // variable send
dataType: "html", // return type
success: function(data) { // callback function
$('#year').html(data);
}
})
});
});
</script>
My Model:
function get_categories($table) {
$this->db->select('category2')->from($table);
$query = $this->db->get();
return $query->result();
}
My only problem with this is that the 2nd dropdown isn't visible on the page when loaded, and it would only appear when I select on the 1st dropdown.
How can i make set it to appear on the page without selecting on the 1st dropdown?
Can anyone help?

Ok I couldn't figure out how to do what i wanted. So instead i searched around the deep parts of the internet and found this little tutorial that was actually what i needed.
http://supundharmarathne.wordpress.com/2013/03/13/simple-ajax-drop-down-filtering-with-codeigniter/

This is happening because the ajax call to populate your table is only being triggered after the table changes $('#table').change(function(){...}). Try populating the table without waiting for such change; maybe inside $(document).ready(function(){...})

you added a completely obsolete if ($_POST) to your code. You are already checking if a variable in $_POST exists, hence it can never be empty after that. That caused your ELSE statement to relate to the second IF, not the first.
function ajax_call() {
if(!empty($_POST['table'])){
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
and that is why you should always indent your code correctly.

Related

Configuring a submit button using AJAX that checks for the value of an incremented variable

I'm trying to use AJAX properly to display an incremented value from a separate PHP file, but I'm a little iffy on the code. This is what it looks like:
$("#submit").click(function()
{
$.ajax({
type: 'POST',
url: 'info.php',
dataType: 'json',
data: {$_SESSION['totalCorrect'}
success: function()
{
if ($_SESSION['totalCorrect'] >= 8 && $_SESSION['totalCorrect'] <= 10)
{
window.location.replace('success.php');
}
else
{
window.location.replace('retake.php');
}
}
});
});
The value is stored in info.php and I'm trying to pull that value from that file, but I'm not sure on how to code the AJAX syntax. I'm certain this data: {$_SESSION['totalCorrect'} code isn't correct.
I can display the incremented value so I know, at least, that the variable is being incremented, but what I want to do now is to use that variable to check if they passed or not. If they did, then they get redirected to success.php. If not, then they get sent to retake.php.
EDIT: info.php
if (empty($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
foreach ($correctAns as $key => $answer)
{
if (!empty($_POST[$key]))
{
if ($_POST[$key] == $answer)
{
echo $correct[$index];
$_SESSION["totalCorrect"]++;
}
else if($_POST[$key] != $answer)
{
echo $incorrect[$index];
}
$_SESSION[$key] = true;
}
$index++;
};
You haven't posted all code, so I can only answer the one question.
First:
You're mixing php and javascript. You cannot access php variables in javascript unless you assign them as string to the output html or post them via an ajax - that's what you want to do.
So let's have a look at your jQuery-ajax:
$("#submit").click(function() {
$.ajax({
type: 'POST',
url: 'info.php',
// dataType: 'json', // I deactivated this to recieve a string only
// in data you should get the answers the user gave - another topic
data: {question1: '42', question2: 'Douglas'}, // that ',' was missing
// you'll get whatever you echo in info.php as 'result' as parameter
// in this success-callback-function (as result [json]):
success: function(result) {
// now you can check what the result is:
console.log(result); // make it visible to you for debugging
if (parseInt(result) >= 8 && parseInt(result) <= 10) {
console.log('redirecting to SUCCESS');
//window.location.replace('success.php'); // uncomment when working
}
else {
console.log('redirecting to RETAKE');
//window.location.replace('retake.php'); // uncomment when working
}
}
});
});
now lets adjust your info.php:
if (empty($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
foreach ($correctAns as $key => $answer)
{
// remember, that in $_POST you'll get everything you've put in 'data' before!
if (!empty($_POST[$key]))
{
if ($_POST[$key] == $answer) // better change to === if you know what data-types you'll get (and google the difference)
{
//echo $correct[$index]; // do not echo anything else but the result
$_SESSION["totalCorrect"]++;
}
else if($_POST[$key] != $answer)
{
//echo $incorrect[$index];
}
$_SESSION[$key] = true;
}
// $index++; // we don't need that, do we??
};
// here's the actual response/result:
// All you echo will be in 'result' of your ajax succes-callback-function
echo $_SESSION["totalCorrect"];
I don't know what your form looks like, how all the pages are set up, so I can't provide a complete code - also this would go far beyond the question.
But this should give you an idea of how getting are variable from php via ajax works.
Further Info:
Getting form data using JavaScript and sending data with Ajax
usefull stuff about json:
http://www.w3schools.com/js/js_json.asp
http://php.net/manual/en/function.json-encode.php

Ajax div to refresh on success not working

I have a DIV which contains how many likes fetching from Mysql database.
I click on button which says like and it will go through ajax function like(id1) with parameter.
Ajax use page likes.php and does all job adding to database. And it gives out JSON data as feedback with code zero if successful. And one if fails.
In success section ajax _js.code is one then its already liked. Thus shows us message. But my problem is I cannot refresh DIV likes when code is zero which is success. It either goes to top of the page instead of staying at DIV likes.
For information it also appends hash TAG at the end of URL.
Button line, I want like button which should work as facebook or other major app does. Without moving page on top. And update like button immediately when clicked.
My main page
<input type="checkbox" id="like" onclick="like(<?php echo $_SESSION["id"];?>);"/>
<div id="likes">
<?php
$like = 0;
$conditions = "WHERE id = $_SESSION[id]";
echo $total = $ll->get_likes($conditions); //displaying how many likes
?>
</div>
Ajax
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}
likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' = 0,
'message' = ""
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
change following in HTML and JS
<input type="checkbox" id="like" onclick="return like(<?php echo $_SESSION["id"];?>);"/>
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
return false;
}
#tashi,
There is a syntax error in likes.php. Use => operator when declaring arrays. The code should be as follows.
$return = array (
'code' => 0,
'message' => ""
);
if you want to display no of likes on success the change your code as follows
In likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' => 0,
'message' => "",
'likes_count' => $likes_count //get updated likes count from db
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
//here you do not need to send the like count
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
javascript code
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
$('#likes').html(_js.likes_count);//this will update your likes count
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}

return 2 or more variables separately from looped $.post()

I'm currently developing a textarea that whatever pasted after the push of button, it will be added to the database. Setting aside the database function aside.
I would like to achieve is:
Return the number of records that is successfully posted
Return the number of records which was not inserted telling its already a duplicate
jquery code
$(function(){
$('#sw').click(function(){
if($("#txta").val().length>0)
{
var h=confirm("Are you sure?");
if(h==true)
{
var fld=$("#txta").val().split('\n');
$.each(fld, function(){
$.post('up.php',
{ 'ldta': this.split('\t') },
function(data) {
$('#out').append(data);
}
);
});
alert('Upload completed');
}
else
alert("Cancelled");
}
else
{
alert("Textarea is empty.");
$('#out').html('');
}
});
});
php
$setsu = dbSetsuzoku();//connection string stored on separate file
$ldta=$_POST['ldta'];
$qSql='';
$dtHK=0;
$qSql="SELECT * FROM bet WHERE bet_id=".$ldta[0];
$stmt = $setsu->query($qSql);
$rwk=$stmt->rowCount();
if ($rwk==0)
{
//post to database code..
}
else
$lkaku.=$lines.", ";//$lines tell the line that was not added
if(!is_null($lkaku))
{
$hj='<table><tr style="background-color:#FF0000">';//displays the record that was not added table red in color..
foreach ($ldta as $key => $value) {
$hj.='<td>'.$value.'</td>';
}
$hj.='</tr></table>';
echo $hj;
}
else
{
$hj='<table border="1"><tr>';//displays the successfully added record/line
foreach ($ldta as $key => $value) {
$hj.='<td>'.$value.'</td>';
}
$hj.='</tr></table>';
echo $hj;
}
I noticed that whatever echoed on php it is get by the $.post() function on the part
function(data) {
$('#out').append(data);
}
Workarounds or ideas are welcome.
using array in your php code. And using return json.
$data['first'] = "firstdata";
$data['second'] = array(0=>"iam",1=>"cool");
echo json_encode($data);

retrieve data from .post

I'm using codeigniter, I had a problem to process a data using jQuery $.post function. I want to send a value such as subjectid to ajax_get_subject_credit function and retrieve another field within same database table. The result shows on another text field. Here is my code.
View:
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(data){
$('#chours' + id).val(data); });
This get a value from drop-down and I want to make a text field automatic populate from drop-down. #chours is a text field ID.
Controller:
function ajax_get_subject_credit($result)
{
$this->db->select('subjectid, subjectcredit');
$query = $this->db->get('ref_subject');
$result = $query->result_array();
$query->free_result();
$subjectid = array();
foreach($result as $row)
{
$result = $result + array($row['subjectid'] => $row['subjectcredit']);
}
return $result;
}
Modified In Controller
I also tried using this statement in controller for direct calling the field but still no success :
function ajax_get_subject_credit($subjectid)
{
$this->db->select('subjectid, subjectcredit');
$this->db->where('subjectid',$subjectid);
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
echo $credithour;
}
I am going to provide a general example here
in view file
$.post('<?php echo site_url("test/test"); ?>', {'id':1}, function(response){
if(response.success)
{
alert(response.message);
} else
{
alert('Something went wrong!!');
}
}, 'json');
in controller Test.php
function test()
{
$id = $this->input->post('id');
//do additional stuff
$result = 'i am coming right out of controller!! ';
echo json_encode(array('success' => true, 'message' => $result));
}
Dont use return to return value to AJAX. use echo
change this,
return $result;
to
echo $result;
If you want your method to return an array that the javascript can use to populate a dropdown, you probably don't want to return a string.
Try something like this:
function ajax_get_subject_credit()
{
$query = $this->db->select('subjectid, subjectcredit')->get('ref_subject');
$result = $query->result();
$out = array();
foreach($result as $row) {
$out[$row->subjectid] = $row->subject_credit;
}
header('Content-Type: application/json');
echo json_encode($out);
}
This will return a JSON array to your view, which your javascript method can use to populate the dropdown with values and labels.
Here is my Result:
In View :
function subjectid_change(id, subjectid){
//Set value
setValue(id, subjectid);
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(response){
if(response.success)
{
$('#chours' + id).val(response.value);
} else
{
alert('Something went wrong!!');
}
}, 'json'); }
And my controller :
function ajax_get_subject_credit()
{
//Get Post Value
$subjectid = $this->input->post('subjectid');
//Select subjectid,subjectcredit FROM
$this->db->select('subjectid, subjectcredit');
//Where subjectid = 'subjectid'
$this->db->where('subjectid',$subjectid);
//Database name
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
$result = $credithour;
echo json_encode(array('success' => true, 'value' => $result));
}
Thanks to everybody who helped me.

autocomplete value in textbox codeigniter

I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";

Categories