jquery can't select unique elements using classes - javascript

I'm trying to use ajax on some auto generated html elements from django. I saw that you do this by selecting the instances via the class, but I can't seem to get it working. What do I have wrong here?
javascript
$(document).ready(function() {
$('.fix-button').on('submit', function(event) {
event.preventDefault();
var $issue_id = $(this);
$.ajax({
url: '{% url "fix_issue" %}',
type: 'POST',
datatype: 'json',
data: {
issueid: $issue_id.val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.getElementById("fixed_bool").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err) {
}
});
});
});
html
<button class = "fix-button" value = "{{ issue.id }}">Fix</button>
views.py
def FixView(request):
if request.POST.get('action') == 'post':
result = ''
id = int(request.POST.get('issueid'))
issue = get_object_or_404(Issue, id=id)
if issue.fixed == False:
issue.fixed = True
result = str(issue.fixed)
issue.save()
else:
issue.fixed = False
result = str(issue.fixed)
issue.save()
return JsonResponse({'result': result, })

You're trying to add an eventlistener to essentially, a list, instead of a single element.
Try using the .each() method after grabbing the element.
https://api.jquery.com/each/

The backend was actually working, but the label that switches between true and false was the thing that wasn't properly updating. To fix this, I added unique id's to the label, <span id = "{{ issue.id }}">{{ issue.fixed }}</span> and got the unique id using
var issue_id = $(this).val()
document.getElementById(issue_id).innerHTML = json['result']

Related

HTML value passed to WebService is showing NULL

I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146&quotenum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

Javascript - CORRECTLY append new comments without reloading

I have asked a question, how to append comments already. I got quite great answer. BUt now i want to know how to append new comments correctly, without refreshing! RIght now I add new comments with just creating new element containing comment and comment user, but they dont appear "from database". Is there any way to append new comments without having to reload whole page, but just the div containing comments, and just adding new comment?
I have this code for now:
$(".comments input[name='post']").keydown(function (evt) {
var keyCode = evt.which?evt.which:evt.keyCode;
if (keyCode == 13) {
var form = this.closest("form");
var container = form.closest(".comments");
var olist = $(container).find(".clearfix");
var input = this;
$.ajax({
url: "{% url 'comment' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}",
data: $(form).serialize(),
type: 'post',
cache: false,
beforeSend: function () {
$(input).val("");
$(input).blur();
},
success: function (data) {
alert(data.comment);
clearfix = $(container).children(".clearfix");
clearfix.append("<small>"+data.user+"</small>" + "<br>" + data.comment)
}
});
}
});
I have this in the views:
def comment(request, letnik_id, classes_id, subject_id):
if request.method == 'POST':
exam_id = request.POST.get('exam_id')
exam = get_object_or_404(Exam, id=exam_id)
comment = request.POST.get('post')
comment = comment.strip()
if len(comment) > 0:
instance = ExamComment(
exam=exam,
comment=comment,
comment_user=request.user)
instance.save()
user = request.user.username
return JsonResponse({'comment': comment, 'user': user})
else:
return HttpResponseBadRequest()

Updating an element via ajax: shall I use global variable to keep element's id or it is a bad habit?

On a page I have a list of dates which I want to edit via AJAX.
Example:
<li>January 2015<a data-update_url="/frame_date/22/update/" class="update" id="update_framedate_22" href="javascript:void(0)">Edit</a>
When the user clicks on the Edit link, I catch element id and the edit link.
Than AJAX requests the update form from the server. And now I have to place the form instead of the element with the mentioned id.
In other words, in frame_date_update_show_get I need element's id. In the example below, I keep it in the global variable date_id. But inside me there is a protest: I was always taught that global variables is a bad practice. But in this case I don't know how to get along without the global variable date_id.
Could you give me some piece of advice: is my code acceptable or there is a better way to cope with the problem.
function frame_date_update_show_get(data){
$("#" + date_id).replaceWith(data);
}
function frame_date_update_get_data(){
date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');
$.ajax({
method: 'get',
url: cuaghtUrl,
success: frame_date_update_show_get,
error: fail
});
}
var date_id = ""
Use an anonymous function as success callback function and then call frame_date_update_show_get with an additional date_id parameter:
function frame_date_update_show_get(data, date_id) {
$("#" + date_id).replaceWith(data);
}
function frame_date_update_get_data() {
var date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');
$.ajax({
method: 'get',
url: cuaghtUrl,
success: function(data) {
frame_date_update_show_get(data, date_id);
},
error: fail
});
}
I would use contenteditable combined with AJAX this way:
function dateChange(options){
switch( options.action ) {
case 'update':
if( options.id && options.text && options.updateUrl ) {
$.ajax({
method: 'post',
url: options.updateUrl,
data: {
id: options.id,
html: options.text
},
success: function(response) {
options.element.html( response );
options.element.removeClass('editing');
},
error: function(err) {
console.log( 'request failed: ' + err.text );
}
});
};
break;
default:
console.log( 'action invalid' );
return false;
break;
};
};
var editTimeout = null;
$('li[data-update-url]').on('input', function(e) {
var thisText = $(this);
thisText.addClass('editing');
clearTimeout( editTimeout );
editTimeout = setTimeout(function() {
var updateUrl = thisText.data('updateUrl');
var id = thisText.data('id');
dateChange({
'action': 'update',
'element': thisText,
'id': id,
'updateUrl': updateUrl,
'text': thisText.html()
});
}, 1000);
});
.editing {
color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-update-url="/echo/html/" data-id="update_framedate_22" contenteditable>January 2015</li>
</ul>
Check how it works on JSFiddle.
This code would be easy to expand for other actions you may need, as delete, add.

Trouble with Ajax post in Django

I need three dependent drop down menus. When a user selects the first menu (market environment), then I need ajax to send that selection to my view in django so I can query SQL to get a list of currencies and populate the second list. In firebug, I keep getting the following error:
MultiValueDictKeyError at /Tplots/ajax_curr/"'mkt'"
I also notice that my Post is empty so I think something is going wrong with my ajax code and I'm not sure whats wrong. Any help would be great.
HTML
<script type="text/javascript">
$(document).ready(function get_currency(){
$('#id_mkt').on('change', function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url: "/Tplots/ajax_curr/",
datatype: "json",
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
}
})
})
})
</script>
<div align="center">
<h1>Swap Curves</h1>
<form action="{% url 'Tplots:swapFig' %}" method = "post">
{% csrf_token %}
{{form.mkt}}
{{form.curr}}
{{form.horizon}}
<input type = "submit" value="Go To" />
</form>
view.py
#csrf_exempt
def ajax_curr(request):
if request.is_ajax():
selected_mkt = MktEnv.objects.get(mkt=request.POST['mkt'])
#selected_mkt = request.POST.get('mkt','')
conn = pyodbc.connect('abcd')
cursor = conn.cursor()
sql_raw = r'''
select currency from market_env_detail
where mkt_env_id=%s
and idx = 1''' % (selected_mkt)
cursor.execute(sql_raw)
xx = cursor.fetchall()
currencyL = []
for items in xx:
x = str(items[0])
currencyL.append(x)
curr = list(set(currencyL))
json = simplejson.dumps(curr)
print json
return HttpResponse(json, mimetype="application/json")
forms.py
class CurrencyForm(forms.Form):
Env_Choices = [('', '-- Choose a Environment --'), ] + [(m.mkt, m.mkt) for m in MktEnv.objects.all()]
Curr_Choices = [('', '--Choose a Currency --'),]+[(c.curr, c.curr) for c in CurrencyAjax.objects.all()]
Horizon_Choices = [('', '--Choose a Horizon --'),] +[(h.hid, h.hid) for h in HorIdAjax.objects.all()]
mkt = forms.ChoiceField(choices=Env_Choices)
curr = forms.ChoiceField(choices=Curr_Choices)
horizon = forms.ChoiceField(choices=Horizon_Choices)
Edit:
I'm trying to put the data into the second dropdown using this success function but all my values become blank. Don't know why.
success: function(data) {
for(var i =0; i<data.length; i++) {
var item=data[i];
$('#curr').append(
$("<option></option>").val(item.Id).html(item.Name));
}
}
You are not sending POST data. You are missing the data parameter.
var data = $(this).parents('form').serialize();
$.ajax({
type:"POST",
url: "/Tplots/ajax_curr/",
data: data,
datatype: "json",
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
}
})

Categories

Resources