Running SQL query after AJAX completes - javascript

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>

Related

Getting updated input value for further update in jQuery

I use an Ajax form (with JQuery Validation Plugin) on my site. It works except for the following problem: if I enter something in a text field and then click on the send button, the value is updated. With each next update, however, the old value is always used. I already understand that I may have to work with .on or .keyup, but I understand how to properly integrate it into the code, after the click or outside ...
Update:
I have several fields in the form. Here is simplified code. I also noticed that after the first update of the form, no fields can be updated with newly entered values. All values remain old.
HTML:
<form id="org-684" class="org">
<input class="org-name" type="text" name="name" value="" required>
<button type="submit" class="updateOrg">Update</button>
</form>
JS:
$(document).ready(function(){
$('.updateOrg').click(function() {
var id = $(this).closest(".org").attr("id");
id = id.split('-');
id = id[1];
var org_id_attr = "#org-"+id;
var org_name = $(org_id_attr).find(".org-name").val();
$(org_id_attr).validate({
submitHandler: function() {
$.ajax({
type: "POST",
url: "update.php",
data: ({
id: id,
org_name: org_name
}),
success: function(response){
var result = jQuery.parseJSON(response);
$(org_id_attr).find(".org-name").val(result.name);
},
error: function() {
},
cache: false
});
return false;
}
});
});
})
PHP:
<?php
$orgId = $_POST['id'];
$orgName = $_POST['org_name'];
$select = "
SELECT
name
FROM
org
WHERE
id = $orgId
";
$result = $mysqli->query($select);
$row = $result->fetch_row();
$res = array(
'name' => $row[0]
);
echo json_encode($res);
I solved the problem. You just have to put the variables from the form behind the "SubmitHandler".
$(org_id_attr).validate({
submitHandler: function() {
var org_name = $(org_id_attr).find(".org-name").val();
$.ajax({
type: "POST",

How to update values of dropdown using another dropdown with AJAX nodejs?

I have two dropdowns. One is for selecting the Main category, the second for selecting the sub category.
I want to be able to populate the sub category based on the Main category selected.
What I have tried so far is using JQUERY and AJAX to listen to change in the value of the dropdown using jquery and send an ajax request to the relevant route.
View
<div class="form-control">
<label for="category">Category</label>
<select name="category" id="category">
<option value='Men'>Men</option>
<option value='Women'>Women</option>
<option value='Sports'>Sports</option>
</select>
</div>
<div class="form-control">
<label for="subcategory">Sub Category</label>
<select id="subcategory" name="subcategory">
</select>
</div>
AJAX and JQUERY
$("#category").on("change", function () {
$("#subcategory").empty();
showValue($(this).val());
});
var data = {};
function showValue(val) {
console.log(val);
data.category = val;
$.ajax({
url: "/admin/update-list",
type: "POST",
data: data,
success: function(result) {
updateDOM(result);
},
error: function (err) {
console.log(err);
}
});
};
var updateDOM = function (result) {
var data = result.data;
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
$("#subcategory").append("<option>"+ data[i] +"</option>");
};
};
/admin/update-list Route
router.post('/update-list', (req,res,next) => {
let data = [];
let category = req.body.category;
console.log('From the ajax call, category is' + category);
if(category = "Men") {
data = [
'Sneakers',
'Boots',
'High Heels',
'Litas',
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Women") {
data = [
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Sports") {
data = [
'Soccer Boots',
'Rugby Boots'
];
res.status(200).json({data});
res.end();
}
});
No matter what option I choose, the second dropdown returns the same data.
I would do this in PHP. Hopefully this conveys what you could adapt to your situation:
<select name="foo" >
</select>
ajax call
$.ajax({
type:'POST',
url:'your_code_page.php',
data:'param1='+variable,
success:function(html){
$('[name="foo"]').html(html);
}
});
PHP post back
echo "<option value=''>Please select a thing</option>"; <<outside loop
while ($row = sqlsrv_fetch_array($results)) {
$value = $row['value'];
$display = $row['display'];
//-display the result of the array
echo "<option value= " . $value . ">" . $display . "</option>"; << options returned in post
}

Return javascript output for option select

I'm working on these codes for awhile and need some help. Basically, I'm trying to get the result or output of the script and put it in between the option select as shown here:
<select class="form-control" name="property_list">
*insert output javascript here
</select>
Below is the complete script. Would this method be possible?
<script>
$(document).ready(function(){
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log('Done: ', responseData);
}).fail(function() {
console.log('Failed');
});
});
});
</script>
<div class="input-group mb-3">
<span class="input-group-addon gi data-gi-size gi-user-add"></span>
<select id="client-list" name="client-list">
<?php
$sql = "SELECT `id`, `email`
FROM `clients` ORDER BY `id` ASC";
$result = $DB_CON_C->query($sql);
if($result !== false) {
$data_row = '<option>New Client</option>' . "\n";
foreach($result as $row) {
$data_row .= '<option>' .$row['email'] . '</option>' . "\n";
}
}
unset($row);
echo $data_row;
?>
</select>
</div>
<select class="form-control" name="property_list">
*insert output javascript here
</select>
Use .html() to add returned data to the select, in your done function get select by name and add the data. This will work if the returned data is in the following format:
<option value="1">1</option>
<option value="2">2</option>
jQuery
$(document).ready(function () {
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log(responseData);
var data = JSON.parse(responseData);
$('select[name="property_list"]').html(data);
}).fail(function() {
console.log('Failed');
});
});
});
Loop through your response data and append options to your property list like so:
$(document).ready(function(){
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log('Done: ', responseData);
var data = JSON.parse(responseData); // Assuming response data is a JSON string
data.each(function(i, property) {
$("input[name=property_list]").append("<option />").text(property);
});
}).fail(function() {
console.log('Failed');
});
});
});
The options will need values as well so you can add that attribute to the options too:
$("input[name=property_list]").append("<option />").attr('value', property).text(property);

Reload a portion of the webpage using ajax?

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

change active state of flipswitch jquery mobile

I am trying to save the value of a flipswitch and after reload the webapp, the option with the same value as the status has should be active. I.e. if you select <option id="v2" value="0">OFF</option>, the cookie status have the value 0 and after reloading the page the flipswitch should show OFF.
Now after every reload the first option is always selected automatically and with that the value too. How can I change that?
my flipswitch:
<select id="status" name="status" data-role="flipswitch">
<option id="v1" value="1">ON</option>
<option id="v2" value="0">OFF</option>
</select>
my php snippet:
$t = time() + 60 * 60 * 24 * 1000;
setcookie("status", $_POST['status'], $t);
my own try:
function state () {
var statuse = <?php echo $_COOKIE['status']; ?>;
if (statuse == 0) {
$('#v2').addClass('ui-flipswitch-active');
}
if (statuse == 1) {
$('#v1').addClass('ui-flipswitch-active');
}
}
state();
function which calls php script:
function status () {
var stats = $("#status").val();
$.ajax({ url: 'status.php',
data: {status: stats},
type: 'post',
success: function(output) {
//alert(output);
}
});
}
status();
setInterval(function(){
status() // this will run after every 5 seconds
}, 5000);
I would try the following to load the proper switchstate on the pageload:
<select id="status" name="status" data-role="flipswitch" class="">
<option id="v1" value="1" <?php if (isset($_POST['status]') && $_POST['status'] == 1) echo 'class="ui-flipswitch-active"'; ?>>ON</option>
<option id="v2" value="0" <?php if (!isset($_POST['status]') || $_POST['status'] == 0) echo 'class="ui-flipswitch-active"'; ?>>OFF</option>
</select>
If you do this afterwards with javascript and the page loads slowly you get a 'flickering' since it takes a while to proces the javascript.
And the javascript:
$( "#status" ).change(function() {
var stats = $("#status").val();
$.ajax({ url: 'status.php',
data: {status: stats},
type: 'post',
success: function(output) {
//alert(output);
}
});
});
This way when the change event of the select is triggered, it starts the ajax query. Make sure the php script has the session_start(); Otherwise it probably won't work.

Categories

Resources