django csrf cookie no longer working - django

I don't understand why, but Django has ceased including the csrf cookie in responses. I have the middleware enabled, have tried using RequestContext and am using render. I have even tried using the csrf_protect and requires_csrf_token decorators.
I am working on a dev server right now, and I can print the context after I use RequestContext, and it seems to include a csrf_token.
But when I look at the actual headers using Chrome's inspect element, the csrf_token isn't there, also when I use the console and type in "document.cookie" that does not have the csrf token.
HELP!
Here's an example view
#requires_csrf_token
def index(request):
context = RequestContext(request, {'foo':'bar'})
print context
return render(request, 'index.html', context)
The CSRF token seems to be in the context:
{u'csrf_token': <django.utils.functional.__proxy__ object at 0x1025ab990>}, ...
But it fails to make its way through...
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:__utma=96992031.468590559.1369255550.1369255550.1369255550.1; __utmb=96992031.17.10.1369255550; __utmc=96992031; __utmz=96992031.1369255550.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Host:127.0.0.1:8000
Referer:http://127.0.0.1:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
UPDATE: Here is the template I'm using:
{% extends "base.html" %}
{% block hello %}
Basic Stock Event Charts
{% endblock %}
{% block content %}
<div id="leftsidebar">
<p>Use this tool to graph a time series data for a security. You can graph a security and
four other features such as volume, call option volume, or implied volatility. The tool will
zoom in on the date of interest to show the target audience the changes in the selected
vaiables preceeding the event. Because of large movement in variables before the announcement,
it may be helpful to use the minimum and maximum tools to zoom in on smaller movements ahead
of the event. </p>
<div class="ui-widget inline">
<label for="securities">1. Type in a ticker symbol</label>
<input id="securities">
</div>
<div class="inline"><input type="button" id="reload" value="Reset" class="hide" /></div>
<label for="datepicker">2. Pick your event date of interest.</label>
<input type="text" id="datepicker" disabled />
<label>3. Choose other series to graph.</label>
<p><strong>Primary Axis</strong></p>
Left Axis: <select id="series1" class="selectpicker span2" disabled><option value=""></option></select>
<div id="series1minmax" class="hide">
Min <input type="text" id="min1" class="input-mini" />
Max <input type="text" id="max1" class="input-mini" />
</div><input type="button" id="addaxes1" value="Graph" class="hide" />
<input type="button" id="removeaxes1" value="Remove" class="hide" /><br />
<br/>Right Axis: <select id="series2" class="selectpicker span2" disabled><option value=""></option>></select>
<div id="series2minmax" class="hide">
Min <input type="text" id="min2" class="input-mini" />
Max <input type="text" id="max2" class="input-mini" />
</div><input type="button" id="addaxes2" value="Graph" class="hide" />
<input type="button" id="removeaxes2" value="Remove" class="hide" /><br />
<input type="button" id="addextraaxis" value="Add Additional Axis" disabled/><br />
<div id="additional" class="hide">
<p><strong>Additional Axis</strong></p>
Left Axis: <select id="series3" class="selectpicker span2" disabled><option value=""></option></select>
<div id="series3minmax" class="hide">
Min <input type="text" id="min3" class="input-mini" />
Max <input type="text" id="max3" class="input-mini" />
</div><input type="button" id="addaxes3" value="Graph" class="hide" />
<input type="button" id="removeaxes3" value="Remove" class="hide" /><br />
<br/>Right Axis: <select id="series4" class="selectpicker span2" disabled><option value=""></option>></select>
<div id="series4minmax" class="hide">
Min <input type="text" id="min4" class="input-mini" />
Max <input type="text" id="max4" class="input-mini" />
</div><input type="button" id="addaxes4" value="Graph" class="hide" />
<input type="button" id="removeaxes4" value="Remove" class="hide" /><br />
</div>
</div>
<div id="rightsidebar">
<div id="container" class="hide"></div>
</div>
</div>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script>
$(function() {
$("#removefromchart").click(function() {
var conceptName = $('#savedseries').find(":selected").remove();
});
$("#reload").click(function() {
location.reload();
})
$("#addextraaxis").click(function() {
$("#additional").removeClass("hide");
this.disabled = true
$("#addextraaxis").addClass("hide");
var chart = $("#container").highcharts();
chart.setSize(null, 650);
})
});
$(function() {
$("#series1").change(function() {
$("#addaxes1").removeClass("hide");
});
$("#series2").change(function() {
$("#addaxes2").removeClass("hide");
});
$("#series3").change(function() {
$("#addaxes3").removeClass("hide");
});
$("#series4").change(function() {
$("#addaxes4").removeClass("hide");
});
});
$(function() {
function setExtreme(isMin, axis, value) {
console.log("fired");
var chart = $('#container').highcharts();
if (isMin) {
console.log(value + " " + chart.yAxis[axis].getExtremes()["max"])
chart.yAxis[axis].setExtremes(value, chart.yAxis[axis].getExtremes()["max"]);
} else {
console.log(value + " " + chart.yAxis[axis].getExtremes()["min"])
chart.yAxis[axis].setExtremes(chart.yAxis[axis].getExtremes()["min"], value);
}
console.log(value);
}
function getAxisNumber(series) {
var indicies = {}
$.each(chart.yAxis, function(index, element) {
indicies[element.options.id] = index;
console.log(element.options.id);
});
return indicies[series]
}
$("#max1").change(function() {setExtreme(0, getAxisNumber("#series1"), this.value)});
$("#min1").change(function() {setExtreme(1, getAxisNumber("#series1"), this.value)});
$("#max2").change(function() {setExtreme(0, getAxisNumber("#series2"), this.value)});
$("#min2").change(function() {setExtreme(1, getAxisNumber("#series2"), this.value)});
$("#max3").change(function() {setExtreme(0, getAxisNumber("#series3"), this.value)});
$("#min3").change(function() {setExtreme(1, getAxisNumber("#series3"), this.value)});
$("#max4").change(function() {setExtreme(0, getAxisNumber("#series4"), this.value)});
$("#min4").change(function() {setExtreme(1, getAxisNumber("#series4"), this.value)});
});
$(function()
{
$("#removefromchart").click(function()
{
var conceptName = $('#savedseries').find(":selected").remove();
});
});
$(function() {
function addPlotLine(ts) {
var chart = $('#container').highcharts();
chart.xAxis[0].addPlotBand({
from: ts,
to: ((ts + 86400000) * 365),
color: 'rgba(68, 170, 213, 0.2)',
id: 'tsband'
});
chart.xAxis[0].addPlotLine({
value: ts,
color: 'rgb(255, 0, 0)',
width: 1,
id: 'tsline'
});
chart.xAxis[0].setExtremes(ts - (86400000 * 30), ts + 86400000)
}
function removeEventIfExists() {
var chart = $("#container").highcharts()
chart.xAxis[0].removePlotBand("tsband");
chart.xAxis[0].removePlotLine("tsline");
}
$("#datepicker").datepicker({
showButtonPanel: true, /*added by oussama*/
changeMonth: true, /*added by oussama*/
changeYear: true, /*added by oussama*/
dateFormat: 'yy-mm-dd',
onSelect: function (dateText, inst) {
utcDate = Date.UTC(dateText.split("-")[0], dateText.split("-")[1] - 1, dateText.split("-")[2]);
removeEventIfExists();
addPlotLine(utcDate);
$("#series1").removeAttr("disabled");
$("#series2").removeAttr("disabled");
$("#series3").removeAttr("disabled");
$("#series4").removeAttr("disabled");
$("#addextraaxis").removeAttr("disabled");
var ticker = $("#securities").val();
var date = $("#datepicker").val();
chart.setTitle({text: ticker + " around " + date});
}
});
});
$(function() {
function createChart() {
var chart = $('#container').highcharts();
var options = {chart: {
renderTo: 'container',
height: 450,
},
events: {
load: function(event) {
this.setExtremes();
}
},
rangeSelector: {
enabled: false,
},
exporting: {
enabled: false,
},
navigator: {
enabled: true,
series: { id: 'navigator' },
},
yAxis: [{
title: {
text: 'Price'
},
height: 150,
}],
},
chart = new Highcharts.StockChart(options);
return chart;
}
$("#securities").autocomplete({
source: "/api/get_securities/",
minLength: 1,
select: function(event, ui) {
var ticker = ui.item.label;
getSeries(ticker);
chart = createChart();
getTimeSeriesData(ticker + "|PX_LAST", 0);
$('#container').show();
$('#datepicker').removeAttr("disabled");
$('#reload').removeClass("hide");
chart.setTitle({text: ticker});
this.disabled = 'disabled';
},
});
});
$(function() {
function removeAxes(id) {
var chart = $('#container').highcharts();
chart.get(id).remove();
}
$("#removeaxes1").click(function() {
console.log("removeaxes1 clicked");
removeAxes("#series1");
$("#removeaxes1").addClass("hide");
$("#series1minmax").addClass("hide");
$("#series1minmax").removeClass("inline");
$("#series1").val("");
$("#min1").val("");
$("#max1").val("");
$("#series1").removeAttr("disabled");
});
$("#removeaxes2").click(function() {
console.log("removeaxes2 clicked");
removeAxes("#series2");
$("#removeaxes2").addClass("hide");
$("#series2minmax").addClass("hide");
$("#series2minmax").removeClass("inline");
$("#series2").val("");
$("#min2").val("");
$("#max2").val("");
$("#series2").removeAttr("disabled");
});
$("#removeaxes3").click(function() {
console.log("removeaxes3 clicked");
removeAxes("#series3");
$("#removeaxes3").addClass("hide");
$("#series3minmax").addClass("hide");
$("#series3minmax").removeClass("inline");
$("#series3").val("");
$("#min3").val("");
$("#max3").val("");
$("#series3").removeAttr("disabled");
});
$("#removeaxes4").click(function() {
console.log("removeaxes4 clicked");
removeAxes("#series4");
$("#removeaxes4").addClass("hide");
$("#series4minmax").addClass("hide");
$("#series4minmax").removeClass("inline");
$("#series4").val("");
$("#min4").val("");
$("#max4").val("");
$("#series4").removeAttr("disabled");
});
function addSeries(id, minMaxId, isOpposite, isAdditional) {
var chart = $('#container').highcharts();
indicies = {}
console.log('climlckedaddaxes');
var series = $(id).val()
var top = 210
if (isAdditional) top = 380
var options = {
title: {
text: series.split("|")[1]
},
top: top,
height: 150,
opposite: isOpposite,
id: id,
offset: -30
}
chart.addAxis(options)
$.each(chart.yAxis, function(index, element) {
indicies[element.options.id] = index;
console.log(element.options.id);
});
getTimeSeriesData(series, indicies[id]);
$(minMaxId).removeClass("hide")
$(minMaxId).addClass("inline")
}
$("#addaxes1").click(function() {
addSeries('#series1', "#series1minmax", false, false);
$("#addaxes1").addClass("hide")
$("#removeaxes1").removeClass("hide")
$("#series1").attr("disabled", "disabled")
});
$("#addaxes2").click(function() {
addSeries('#series2', "#series2minmax", true, false);
$("#addaxes2").addClass("hide")
$("#removeaxes2").removeClass("hide")
$("#series2").attr("disabled", "disabled")
});
$("#addaxes3").click(function() {
addSeries('#series3', "#series3minmax", false, true);
$("#addaxes3").addClass("hide")
$("#removeaxes3").removeClass("hide")
$("#series3").attr("disabled", "disabled")
});
$("#addaxes4").click(function() {
addSeries('#series4', "#series4minmax", true, true);
$("#addaxes4").addClass("hide")
$("#removeaxes4").removeClass("hide")
$("#series4").attr("disabled", "disabled")
});
})
$('#addtochart').click(function() {
var selectedValues = $('#seriesselector').val();
$.each(selectedValues, function(index, value) {
$('#savedseries').append($('<option>', {
value: value,
text: value,
selected: true,
}));
$('#seriesselector option[value="' + value +'"]').remove();
});
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function parseDate(inputdate, value) {
var date = inputdate;
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) - 1;
var day = parseInt(date.split("-")[2]);
var outputdate = Date.UTC(year, month, day);
if (year == 2013 && month == 3) {
//console.log(inputdate, outputdate, value);
}
return outputdate;
};
function getTimeSeriesData(seriesName, axis) {
var csrftoken = getCookie('csrftoken');
console.log('csrftoken is :: ' + csrftoken);
$.ajax({ // create an AJAX call...
beforeSend: function(xhr, settings) {
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
data: {'seriesName': seriesName }, // get the form data
type: 'POST',
url: '/api/get_time_series_data/',
success: function(response) { // on success..
console.log(response);
var series = {}
series['name'] = response[0]['series_name'];
series['data'] = []
$.each(response, function(index, value) {
series['data'][index] = [
parseDate(response[index]['date'], response[index]['value']),
parseFloat(response[index]['value'])
];
});
series['yAxis'] = axis
series['marker'] = {
enabled : true,
radius : 3
}
var chart = $('#container').highcharts();
chart.addSeries(series);
var nav = chart.get('navigator');
if (axis == 0) nav.setData(series['data']);
}
});
return false;
};
function getSeries(ticker) {
var csrftoken = getCookie('csrftoken');
$.ajax({ // create an AJAX call...
beforeSend: function(xhr, settings) {
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
data: {'ticker': ticker }, // get the form data
type: 'POST',
url: '/api/get_series/',
success: function(response) { // on success..
$('#seriesselector').empty()
for (var i = 0; i < response.length; i++) {
if (response[i].value == 'PX_LAST') continue;
$('#series1').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
$('#series2').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
$('#series3').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
$('#series4').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
}
}
});
return false;
};
</script>
{% endblock %}

Turns out you need the
{% csrf_token %}
regardless of whether or not you are posting a html form. I was only doing AJAX requests, but Django won't include the token in the response header unless it sees it the template.

Related

How can I send a CSRF token in a form?

I included a Vue form component in one of my Django templates. Now, I would like to send a CSRF token along with the data, since Django views require a CSRF token. Is there any way I can include it in my Vue form?
Here is my component:
<template>
<form #submit.prevent="formSubmit()">
<input type="text" class="form-control" v-model="amount">
<br>
<input type="text" class="form-control" v-model="price">
<br>
<button class="btn btn-primary" style="width: 100%">BUY</button>
</form>
</template>
<script>
import axios from 'axios'
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
name: '',
description: '',
output: ''
};
},
methods: {
formSubmit() {
let currentObj = this;
axios.post('MY_URL', {
price: this.price,
amount: this.amount,
})
.then(function (response) {
currentObj.output = response.data;
}.bind(this))
.catch(function (error) {
currentObj.output = error;
});
},
}
}
</script>
First, acquire the token from the csrftoken cookie:
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
...or from querying the document:
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value
Then, add the token value to your POST header:
axios.post('MY_URL', {
price: this.price,
amount: this.amount,
}, {
headers: {
'X-CSRFToken': csrftoken
}
})

Optimize JSOM Query

I have the following SharePoint 2016 JSOM query that retrieve the list item based on the current user email...this query currently works, however, I have been doing some study around using jquery defferred and Promised objects. In order to rationalize how this methods works I want to optimize the existing code below
<script type="text/javascript" src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
getCurrent();
//getMyTasks();
$('#checkall').click(function (e) {
$("#GetItems").find('td input:input[name=chk]').prop('checked', this.checked);
if($(this).is(':checked')) {
$('#Reject').removeAttr('disabled');
$('#Approve').removeAttr('disabled');
} else {
$('#Reject').attr('disabled', true);
$('#Approve').attr('disabled', true);
}
});
$('#GetItems').on('change', 'input[name=chk]', function(){
if($(this).is(':checked')) {
$('#Reject').removeAttr('disabled');
$('#Approve').removeAttr('disabled');
} else {
$('#Reject').attr('disabled', true);
$('#Approve').attr('disabled', true);
}
});
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', approve);
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', reject);
// approve();
//reject();
});
function getCurrent()
{
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=Email",
headers: { Accept: "application/json;odata=verbose" },
success: function (data) {
currentEmail=data.d.Email;
getMyTasks();
} ,
error: function (data) {
alert("failed to get email");
}
});
}
function getMyTasks(){
//var listTitle="hardware%20requisition";
var row = "";
var buttonrow="";
var url =_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EUS Asset Request')/Items?$select=ID,AssetMgrEmail,EUSPersonMailID,SRNo,AssetAvailability,Asset_x0020_Manager_x0020_Approv,Asset_x0020_Manager_x0020_Commen,Attachments,Department,Department_x0020_Head,Department_x0020_head_x0020_Appr,Department_x0020_head_x0020_appr1,Department_x0020_head_x0020_Appr0,HOD_x0020_Approval_x0020_Comment,IT_x0020_Head,IT_x0020_Head_x0020_Approval_x001,IT_x0020_head_x0020_Approval_x00,Items_x0020_Requested_x0020_For,IT_x0020_head_x0020_approval_x000,IT_x0020_head_x0020_Approved_x00,Job_x0020_Title,L1_x0020_Approval_x0020_Comments,L1_x0020_Approval_x0020_Date,L1_x0020_Approval_x0020_Status,L1_x0020_Approved_x0020_Date,L1_x0020_Supervisor_x0020_Email,Motivation,OPCO,Replacement_x0020_Type,Request_x0020_Summary,Request_x0020_Type,Requester_x0020_Name,EUSPersonMailID,Requester_x0020_Phone_x0020_Numb,ViewID,Author/Name,Author/EMail,Author/Title&$expand=Author/Id&$filter=EUSPersonMailID eq '"+currentEmail+"' and L1_x0020_Approval_x0020_Status eq 'Approved' and Department_x0020_head_x0020_appr1 eq 'Approved' and IT_x0020_head_x0020_approval_x000 eq 'Approved' and Asset_x0020_Manager_x0020_Approv eq 'Approved' and EUSTeamConfirmation eq 'Pending'"
$.ajax({
url: url,
type: "GET",
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
},
success: function(data){
var result = data.d.results;
if(result.length>0)
{
$("#divbuttons").show();
$.each(result, function(key, item)
{
var createdDate= moment(item.Created_x0020_Date).format("DD/MM/YYYY");
row = row + '<tr style="background-color: #cccccc;"><td style="width: 261.6px;"><strong>Select</strong> <input name="chk" type="checkbox" value='+ item.Id+' /></td><td style="width: 151.2px;"> </td><td style="width: 324.8px;"><strong>Request ID: </strong>'+item.ID+'</td><td style="width: 324.8px;"><strong>Requester Name: </strong>'+item.Author.Title+'</td><td style="width: 376.8px;"><strong>Phone Number:</strong><br />'+item.Requester_x0020_Phone_x0020_Numb+'</td><td style="width: 396px;"><strong>Department:</strong><br />'+item.Department+'</td><td style="width: 213px;"><strong>Request Type</strong><br />:'+item.Request_x0020_Type+'</td><td style="width: 4.8px;">Availability Status<br/>:'+item.AssetAvailability+'</td><td style="width: 213px;"><strong>Serial Number</strong><br />'+item.SRNo+'</td><td style="width: 213px;"><strong>EUS Person MailID</strong><br />'+item.EUSPersonMailID+'</td><td style="width: 213px;"><strong>Receiver MailID</strong><br />'+item.Author.EMail+'</td></tr>';
})
$("#GetItems>tbody").html(row);
$("#GetItems").show();
}
else{
$("#NoTask").show();
}
},
error: function(data){
alert("Failed to get list items.");
}
});
}
function approve(){
$("#Approve").click(function(event){
event.preventDefault();
var searchIDs = $("#GetItems input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var itemArray = [];
var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
var oList = clientContext.get_web().get_lists().getByTitle("EUS Asset Request");
for(var i = 0; i< searchIDs.length; i++){
// alert($("#GetItems textarea#"+searchIDs[i]+"").val());
var oListItem = oList.getItemById(searchIDs[i]);
oListItem.set_item('EUSTeamConfirmation', 'Confirmed');
oListItem.set_item('ViewID', 'FinalVw');
oListItem.update();
itemArray[i] = oListItem;
clientContext.load(itemArray[i]);
}
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded() {
alert('Items Updated');
location.reload(true);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
location.reload(true);
}
});
}
function reject(){
$("#Reject").click(function(event){
event.preventDefault();
var searchIDs = $("#GetItems input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var itemArray = [];
var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
var oList = clientContext.get_web().get_lists().getByTitle("EUS Asset Request");
for(var i = 0; i< searchIDs.length; i++){
var oListItem = oList.getItemById(searchIDs[i]);
oListItem.set_item('EUSTeamConfirmation', 'Rejected');
oListItem.set_item('ViewID', 'RejectVw');
oListItem.update();
itemArray[i] = oListItem;
clientContext.load(itemArray[i]);
}
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded() {
alert('Task Rejected');
location.reload(true);
//getCurrent();
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
location.reload(true);
// getCurrent();
}
});
}
</script>
<div id="NoTask" style="display:none">You don't have pending tasks for approval</div>
<div style="display:none" id="divbuttons"><input type="checkbox" id="checkall"></input><button type="button" id="Reject" disabled>Reject</button><button type="button" id="Approve" disabled>Approve</button></div>
<table id="GetItems" cellspacing="12"><tbody></tbody> </table>
Kindly assist

Opencart if product available Button show else disable that button

Hi i'm creating a application using Opencart. It fully customized, i have doubt in this.
I have filter.tpl page, in this page i need to display and hide button based on product availability
Eg:
If product available show like this
enter image description here
else button show like this enter image description here
Am trying this fowling code using ajax
filter.tpl
$('input[name=\'filter_name\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/product/getProductCheck' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
label: item['name'],
value: item['product_id']
}
}));
}
});
},
'select': function(item) {
$('input[name=\'filter_name\']').val(item['label']);
}
});
In controller
product.php
public function getProductCheck()
{
/*Some code here*/
}
So you can use if ($product['quantity']) statement for example
I got the out put am using javascript following code
<div class="form-group">
<div style='display:none;' id='instock'>
<a class='instock-btn'>Product / Solution Available</a>
<input type='submit' class='btn-orng available' name='' value="Click here for more details" size='20' />
</div>
<div style='display:none;' id="outstock">
<input type='submit' class='outstock-btn' name='' value="Product / Solution Not Available" size='20' />
<input type='submit' class='btn-orng' name='' value="We will contact you at the earliest" size='20' />
</div>
</div>
script
$(document).ready(function(){
$('#dia1').on('change', function() {
//var value =
if (this.value <='320' )
{
$("#instock").show();
$("#outstock").hide();
}
else
{
$("#instock").hide();
$("#outstock").show();
}
});
$('#len1').on('change', function() {
//var value =
if (this.value <='310' )
{
$("#instock").show();
$("#outstock").hide();
}
else
{
$("#instock").hide();
$("#outstock").show();
}
});
});

Activeadmin Rails 4 TypeError: $(...).fullCalendar is not a function

Am using rails 4 in my application with active admin gem. i am using fullcalender to show the events.
my code is below index.html.erb
<br />
<div class="link_back">
<%= link_to "Back", meeting_rooms_path, class: "btn-sm btn-primary" %>
</div>
<br />
<%= render 'errors' %>
<p>
<%=link_to 'Create Event', new_event_url(meeting_room_id: params["meeting_room_id"]), :id => 'new_event' %>
</p>
<br />
<!-- <div>
<div class='calendar'></div>
</div> -->
<div>
<div id='calendar'>
</div>
</div>
<div id = "desc_dialog" class="dialog" style ="display:none;">
<div id = "event_desc">
</div>
<br/>
<br/>
<div id = "event_actions">
<span id = "edit_event"></span>
<span id = "delete_event"></span>
</div>
</div>
<div id = "create_event_dialog" class="dialog" style ="display:none;">
<div id = "create_event">
</div>
</div>
<script>
// page is now ready, initialize the calendar...
$('#new_event').click(function(event) {
event.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
beforeSend: function() {
$('#loading').show();
},
complete: function() {
$('#loading').hide();
},
success: function(data) {
$('#create_event').replaceWith(data['form']);
$('#create_event_dialog').dialog({
title: 'New Event',
modal: true,
width: 500,
close: function(event, ui) { $('#create_event_dialog').dialog('destroy') }
});
}
});
});
$('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
//defaultView: 'agendaWeek',
defaultView: 'month',
height: 500,
slotMinutes: 15,
loading: function(bool){
if (bool)
$('#loading').show();
else
$('#loading').hide();
},
events: "/events/get_events?meeting_room_id=<%= params[:meeting_room_id]%>",
timeFormat: 'h:mm t{ - h:mm t} ',
dragOpacity: "0.5",
eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc){
// if (confirm("Are you sure about this change?")) {
moveEvent(event, dayDelta, minuteDelta, allDay);
// }
// else {
// revertFunc();
// }
},
eventResize: function(event, dayDelta, minuteDelta, revertFunc){
// if (confirm("Are you sure about this change?")) {
resizeEvent(event, dayDelta, minuteDelta);
// }
// else {
// revertFunc();
// }
},
eventClick: function(event, jsEvent, view){
if ((<%= current_user.id %>) == event.user_id){
showEventDetails(event);
}
},
});
</script>
the same fullcalender i have used with normal rails 4 applicaiton its working fine.
but with activeadmin its throwing the javascript error as,
TypeError: $(...).fullCalendar is not a function
and the calender is not displaying in view
Because of this error am not able to continue pls help ..
You are not importing fullcalendar js and css files, add these lines
in app/assets/javascripts/active_admin.js.coffee
#= require fullcalendar
in app/assets/javascripts/active_admin.css.scss
#import "fullcalendar"

How to preselect a default object using Ember.select

and I'm currently using Ember.select for a drop down menu, and while there's a default value showing, the object does't appear to actually be selected. When IO render the page, the modal open up but the value for selected_funding_instrument is undefined until I click on the drop down menu. Any tips?
debit-customer-modal.hbs:
<div {{bindAttr class=":control-group model.validationErrors.source_uri:error"}}>
<label class="control-label">Account number</label>
<div class="controls">
{{view Ember.Select
contentBinding="customer.debitable_funding_instruments"
valueBinding="model.source_uri"
optionValuePath="content.uri"
optionLabelPath="content.description_with_type"
class="span8"
}}
</div>
</div>
<div class="control-group">
<label class="control-label">Account holder's name</label>
<div class="controls">
<span class="label1a">{{selected_funding_instrument.name}}</span>
</div>
</div>
debit_customer_modal.js
require('app/components/modal');
Balanced.DebitCustomerModalComponent = Balanced.ModalComponent.extend({
submitAction: 'submitDebitCustomer',
dollar_amount: null,
actions: {
open: function() {
var fundingInstruments = this.get('customer.debitable_funding_instruments');
var debitUri = (fundingInstruments && fundingInstruments.length > 0) ? fundingInstruments[0].get('debits_uri') : null;
var debit = Balanced.Debit.create({
uri: debitUri,
amount: null,
order: this.get('order.href')
});
this.set('dollar_amount', null);
var selfie = this.get('selected_funding_instrument');
this._super(debit);
},
save: function() {
if (this.get('model.isSaving')) {
return;
}
var debit = this.get('model');
var selfie = this.get('selected_funding_instrument');
if (selfie) {
debit.set('uri', selfie.get('debits_uri'));
}
var cents = null;
try {
cents = Balanced.Utils.dollarsToCents(this.get('dollar_amount'));
} catch (error) {
debit.set('validationErrors', {
'amount': error
});
return;
}
debit.set('amount', cents);
this._super(debit);
}
},
selected_funding_instrument: function() {
var sourceUri = this.get('model.source_uri');
if (sourceUri) {
return this.get('customer.debitable_funding_instruments').find(function(fundingInstrument) {
return sourceUri === fundingInstrument.get('uri');
});
}
}.property('model.source_uri', 'customer.debitable_funding_instruments'),
can_debit: function() {
return this.get('customer.debitable_funding_instruments.length') > 0;
}.property('customer.debitable_funding_instruments')
});
You need to fire up selected_funding_instrument
Balanced.DebitCustomerModalComponent = Balanced.ModalComponent.extend({
init: function () {
this.selected_funding_instrument();
return this._super();
}
}):
It would be nice if you can create fiddle.