change active state of flipswitch jquery mobile - javascript

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.

Related

Ajax onClick Safari iOS

I have a custom WordPress plugin that uses a Javascript ajax onClick function to make a clickable element that rondomly selects an item from a dropdown list and then opens that selection in a new tab.
The code works like a dream on every desktop and mobile browser except Safari on iOS.
In Safari on iOS if you click the random button it succeeds in randomly selecting an option from the select list and shows the loading animation but it fails to load the new page from the selection.
It seems that this bug is similar to other safari only ajax onClick bugs that have been discussed at length since the early days of iOS. Except that I have yet to find a workaround to this particular implementation.
I'm including code for both the random button where the bug is found and the select list as, based on my research to date, it may be the interaction of these two elements that is causing the bug on Safari.
Any thoughts?
(The following code has been sanitized to protect my client)
PHP in WordPress plugin
<div ><a href="javascript:;" id="randoms" class="tooltip">
<span class="tooltiptext" style="background : grey; opacity : 0.5;">Random</span>
</a></div>
<div class="select_able">
<div class="ruler"></div>
<img src="<?php echo CLIENT_WEBSITE_URL; ?>public/image/widget-background.jpg" alt="Widget">
<select name="person_profile" id="person_id">
<option value="0" >Search</option>
<?php if(!empty($search_person)): ?>
<?php foreach($search_person as $search_person): ?>
<option value="<?php echo $search_person->entity_id; ?>"> <?php echo $search_person->person_name ?> </option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
HTML Output
<div><a href="javascript:;" id="randoms" class="tooltip">
<span class="tooltiptext" style="background : grey; opacity : 0.5;">Random</span>
</a></div>
<div class="select_able">
<div class="ruler"></div>
<img src="https://image.url" alt="Widget" data-pagespeed-url-hash="123456" onload="pagespeed.CriticalImages.checkImageForCriticality(this);">
<select name="person_profile" id="person_id">
<option value="0">Search</option>
<!-- List with hundreds of options -->
</select>
</div>
Javascript in WordPress plugin
$("#randoms").on("click", function() {
$.ajax({
type: "post",
dataType: "json",
url: ajaxUrl,
data: {
action: "random_client"
},
beforeSend: function() {
$(".loader").removeClass("hide");
},
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
success: function(resp) {
$(".loader").addClass("hide");
if (resp.code == 200) {
var data = {
id: resp.entity_id,
text: resp.person_name
};
var newOption = new Option(data.text, data.id, true, true);
$("#person_id")
.append(newOption)
.trigger("change");
var pers_rating = $.trim($(".person_rating").val());
if (pers_rating < 0) {
$(".ruler").addClass("hide");
}
}
}
});
});
$(".new-tab-random").on("click", function() {
$.ajax({
type: "post",
dataType: "json",
url: ajaxUrl,
data: {
action: "random_client"
},
beforeSend: function() {
$(".loader").removeClass("hide");
},
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
success: function(resp) {
$(".loader").addClass("hide");
if (resp.code == 200) {
fetch_profile_tab(resp.entity_id, resp.person_name);
}
}
});
});
$(".loader").removeClass("hide");
$(document).on("click", ".lower", function() {
$("#designator").val("lower");
var designator = $("#designator").val();
feed_back(designator);
});
$(document).on("click", ".higher", function() {
$("#designator").val("higher");
var designator = $("#designator").val();
feed_back(designator);
});
function fetch_profile_tab(
person_new_tab_id = 0,
slug_name_new_tab = 0
) {
var person_id;
var slug_name;
if (person_new_tab_id != 0) {
person_id = person_new_tab_id;
slug_name = string_to_slug(slug_name_new_tab);
} else {
person_id = $("#person_id").val();
var data = $("#person_id").select2("data");
slug_name = string_to_slug(data[0].text);
}
if (window.location.hostname == "localhost") {
var new_link =
window.location.origin +
"/website/result/" +
person_id;
} else {
var new_link =
window.location.origin + "/result/" + person_id;
}
window.open(new_link, "_blank");
}
What if you try to replace href="javascript:;" with href="#" in your <a> tag?

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>

How to get input tag and option tag separately and load inside div and inside select

I have empty <div> and <select> want to load label and input tags inside div and option inside select after ajax response. How would i do that?
here is the response
i want to separately extract label and input for <div> & extract option for <select>.
here is my code:
<div class="form-group">
<select id="student" name="student" class="form-control" onchange="getName(this.value)">
</select>
</div>
<div name="state" id="state">
</div>
<script>
function getschool() {
var st = $('#school option:selected').val();
$.ajax({
type: "POST",
url: '<?php echo base_url();?>Choice/student',
type: 'POST',
data: {
// fname: fname
st:st
},
dataType: 'text',
success: function(data) {
alert(data);
//alert(data[0].id);
// for(k in data){
// alert(data[k].id);
$('#student').html(data);
//$('#state').html(data.input);
$('#state').html(data);
// }
//$('body').html(data);
// console.log(data);
//alert(data);
//alert("Succesful ");
//location.reload(false);
//window.location.href = "http://localhost:8080/choicelaunch/Choice/order_fullmenu";
}
});
}
</script>
After doing so i get every thing inside div like:
Plus i am getting this reponse from my Codeigniter controller:
public function student()
{
$sch= $this->input->post('st');
$swt=$this->data['school'] = $this->catering_model->selstu($sch);
//echo(json_encode( $swt));
if(!empty($swt))
{
if(($sch == "1"))
{
echo ('<label class="checkbox-inline">
<input type="checkbox" id="offer1" name="offer" value="Monday">Monday
</label>');
}
foreach($swt as $in)
{
echo ('<option value="'.$in->id.'" select="select">'.$in->fname.' '.'</option>');
}
}
//var_dump($data['school']);
}
i dnt knw why. i only need checkbox not non-checkbox.
You could use filter():
$('#student').html($(data).filter('option'));
$('#state').html($(data).filter('label'));
I know it's little bit tricky. But, try this one.
Why don't you try to add a separator between div content and select content on controller. Here what I mean:
public function student()
{
$sch= $this->input->post('st');
$swt=$this->data['school'] = $this->catering_model->selstu($sch);
//echo(json_encode( $swt));
if(!empty($swt))
{
if(($sch == "1"))
{
echo ('<label class="checkbox-inline">
<input type="checkbox" id="offer1" name="offer" value="Monday">Monday
</label>');
}
echo "##"; //the separator
foreach($swt as $in)
{
echo ('<option value="'.$in->id.'" select="select">'.$in->fname.' '.'</option>');
}
Then, after success receive data, try to split it.
success: function(data) {
alert(data);
var res = data.split("##");
$('#student').html(res[0]);
$('#state').html(res[1]);
}

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

Categories

Resources