Avoid double call GET Ajax load - django

Well, I'm trying to create a graphical interface for a database using django.
I have to say that I'm trying to learn so I don't have too much experience with Frameworks, just with pure code.
The doubt I have is:
-When trying to create a filter system with checkboxes I have used Ajax to be able to update the view without having to refresh. Like this:
$(document).on('click','#console_check_filter',function(){
var ps_id;
ps_id = $(this).attr("data-posts-id");
$.ajax({
url: "{% url 'list-view' %}",
method: 'POST',
data: {
'getfilter': ps_id,
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function (res, status,data) {
$("#list").load("/game/list-view");
},
error: function (res,ras,rus) {
}
});
});
But I had the error that for every call I made with POST the AJAX function ().load() made another call which eliminated the variable that gave me the POST. This made it impossible for me to use the information received from the POST to create the filter.
Result: I click on the checkbox and in the console I get a call with the filtered list and then another one without filter, and as it is not only the last one that is rendered, which has no data.
To solve this I have used a globar variable to save the value in the POST and the ().load() return to make the GET call using the value saved in the GLOBAL.
filet=""
def game_list(request):
global filet
context = {}
game_filter = request.GET.get('console_check_filter')
games = Game.objects.all()
game_post = games
data = {'success': False}
page = request.GET.get('page',1)
game_console_filter=""
context['games'] = games
#if request.method=='POST':
game_console_filter = request.POST.get('getfilter')
if not game_console_filter:
game_console_filter = request.GET.get('getfilter')
if request.method=="POST":
filet = get_game_console_filter(request,game_console_filter)
context['games'] = games
context['game_post'] = filet
return render(request,'Jocs/list-view.html',context )
This doesn't seem elegant to me, I'm out of the woods, yes, but I don't think it's the best solution.
Any idea to avoid this happening to me?
A greeting and thank you very much for everything

Apparently I am more stupid than I thought. In the end the solution was to send the variable by URL. Example:
AJAX:
$(document).on('click','#console_check_filter',function(){
var ps_id;
ps_id = $(this).attr("data-posts-id");
$.ajax({
url: "{% url 'list-view' %}",
method: 'POST',
data: {
getfilter': ps_id,
csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function (res, status,data) {
$("#list").load("/game/list-view/?filters="+ps_id); > <-----HERE
},
error: function (res,ras,rus) {
}
});
});
views.py:
#if request.method=='POST':
game_console_filter = request.POST.get('getfilter')
if not game_console_filter:
game_console_filter = request.GET.get('filters') <---HERE
I think that if this is the right way to proceed, at least it's more elegant.
I hope someone else will find this answer useful.
Sorry for the inconvenience and for asking trivial questions. Greetings to all.

Related

AJax does not seem to work on the delete button

I am really new to ajax. I want to delete the entry from database on button click and I do not want the page to reload. but the ajax doesn't seem to work at all. What is wrong in my code? Please suggest the correct code. Thanks in advance.
<script>
$(document).on('click','#delete',function(){
var a ;
a=confirm("Do you really want to delete the user?");
if(a==true){
var newurl = "{% url 'NewApp:centredelete' pk=1%}"
var id = $(this).attr('name')
$.ajax(
{
type:"GET",
url: "newurl.replace('1',id);",
data:{
delete:True
},
success: function( data )
{
if(data.success == true){
$(id).remove();
}
else{
alert(data.error)
}
}
})}
});
</script>
views.py
def CentreDeleteView(request, pk):
centre = Centre.objects.get(pk=pk)
centre.delete()
return HttpResponseRedirect(reverse('NewApp:centrelist'))
edit:
urls.py
url(r'^centredelete/(?P<pk>\d+)/$',views.CentreDeleteView,name='centredelete'),
I am getting "Not Found: /NewApp/centrelist/url.replace('1',id);
" in the terminal. I don't know why it is taking the wrong url.
Kindly add your url file here and mention here the response on server terminal
replace "newurl.replace('1',id);" with newurl.replace('1',id) in your ajax.
You've used double quotes around newurl.replace('1',id) so the url will send as is instead of replacing '1' with the required id.

can't access to the POST variable that sent from register form in django

I have a register form in html that has a button that type of submit and the name of registerSubmit like this:
<input class="RegisterButton right green" name="registerSubmit" type="submit" value="Continue">
I want to check the form with Ajax and then if every thing is valid then redirect the user to her/his profile.But when I want to redirect the user to his/her profile I can't send the submit input that its name is registerSubmit. here is a section of JQuery code that related to this event:
$("#mainRegisterForm").submit(function(event){
var thisRegisterForm = $(this);
$(".ajaxLogoRegister").show();
event.preventDefault();
var firstName = $("input[name='firstname']").val();
var lastName = $("input[name='lastname']").val();
var emailAddress = $("input[name='email']").val();
var password = $("input[name='password']").val();
var rePass = $("input[name='rePass']").val();
var sex = "NULL";
if ($("input[name='gender']").is(":checked")){
sex = $("input[name='gender']:checked").val();
}
var data ={
firstname:firstName,
lastname:lastName,
emailaddress:emailAddress,
password:password,
repass:rePass,
sex:sex
};
$.ajax({
url: 'ajax/registercheck',
data: data,
dataType: 'json',
success:function(result){
if(result.fn==0){
//do some stuff
}
//another if conditions that checks the validity of every field of refister form
...
...
$(".ajaxLogoRegister").hide();
if(result.isOK=='1'){ //isOK = 1 when every filed is valid and user must redirect to his/her profile
thisRegisterForm.unbind('submit').submit();
}
}
});
});
My main problem is that when I click the registerSubmit button in views.py the request.POST.get('registerSubmit') returns None object instead of Continue value.
when I don't use Ajax and send the form normally registerSubmit value is Continue and every thing is OK.where I am wrong?
By default, $.ajax(); will issue a GET request, not a POST. You need to specify that in your ajax options. Second, I don't see where you're accessing the value of the element named "registerSubmit". I see an "rePass", but you're not including the value you're expecting to find in the request.
You need to either specifically set the "type" ajax option type to "POST" or retrieve the method property from the form element:
$ajax({
url: 'ajax/registercheck',
data: data,
dataType: 'json',
type: 'POST',
....
});

Why does my Django request.method does not match POST

$.ajax({
type :'GET',
url : geturl(a),
// type: $(this).attr('method'),
dataType : 'json',
views.py:
if request.method=="POST":
if request.POST.get('monyrsubmit'):
monthform=MonthForm(request.POST)
if monthform.is_valid():
selected_month=monthform.cleaned_data["Month"]
selected_year=monthform.cleaned_data["Year"]
print selected_month
print selected_year
can i have both GET and POST requests in the type field of ajax. im using a form and only when the submit button is clicked im trying to display information based on the data submitted. if request.POST.get('monyrsubmit') does not work.
Help will be appreciated
It's very simple. You have to abstract the events.
function event_page_load() {
function ajax_request('GET')
}
function click_submit_button() {
function ajax_request('POST')
}
function ajax_request(type) {
$.ajax({
type : type,
......
......
})
}
You can also consider the follwoign general guidelines.
GET and POST should be used based on the type of the request to the server
- If you are reading the existing data(without modification) from the server, use GET
- if you are writing/modifying any data in the server, use POST
in jQuery, you can use these simple methods.
For GET requests
$.get(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
for POST requests
$.post(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
Make sure that you have disable the browser caching.
$.ajaxSetup ({
cache: false
});
In django side, you can use request.is_ajax() method to verify the ajax call and you can filter based on request.method property.
You can refer all the possible usages of AJAX with Djano at https://github.com/sivaa/django-jquery-ajax-exmaples

AJAX call not returning -- success function not being executed in Django

I am doing AJAX calls using jQuery in Django. Everything seems to be working fine except that the ajax call is not being returned as a result the success function is not being executed. This is my jquery file
$.ajax({
type: "POST",
url: "/contact_us/",
data: {
'name': name_val,
'email': email_val,
'message': message_val,
'subject': subject_val,
'cc': cc_val,
},
success: function()
{
// display success message and reset values in the form fields
$("#reply-message").html('Your message has been sent!').fadeOut(3000, function() {});
// clear the fields
$("#contact-name").val("");
$("#contact-email").val("");
$("#contact-message").val("");
$("#contact-subject").val("");
}
});
I do not know what to return in the view for an AJAX call so right now I am just returning a dummy message, but it is not working. Here is the views.py
def contact_us(request):
if request.is_ajax():
if request.method == 'POST':
name = request.POST.get('name', False)
email = request.POST.get('email', False)
message = request.POST.get('message', False)
subject = request.POST.get('subject', False)
cc = request.POST.get('cc', False)
recipients = ['abc#gmail.com']
if cc:
recipients.append(email)
from django.core.mail import send_mail
send_mail(subject, message, email, recipients)
return_message = "Sent mail"
return Httpresponse(return_message)
The return_message is dummy, I don't even want to process it in my response. But why is the ajax call not returning, rest everything is working fine and I am also receiving the mail.
I just realsed that I had made a very stupid mistake I have written Httpresponse whereas it has to be HttpResponse. Now it is working absolutely fine
I can't see any immediate problems with your code. If you have Firebug, open up the 'Net' tab and you should be able to see the response code received and inspect the response. You should be getting a '200 OK'.
Another debugging option - try putting in the following:
$.ajax({
type: "POST",
url: "/contact_us/",
data: {
'name': name_val,
'email': email_val,
'message': message_val,
'subject': subject_val,
'cc': cc_val,
},
success: function()
{
// display success message and reset values in the form fields
$("#reply-message").html('Your message has been sent!').fadeOut(3000, function() {});
// clear the fields
$("#contact-name").val("");
$("#contact-email").val("");
$("#contact-message").val("");
$("#contact-subject").val("");
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
That should tell you what the problem is if the Ajax call fails.
The reason your success function isn't being executed is probably because you aren't returning valid xml. jquery checks the data coming in to see if its the right format, aka xml because you are using the ajax call.
Reformat your data, or switch to a different jquery call.
from the jquery website on the ajax call.
success(data, textStatus, jqXHR)Function, Array A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
Edit: Additional info from the jquery site, check your MIME type for the return:
Note: We must ensure that the MIME type reported by the web server
matches our choice of dataType. In particular, XML must be declared by
the server as text/xml or application/xml for consistent results.
This is a bit late, but here it is.
Are you passing a CSRF token with your ajax requests?
To explicitly do this with each request, add the token to the data being sent to the server
$.ajax({
...
data: {
...
csrfmiddlewaretoken: '{{ csrf_token }}',
...
},
...
});
If you want the token to be sent automatically with each request, then you'll have to jump through the hoops described in the link.
Either way, be sure to add django.middleware.csrf.CsrfViewMiddleware to you MIDDLEWARE_CLASSES list in your settings.py file.

jQuery .load() not working in Django

I'm trying to make a call to a url in Django and load the contents of it. Right now I have:
<script>
$('.myClass').load('{% url update_dropdown %}',
{'kind': "Book" },
function(data){
alert(data);
});
</script>
And then the view that update_dropdown refers to is:
#csrf_exempt
def update_dropdown(request):
category = request.POST.get('kind', None)
all =False;
args = {
"label":category,
"all":all
}
return render_to_response('template.html',(args))
However, the .load() won't work for some reason. If I go directly to the URL it shows the data I expect, but .load() won't cooperate. I know it's not a display issue, as the alert will not work (unless I remove the #csrf_exempt, then it alerts the HTML of the error page)
I'm pretty confused as to what's going on, and I've been debugging this and trying to find the error for hours now, any help would be appreciated .
I can get it to work if I make the return type a JSON object and use getJSON(), but I'd prefer not to
Try wrapping it in a ready:
$(document).ready( function () {
$('.myClass').load('{% url update_dropdown %}',
{'kind': "Book" },
function(data){
alert(data);
});
});
Apparently it was an issue with the jQuery uiSelect library I was using. It was out of date and causing errors.