Reload a portion of the webpage using ajax? - javascript

Controller (called for loading a specific board):
public function getBoard()
{
$role = $this->session->userdata('role');
$user_id = $this->session->userdata('user_id');
$board_id = $this->input->post('board_id');
if ($this->session->flashdata('first_board_id') !== null)
{
$board_id = $this->session->flashdata('first_board_id');
}
$data['board_id'] = $board_id;
$data['board_name'] = $this->Board_model->getBoardName($board_id);
$data['columnData'] = $this->Column_model->getColumns($board_id);
$data['rowData'] = $this->Row_model->getRows($board_id);
$data['tasks'] = $this->Task_model->getTasks($board_id);
$data['pendingSubtasks'] = $this->Task_model->countPendingSubtasks($data['tasks']);
$data['finishedSubtasks'] = $this->Task_model->countFinishedSubtasks($data['tasks']);
$data['boards'] = $this->Board_model->getBoards($role, $user_id);
$this->load->view('templates/header',$data);
$this->load->view('main_kanban', $data);
$this->load->view('templates/footer',$data);
}
From templates/header.php
<li class="custom-holder select-board">
<label class="boostrap-select-label">BOARD:</label>
<select class="selectpicker" title="CHOOSE BOARD" id='board_selection'>
<?php
if (count($boards) > 0) {
foreach ($boards as $b) {?>
<option value="<?php echo $b->id; ?>"><?php echo $b->name; ?></option>
<?php
}
}
?>
</select>
</li>
From func_board.js (Loaded in the footer; called when dropdown selection is changed)
$('.select-board').on('change', '#board_selection', function() {
console.log('Changed board selection.');
var selected_board = $('#board_selection option:selected').val();
$.ajax({
type: 'POST',
url: base_url + 'home', //configured this in routes.php
data: { 'board_id' : selected_board },
success: function(msg) {
if (msg != 'failed')
{
console.log('Loading board success!');
$('.mainboard').load(base_url + 'home', {
'board_id' : selected_board
}); //mainboard is the parent div in main_kanban
//that basically contains all the elements for the board
}
else
{
console.log('Error >> ' + msg);
}
},
error: function(xhr, error, errorThrown) {
console.log(xhr.responseText);
console.log(error);
}
});
});
I have a select or dropdown menu from which you can choose which board to view. However, as hinted by my code above, I'm using templates. Basically, when you click on a different board from the dropdown, it's supposed to load that board. The html for the board is in main_kanban. I don't think I can use redirect since there is data that I need to pass with the view.
I've tried jQuery's load() but I'm having problems with it. (There's a New Task button in each <td> as I'm using a table for the boards. When that New Task modal opens there is an option to select the To Date and From Date. When I use load() the date time picker doesn't show up. I'm using several scripts for the customization which are loaded in the templates/footer.php I have other select menus in the modal too. When ajax is finished those menus are empty.)
How can I achieve this?

Use the completion callback of load() to initialize plugins like date pickers
var loadData = {'board_id' : selected_board};
$('.mainboard').load(base_url + 'home', loadData , function(){
// new html exists now .. initialize plugins or event listeners
$(this).find('.datepickerClass').datepicker({ /* options */})
});

Related

Close Select2 Dropdown after clicking on X to Clear

I'm trying to get a Select2 Dropdown to close after clicking on X to clear it because it stays open. I'm currently using the .on('select2:unselect') function to trigger it when the button is clicked to clear the selections but I either get an error or it just doesn't do anything.
Error
TypeError: Cannot read properties of null (reading 'query')
Select2 HTML
<select class="softwareReleaseItem" name="softwareReleaseItem" id="softwareReleaseItem" data-control="select2">
<option></option>
<?php
asort($softwaredb);
foreach ($softwareDB as $software) {
echo "<option value=\"" . $software['Guid'] . "\">" . strtoupper($software['Name']) . "</option>";
}
?>
</select>
<div id="sRI"></div>
Javascript
$('.softwareReleaseItem').on('select2:select', function(e) {
var sri_data = e.params.data;
var sri_callType = 'softwareReleaseItem';
//console.log(sri_data);
$("#sRI").show();
$.ajax({
type: "POST",
url: "dist/php/ajax/ajax_getItemsByName.php",
data: {
sri_id: sri_data['id'],
sri_text: sri_data['text'],
sri_call: sri_callType
},
success: function(data) {
$('#sRI').html(data);
}
});
}).on('select2:unselect', function(e) {
$("#sRI").hide();
closeSelect();
});
All my attempts to close it ->
function closeSelect() {
//$('.softwareReleaseItem').trigger('select2:close');
//$(".softwareReleaseItem").focusout();
$(".softwareReleaseItem").select2().trigger('close');
//$("#softwareReleaseItem").select2("select2:close");
//$("#select2-drop-mask").click();
//$(document.body).trigger('mousedown');
//$('body').trigger('mousedown');
//$('.select2-hidden-accessible').select2('select2:close');
//$(".softwareReleaseItem").select2("select2:close");
};
UPDATE:
So far this is the only working solution I have come up with that works
I just simulate a mouseclick on a hidden div.
.on('select2:unselect', function(e) {
$("#sRI").hide();
$(".softwareReleaseItem").trigger("reset").trigger("change")
document.getElementById('#sRI')
.dispatchEvent(new MouseEvent('click', {
shiftKey: true
}))
});

PHP & Jquery Creating Multiple Dynamic Select Lists with Probable Conditional Behaviors

The title is a bit much so let me break this down. What I am trying to accomplish here is selecting an option from select 1 (onChange) retrieves the prebuilt select for select 2 from an external php script. Same for 2 -> 3 and 3 -> 4. I know how to do this, perhaps not efficiently, but, I can get it done.
The problem I crashed into was, the 3rd select is not always an option. This is a problem because the 4th select is the end result I need. The second select in this case will give me the ID's to create select 4 instead. Make sense?
HTML:
<td>
<select name="collectionID" id="bpCollection" class="form-control">
<option value="">Select Collection</option>
<?PHP echo optionsFromDatabase();?>
</select>
</td>
<td><select name="bpClass"id="bpClass" class="form-control"></select></td>
<td><select name="bpFaction"id="bpFaction" class="form-control"></select></td>
<td><select name="bpID"id="bpID" class="form-control"></select></td>
JQUERY :
<script>
$("#bpCollection").change(function() {
$("#bpClass").load("inc/api/auto.php?type=class&choice=" + $("#bpCollection").val());
});
$("#bpClass").change(function() {
$("#bpFaction").load("inc/api/auto.php?type=faction&choice=" + $("#bpClass").val());
});
$("#bpFaction").change(function() {
$("#bpID").load("inc/api/auto.php?type=blueprint&choice=" + $("#bpFaction").val());
});
</script>
As Previously stated this does work perfectly.
Auto.php
$group = $db->escape($_GET['type']);
$choice = $db->escape($_GET['choice']);
$list = '';
switch ($group) {
case 'blueprint':
$db->where('marketGroupID',$choice);
$db->orderBy('typeName','ASC');
$map = $db->get('invTypes');
foreach ( $map as $val ) {
$list .= '<option value="'.$val['typeID'].'">'.$val['typeName'].'</option>';
}
break;
default:
$db->where('parentGroupID',$choice);
$db->orderBy('marketGroupName','ASC');
$map = $db->get('invmarketgroups');
foreach ( $map as $val ) {
$list .= '<option value="'.$val['marketGroupID'].'">'.$val['marketGroupName'].'</option>';
}
}
echo $list;
This works perfectly, except. #bpFaction is not always an option where it can't populate since #bpClass holds the ID options for #bpID. I can select the #bpClass select option and will need to jump straight to #bpID. I think a good part of the problem I have is that I don't visualize the code needed on either end to make this work properly. Do I need to make the jquery do this, do I need to change auto.php, or both?
Do you have any thoughts on how best to do it?
I recommended using Ajax with JSON above. Here I will go more in-depth of how to do that. I will be writing this sample using States, Cities, and Jurisdictions as the select box types.
We will be using one controller in PHP for all select boxes (just like yours above) except we will be re-writing it to return JSON instead. I don't know what framework you are using so I just wrote a sample of what it would look like:
// if no state passed in, return list
if(!$stateId = $request->get('state')) {
$loadedStatesFromDb = ...; // states loaded from DB
// if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
$states = [];
foreach($loadedStatesFromDb as $state) {
$states[$state->getId()] = $state->getName();
}
// your framework may require a different method of passing json data
return json_encode([
'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
'states' => $states
]);
}
// if no city passed in, load cities for the selected state
if(!$cityId = $request->get('city')) {
$loadedCitiesFromDb = ...; // cities loaded from DB for $stateId
// if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
$cities = [];
foreach($loadedCitiesFromDb as $city) {
$cities[$city->getId()] = $city->getName();
}
// your framework may require a different method of passing json data
return json_encode([
'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
'cities' => $cities
]);
}
// if no jurisdiction selected, load list
if(!$jurisdictionId = $request->get('jurisdiction')) {
$loadedJurisdictionsFromDb = ...; // jurisdictions loaded from DB for $cityId
// if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
$jurisdictions = [];
foreach($loadedJurisdictionsFromDb as $jurisdiction) {
$jurisdictions[$jurisdiction->getId()] = $jurisdiction->getName();
}
// your framework may require a different method of passing json data
return json_encode([
'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
'jurisdictions' => $jurisdictions
]);
}
And this is what your view would sort of look like (untested, but generally how you would do it):
<select name="state" id="state-select"></select>
<select name="city" id="city-select"></select>
<select name="jurisdiction" id="jurisdiction-select"></select>
<script type="text/javascript">
function _load_select_boxes(e) {
if(
$("#state-select").val() && $("#city-select").val() && $("jurisdiction-select").val() && // if we have an item selected in all select boxes
typeof e !== 'undefined' && e.target.id == 'jurisdiction-select' // if the select box that triggered the event is the last one
) {
_select_box_completed('jurisdiction', $("jurisdiction-select").val());
}
$.ajax({
url: '/where/you/load/select/boxes',
type: 'POST',
data: $("#state-select, #city-select, #jurisdiction-select").serialize(),
dataType: 'json', // what server will return
success: function (data) {
if (data.result === 'ok') {
if(typeof data.states !== 'undefined') {
// no need to reset options for the first select (unless we will be re-loading it without selecting a value)
// set select box options using the array of cities
for(var stateId in data.states) {
var stateName = data.states[stateId];
$("#city-select").append('<option value="' + stateId + '">' + stateName + '</option>')
}
} else if(typeof data.cities !== 'undefined') {
// reset select box
$('#city-select').find('option').remove();
// set select box options using the array of cities
for(var cityId in data.cities) {
var cityName = data.cities[cityId];
$("#city-select").append('<option value="' + cityId + '">' + cityName + '</option>')
}
} else if(typeof data.jurisdictions !== 'undefined') {
if(!data.jurisdictions.length) {
// no jurisdictions returned so we reached end
_select_box_completed('city', $("#city-select").val());
} else {
// reset select box
$('#jurisdiction-select').find('option').remove();
// set select box options using the array of jurisdictions
for(var jurisdictionId in data.jurisdictions) {
var jurisdictionName = data.jurisdictions[jurisdictionId];
$("#jurisdiction-select").append('<option value="' + jurisdictionId + '">' + jurisdictionName + '</option>')
}
}
}
} else {
// handle error for app
}
},
error: function (jqXHR, textStatus, errorThrown) {
// handle error for app
}
});
}
function _select_box_completed(type, id) {
// fired when we have selected as far as we can go
}
$(function(){
// this runs when page finishes loading, so we can load in the defaults and set events on the select boxes
$("#state-select, #city-select, #jurisdiction-select").on('change', function(e){
_load_select_boxes(e);
});
_load_select_boxes();
});
</script>
The simplest way to do this without changing much code is make your switch a function, build in a condition and call it again with changed parameters if that condition is met.
$list= myswitch($db, $group, $choice);
function myswitch($db, $group, $choice){
$list='';
switch ($group) {
case 'blueprint':
...
break;
default:
$db->where('parentGroupID',$choice);
$db->orderBy('marketGroupName','ASC');
$map = $db->get('invmarketgroups');
//*** CONDITION HERE ***
//IF condition met: set new variables
if($choice === ... && $map === ...)){
$group="xxx";
$choice="yyy";
//call the function again with new values
$list = myswitch($db, $group, $choice);
}
//ELSE create normal list
else{
foreach ( $map as $val ) {
$list.= ....
}
}
return list;
}

Running SQL query after AJAX completes

I currently have 2 html dropdowns. Once I select from one, it filters the data in my HTML table and displays data based on the selection. I can also make changes to each row and, by clicking a save button, run an update query that updates the table. After, running that update, I want it to re-run the same query that was used to filter the results based on the dropdown selection so you can see the most up-to-date results of what you selected after clicking save and running the update statement. Right now, you can see that I have window.location.href = window.location.href; under the success callback in my AJAX function, but that reloads the entire page and runs the default query that displays on page load, so that doesn't work for me.
All of my queries that filter the table results after a dropdown selection are in my dropdown-display.php page that is called once I select something.
HTML Dropdowns:
<form name="testForm" action="">
<select id="collector">
<option value="" selected="selected" disabled="disabled">Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date">
<option value="" selected="selected" disabled="disabled">Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
</form>
JavaScript (index.js):
$(document).ready(function () {
$('.save').click(function (event) {
var $row = $(this).parents('tr');
var acct = $row.find('td[name="account"]').text();
var date = $row.find('td[name="date"]').text();
var checked = $row.find('input[name="selected"]').is(':checked');
var currency = $row.find('input[name="currency"]').val();
var datepicker = $row.find('input[name="datepicker"]').val();
var notes = $row.find('textarea[name="notes"]').val();
var paid = $row.find('input[name="paid"]').is(':checked');
var request = $.ajax({
type: "POST",
url: "update.php",
data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
success: function(data){
alert('Row successfully saved');
//window.location.href = window.location.href;
}
});
});
});
And this is my javascript that is run in my head tag in my main index.php page:
function showUser(collector,date) {
$('#billing_table').hide();
if (collector == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('billing_table');
sorttable.makeSortable(newTableObject);
}
}
$.ajax(
"dropdown-display.php"
,{
data:{
q:collector,
data:date||undefined
}
}
).then(
function(responseText){
$("#txtHint").html(responseText);
sorttable.makeSortable($('#billing_table')[0]);
}
,function(error){
console.warn("something went wrong:",error);
debugger;
}
)
}
}
$(document).ready(function(){
$("#collector, #date").change(function(e){
showUser(
$("#collector").val()
,$("#date").val()
);
});
$("#collector").change(function(e){
$.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
$("#date .choice").hide();
$.each(data, function(key,row) {
$("#date option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
});
You can bind the event after successful response of ajax like that:
$(document).ready(function () {
$('.save').click(function (event) {
var $row = $(this).parents('tr');
var acct = $row.find('td[name="account"]').text();
var date = $row.find('td[name="date"]').text();
var checked = $row.find('input[name="selected"]').is(':checked');
var currency = $row.find('input[name="currency"]').val();
var datepicker = $row.find('input[name="datepicker"]').val();
var notes = $row.find('textarea[name="notes"]').val();
var paid = $row.find('input[name="paid"]').is(':checked');
var request = $.ajax({
type: "POST",
url: "update.php",
data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
success: function(data){
alert('Row successfully saved');
$('#chdir select').bind('change', getDirs); // this is use for example like change of select
}
});
});
});
function getDirs(){
//any functionality you want
}
You need to send the filters (in your Ajax call) as parameters to the page that gets the result. You could name them collector_sel and date_sel.
Once the update has been completed, you must return these parameters.
For example, you could return them in the same GET string you use for window.location. href.
window. location. href = "index.php?collector_sel=abc&date_sel=bcd"
Then on the page you initially load it compares the filter values to select them again.
<form name="testForm" action="">
<select id="collector">
<option value="">Collector Name</option>
<?php
$selected = "";
foreach($collect->fetchAll() as $name) {
if (isset($collect_sel)){
if (strpos($_GET['collect_val'],$name['Collector Name'])==0)
$selected = "selected";
}
} ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"
selected="<?php echo $selected; ?>" ><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
// ....
</form>

Populate Dropdown based on another Dropdown Using Ajax, jQuery and Codeigniter

I just wanna ask how to populate a dropdown based on another dropdown's value.
When I select a Campaign, it will show the names of the people that are in that Campaign in another dropdown but the value must be the id of the name.
Here is my Model
function get_agents($campaign_id)
{
$campaign_id1 = mysqli_real_escape_string($this->db->conn_id,trim($campaign_id));
$query = $this->db->query("SELECT tbl_employee.emp_id, CONCAT(tbl_applicant.fname, ' ', tbl_applicant.lname) AS fullname FROM tbl_applicant INNER JOIN tbl_employee ON tbl_employee.apid=tbl_applicant.apid INNER JOIN tbl_account ON tbl_employee.acc_id=tbl_account.acc_id WHERE tbl_account.acc_id='".$campaign_id1."'");
return $query->result();
}
Here is my Controller
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$this->KudosModel->get_agents($campaign_id);
echo $result;
}
Here is my AJAX
$('#addCampaign').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign').val(),
url : 'controller/method',
success : function(data){
$('#anyname').val(data);
}
});
}); //I dont know what to do here
Thanks in advance guys!
I think you need some manipulation in controller like-
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$employees = $this->KudosModel->get_agents($campaign_id);
/*
foreach($employees as $employee)
{
echo "<option value='".$employee->emp_id."'>".$employee->fullname."</option>"
}*/
// for json
$employeesList = [];
foreach($employees as $employee)
{
array_push($employeeList,array('emp_id'=>$employee->emp_id,'fullnme'=>$employee->fullname));
}
echo json_encode($employeeList, JSON_FORCE_OBJECT);
}
now in ajax success function-
success : function(data){
// anyname should be the id of the dropdown
// $('#anyname').append(data);
// for json
$json = JSON.parse(data);
// empty your dropdown
$('#dropdownId').empty();
$.each($json,function(key,value){
$('#dropdownId').append('<option value="'+key+'">'+value+'</option>');
})
}
You can simply iterate through your data and add options to your second Select
$('#addCampaign').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign').val(),
url : 'controller/method',
success : function(data){
//data returns your name, iterate through it and add the name to another select
$.each(data, function($index, $value) {
$('#secondSelect').append($("<option></option>").val($value.id).html($value.name));
});
}
});
});
One thing, if you need a listener on your second <select> lets say on('click'), you need to add it back once you populated it. If not, Jquery won't recognize the new values.
Edit
Also, as #PersyJack stated, you need to asign the variable $result to something if you want to return it.
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$result = $this->KudosModel->get_agents($campaign_id);
echo $result;
}

How to create/find right ID in multiple Form elements of same type $ajax function with jQuery Mobile?

I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();

Categories

Resources