I'm using this setup to show if light is turned on or off:
http://www.jquery2dotnet.com/2012/11/jquery-light-switch-on-off-using-css3.html
How can i choose wich switch state to start?
As of now I have a lightvalue in my database, 1 = on 0 = off. I use sql to retrieve this value and load the appropriate light bulb.
But how would i do this with the switch? I don't have switch1 and switch2 so i can load the one i want based on lightvalue.
here is the code:
light.js
var lightVal = document.getElementById("light-bulb2");
function getLightValue(r) {
var lightValue;
$.ajax({
url: 'Database/checklight.php',
type: "POST",
data: {room: r},
success: function(data) {
data1 = JSON.parse(data);
$.each(data1, function(key, val) {
lightValue = val.light;
lightVal.style.opacity = lightValue;
});
},
async: false
});
}
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {light: val, room: room},
success: function(data) {
data2 = JSON.parse(data);
if (data2 < 1) {
alert("Not Updated");
}
},
async: false
});
}
light.php
<div id="temptre">
<div id="light-bulb" class="off ui-draggable" >
<div id="light-bulb2" style="opacity: 0">
<script src="JS/light.js">
</script>
</div></div>
<div class="cube-switch">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
</div>
<script>
getLightValue(<?php echo $_SESSION['sess_room']; ?>);
$('.cube-switch .switch').click(function() {
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({'opacity': '0'});
updateLight(0, <?php echo $_SESSION['sess_room']; ?>);
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({'opacity': '1'});
updateLight(1, <?php echo $_SESSION['sess_room']; ?>);
}
});
</script>
If you want to make switch work, then you need to trigger the click event, so that it can be switch on and off (based on value).
// call(trigger) click event on success
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {
light: val,
room: room
},
success: function (data) {
data2 = JSON.parse(data);
if (data == 1) {
$('.cube-switch .switch').trigger('click', [{
forceStart: true
}]);
} else {
$('.cube-switch .switch').trigger('click', [{
forceStart: false
}]);
}
},
async: false
});
}
// change your click event to handle the passed argument
$('.cube-switch .switch').click(function (e, data) {
if (typeof data !== 'undefined') {
if (data.forceStart) {
// remove the active class, so that it can add the active class later to match switch on
$('.cube-switch').removeClass('active');
} else {
$('.cube-switch').addClass('active')
}
}
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({
'opacity': '0'
});
updateLight(0, <? php echo $_SESSION['sess_room']; ?> );
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({
'opacity': '1'
});
updateLight(1, <? php echo $_SESSION['sess_room']; ?> );
}
});
JSFIDDLE: http://jsfiddle.net/4rkQZ/152/
I'm not very good with php, but give div.cube-switch a class of 'active' if it's on, and remove the inline opacity style (tidy up the php by all means!)
<div href="" class="cube-switch <?php if ($on) { echo ' active'; } ?>">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
<div id="light-bulb" class="off ui-draggable">
<div id="light-bulb2" <?php if (!$on) { echo 'style="opacity:0"'; } ?>></div>
</div>
Related
I have an image with the Coupon code in Front End/Homepage of my website but when I try to click that nothing happens and click is not working.
The Html is below
<a class="coupon_click text-no-decoration" href="javascript:void(0);" id="coupon_id_<?php echo $couponBanner->getId(); ?>">
jQuery code is below
jQuery(document).ready(function () {
jQuery('.coupon_click').click(function () {
console.log('here');
jQuery.ajax({
type: 'POST',
url: '<?php echo url_for('#blog_couponClicked') ?>',
data: {videoId: <?php echo $video_id ?>, couponId: <?php echo $couponBanner->getId(); ?>},
success: function (res) {
if (res) {
window.location.href = res;
}
}
});
});
});
Hi my advise don't mess the JQuery Code and PHP and make it clean as much as possible,
<a class="coupon_click text-no-decoration" href="javascript:void(0);" c-id="coupon_id_<?php echo $couponBanner->getId(); ?>" v-id="<?php echo $video_id ?>">Click</>
jQuery(document).ready(function() {
jQuery('.coupon_click').on('click', function () {
console.log('here');
var cid= jQuery(this).attr('c-id');
var vid= jQuery(this).attr('v-id');
dataCall(vid,cid);
})
function dataCall(vId, cId){
jQuery.ajax({
type: 'POST',
url: 'your_url',
data: {videoId: vId,couponId:cId},
success: function (res) {
//do whatever you want to do
},error:function(err){
console.log(err);
}
})
}
})
hope it's what u want
<a id="coupon" class="" href="javascript:void(0);" id="coupon_id">coupon</a>
$("document").ready(function()
{
$("#coupon").click(function ()
{
sendS();
});
});
function sendS()
{
var couponID="abc123";//anythg u like
var userID="hahaha#mail.com";
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{cID:couponID,uID:userID},
success: function(data)
{
alert(data)
},
error: function ()
{
alert("Error!");
}
});
}
i have a problem with filling dropdown data from ajax script.
here's my controller:
public function ajax_get_kota($idProv='')
{
$kota = $this->data['namaKota'] = $this->registrasi_model->get_nama_kota($idProv);
echo json_encode($kota);
}
here's my model:
public function get_nama_kota($idProv='')
{
$query = $this->db->query('SELECT id_kab, nama FROM kabupaten WHERE id_prov = '.$idProv.' ORDER BY nama ASC');
return $dropdowns = $query->result();
}
and view:
<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">
<?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
<div class="col-sm-3">
<?php
$atribut_kota = 'class="form-control dropKota"';
echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
set_validation_icon('Kota');
?>
</div>
<?php if (form_error('Kota')) : ?>
<div class="col-sm-9 col-sm-offset-3">
<?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
</div>
<?php endif ?>
<script>
$(document).ready(function () {
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
data: kota,
success: function(datas){
$(".dropKota").select2({
placeholder: "Pilih Kota",
data: datas
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
</div>
what i'm trying to do here is how to pass this data that im getting from ajax:
[{"id_kab":"5103","nama":"KAB. BADUNG"},{"id_kab":"5106","nama":"KAB. BANGLI"},{"id_kab":"5108","nama":"KAB. BULELENG"},{"id_kab":"5104","nama":"KAB. GIANYAR"},{"id_kab":"5101","nama":"KAB. JEMBRANA"},{"id_kab":"5107","nama":"KAB. KARANGASEM"},{"id_kab":"5105","nama":"KAB. KLUNGKUNG"},{"id_kab":"5102","nama":"KAB. TABANAN"},{"id_kab":"5171","nama":"KOTA DENPASAR"}]
into the dropdown dropKota. those data is dynamically generated when another dropdown value is changed.
current result:
select2 requires a specific format so it can be properly displayed in dropdown
var data = [{ id: 0, text: 'enhancement' } //something like this
how do i do this?
U have to do like this :
$.ajax({
url: url,
type: "POST",
async: false,
data: {id: id},
success: function(data) {
var data_array = $.parseJSON(data);
$.each(data_array.emp, function(key, value) {
$('#Your_drop_down_id').append($('<option>', {
value: key,
text: value,
}));
});
}
});
U have to parse the data(JSON to array) and then use $.each for looping all values.
Try this:
success: function(datas){
var data = JSON.parse(datas);
var options = '<select name="dd_name"><option>Select</option>';
for(i=0; i<data.length; i++)
{
options += '<option value="'+ data.col_name +'">'+ data.col_id +'</option>';
}
options += '</select>';
$('#div_id').html(options); // where #div_id is the id of a div in which this drop down is required.
},
Change $.ajax call as below
$.ajax({
url: baseUrl,
data: kota,
dataType: "JSON",
success: function(datas){
var s= document.getElementById('<Element Id>');
s.eampty();
$.each(datas, function(index, el) {
s.options[index]= new Option(index, el);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
dataType: "JSON", will respond output of ajax call in json format.
Replace <Element Id> with element id to which you want to add data.
Full Source
<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">
<?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
<div class="col-sm-3">
<?php
$atribut_kota = 'class="form-control dropKota"';
echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
set_validation_icon('Kota');
?>
</div>
<?php if (form_error('Kota')) : ?>
<div class="col-sm-9 col-sm-offset-3">
<?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
</div>
<?php endif ?>
<script>
$(document).ready(function () {
$(".dropKota").select2({
placeholder: "Pilih Kota"
});
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
data: kota,
dataType: "JSON",
success: function(datas){
var s= document.getElementById('<Element Id>');
s.eampty();
$.each(datas, function(index, el) {
s.options[index]= new Option(index, el);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
</div>
Finally, i found the solution after asking here and there, so here's the solution:
JS and select2 script:
<script>
$(document).ready(function () {
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
dataType: 'json',
success: function(datas){
//since select2 need a specific format u need to do this
var kota = $.map(datas, function (obj) {
obj.id = obj.id || obj.id_kab; // replace id_kab with your identifier
obj.text = obj.text || obj.nama // replace nama with your identifier
return obj;
});
$(".dropKota").select2({ //change dropKota into your element
placeholder: "Pilih Kota",
data: kota
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
I asked a question earlier today (jquery select2: error in getting data from php-mysql). However, I am trying to fix it and doing that now I am getting bit strange issue. I am not sure why it is happening like this.
Below is the JavaScript code.
<div class="form-group">
<label class="col-sm-4 control-label">Product Name</label>
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function(term) {
return {q: term};
},
results: function(data) {
return {results: data};
},
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
Here is the php code (fetch.php)
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
//$search='te';
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
select2 version is 3.5
Above code is able to send/receive request from database by using fetch.php.
Problem is in my database there are two records test & temp when I tag any one of them it create new tag.
It should work like this: if database have value then it won't create the new tag with same name.
Update
Tags need an id and a text. The issue you're facing is that your text doesn't match the id.
So, even if you write the same text, Select2 thinks the new text is a new option because the id don't match.
To solve your issue, you need to set the id with the same value as the text. Change the foreach of your fetch.php to the following:
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
Update:
You also need to update the variable lastResults to avoid the duplication of tags with the same text. When you bind select2, you need to change the results property of ajax to this (based on this answer:
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function(term) {
return {q: term};
},
results: function(data) {
lastResults = data.results;
return {results: data};
},
},
Note the lastResults = data.results;. Without this, the lastResults variable is always empty and, when the createSearchChoice function is executed, it will always return a new tag.
Finally it is working now. I would like to thanks #alex & #milz for their support.
Here is the full n final code. Now duplicate tags are not creating. However, i am working to add tag in database.
php/html file
<div class="form-group">
<label class="col-sm-4 control-label">Product Name</label>
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
tags: true,
placeholder: "Please enter tags",
tokenSeparators: [',', ' '],//[","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: 'json',
// type: "POST",
data: function(term,page) {
return {
term: term
};
},
results: function(data,page) {
lastResults = data;
return {results: data};
},
},
maximumSelectionSize: 3,
minimumInputLength: 3,
createSearchChoice: function(term) {
console.log($(this).attr('data'));
var text = term + (lastResults.some(function(r) {
console.log(r.text);
console.log(term);
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
Here is the php file to get the data from database.
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
//if(isset($_GET)){
$search = strip_tags(trim($_GET['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => 'No Products Found', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
It took lots of time. Almost 3 days. I hope it will save someone efforts.
Apply the changes as in the select2.min.js (v4.0.6-rc.1) code snippet below
section 1
c.on("results:select", function() {
var a = e.getHighlightedResults();
if (0 !== a.length) {
var c = b.GetData(a[0], "data");
"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
//custom select2 tagging
if(a.attr("aria-selected")){
c.id = c.id + 1;
}
e.trigger("select", {
data: c
})
//"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
// e.trigger("select", {
// data: c
// })
}
})
section 2
this.on("query", function(b) {
a.isOpen() || a.trigger("open", {}), this.dataAdapter.query(b, function(c) {
//custom select2 tagging
let searchInput = $(".select2-search__field").val();
searchInput = {results: [{id: searchInput, text: searchInput}]};
a.trigger("results:all", {
data: c,
data: searchInput,
query: b
})
})
})
I am new to Yii2 i want to display list of offers at left side when i clicked on offer it should displays details on right side.
this is my tradesmanOffer view page
<?php
foreach ($model as $offer) {
?>
<div class="offer-row" data-id="<?=$offer->o_id?>">
<div class="box">
<div class="offer-col-7"> <div><b>NEW OFFER</b> from
<?php
if ($offer->c_id) {
$contractor = Contractor::getoffername($offer->c_id);
if (!empty($contractor)) {
echo $contractor->name;
}
}
?></div>
this is my .js file:
$(function () {
$(".offer-row").on("click", function (event) {
$(".offers").empty();
var tid = $(this).attr("data-id");
alert(1);
$.ajax({
url: "offer-details?t_id=" +tid,
type: "GET",
contentType: false,
cache: false,
success: function (data) {
//alert(2);
$("#ajaxdiv").html('');
$("#ajaxdiv").html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
return false;
});
});
this is my controller page as OfferController
public function actionOfferList() {
if (Yii::$app->session->get('t_id') != "") {
$model = new TradesmanOffer();
$t_id = Yii::$app->session->get('t_id');
$offers = $model->getOffers($t_id);
return $this->render('tradesmanOffer', ['model' => $offers]);
} else {
return $this->redirect('../site/index');
}
}
public function actionOfferDetails() {
$t_id= $_GET['t_id'];
$model = new TradesmanOffer();
$offer = $model->getOffers($t_id);
return $this->renderAjax('tradesmanOfferNew', ['model' => $offer]);
}
this is my another view tradesmanOfferNew:
<div> <b>NEW OFFER</b> from
<?php
if ($offer->c_id) {
$contractor = Contractor::getoffername($offer->c_id);
if (!empty($contractor)) {
echo $contractor->name;
}
}
?>
and when i clicked on any offer and if refreshed browser it should same data on page.
how i achieve this?please help
thanks in advance
Why are you using contentType: false in your ajax call? Since you're getting some HTML from your call, you should set it to html
how to redirect the request to specified php page by ajax call, below is my code structure
index.html
<html>
<script>
function shift(str)
{
$.ajax({
url: 'destination.php',
type:'POST',
data: {q:str}
}).done(function( data) {
$("#result").html(data);
});
return false;
}
</script>
<body>
<input type='button' value='test' onclick="shift('test');">
<div id='result'></div>
</html>
destination.php
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
header('something.php');
}
else
{
echo "test";
}
?>
this is my code structure if posted string is same as then header funtion should be work else echo something, but header funstion is not working via ajax
You should specify header parameter to Location. Use the code below
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
header('Location:something.php');
}
else
{
echo "test";
}
?>
Hope this helps you
Go With This
You can check the string in jquery like below..
First you must echo the variable in php page.
then,
$.ajax({
url: 'destination.php',
type:'POST',
data: {q:str}
}).done(function( data) {
if(data=="something")
{
window.location.assign("http://www.your_url.com"); //
}
});
return false;
}
You should always retrieve the response in json format and based on that decide where to redirect. use below code for your requirement.
function shift(str) {
$.ajax({
url: 'destination.php',
type: 'POST',
data: {
q: str
}
}).done(function (resp) {
var obj = jQuery.parseJSON(resp);
if (obj.status) {
$("#result").html(obj.data);
} else {
window.location..href = "YOURFILE.php";
}
});
return false;
}
Destination.php
<?php
$string=$_REQUEST['q'];
$array = array();
if($string=="something")
{
$array['status'] = false;
$array['data'] = $string;
}else {
$array['status'] = true;
$array['data'] = $string;
}
echo json_encode($array);
exit;
?>
function shift(str) {
$.ajax({
url: 'destination.php',
type: 'POST',
data: {
q: str
}
}).done(function (data) {
if (data=="something") {
window.location.href = 'something.php';
}
else {
$("#result").html(data);
}
});
return false;
}
in Destination.php
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
echo "something";
}
else
{
echo "test";
}
?>