Why does my Django request.method does not match POST - django

$.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

Related

How to handle multiple actions in Django-Template

I have created a web app in which page which consist of choose file input and Now I need to preprocess the data with one button and that preprocessed data should be used for next button called forecast to show the result in that page.Is it possible with Django.
Does it compulsory to take any action in page with url changes in django?
The question is not completely clear, but from what I understand you can use Ajax. On first button click send an ajax request, process it in the view logic, send the appropriate data using maybe JsonResponse, and in the success block of your ajax request set the appropriate data for your forecast button using jquery. Something like -
$.ajax({
url: <url_of_data_processing_logic>,
type: 'post',
data: <required data>,
dataType: 'json',
success: function (data) {
$("#<forecast_button_Id>").html(data.forecast_html);
},
error: function (e) {
console.log(e);
}
});

How to get the Rendering Datasource after an AJAX postback

I have the ajax code below:
$.ajax({
url: 'api/sitecore/SmartAds/GetSmartAddsItem',
type: "GET",
dataType: "json",
success: function (result) {
alert(result);
}
});
The problem is the Sitecore.Context.Item.ContextRendering is null in the ajax call.
Question: How do I get the rendering datasource during AJAX call?
I found the below code here, but I am having trouble getting it to work:
public class FormModelBinderProvider : Dictionary, IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
var binders = from binder in this
where binder.Key.IsAssignableFrom(modelType)
select binder.Value;
return binders.FirstOrDefault();
}
}
I am getting an error that says that Dictionary requires 2 type arguments.
Any help is appreciated.
The first issue with your code is that the AJAX request you are making is a 'GET' request rather than a post, so it won't be passing in the hidden field value for the datasource item. To clarify, the article covers situations where a form is posted back, not AJAX GET requests.

Return in Http Response and Html page but its not showing on the browser in Django

I have created a page on locahost:8080/kar, i am sending an ajax POST request to different Url(same domain) i.e. locahost:8080/kar/create_post there i am returning an HTML response but its not showing on the browser as the URL is still on locahost:8080/kar, the data is stored in the database.Where as in the developer console i can see the response in the network tab .When i redirect it is also showing the same thing in the developer console
Why i am not able to change the URl and see the response ?
It's a client side thing, that means the desired behaviour needs to be implemented with javascript. Django is functioning normally here.
When you're sending Requests via AJAX, that is a non blocking request with the XMLHttpRequestheader set, your browser won't trigger the chain of events that occurs when a server side script evaluates your form and returns something, which may be data, or a redirect, depending on whether the form validated or not.
A typical AJAX call in jQuery looks like this:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
If you would like to perform some actions when the request you sent by XMLHttpRequest returns, you could attach that to the appropriate success handler:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
If you need to redirect to the URI that is returned as a redirect from your server you can get the redirect URI from the response in the success handler:
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
If you would like to modify the URL in the users bar without reloading the page you could have a look at this question.

Tastypie ajax POST obj_create - How to return json

Im sending a POST that creates a new User, and that works.
My question is how do I get back for example the pk of the created user to the ajax response?
$.ajax({
url: 'http://localhost:8080/api/v1/create/user/',
type: 'POST',
contentType: 'application/json',
data: '{"uuid": "12345"}',
dataType: 'json',
processData: false,
success: function (r) {
console.log(r)
},
});
def obj_create(self, bundle, request=None, **kwargs):
try:
user = User.objects.create_user(bundle.data['uuid'],'1')
user.save()
except:
pass
return bundle
you can set always_return_data=True within your UserResource's Meta and on POST and PUT request it will return the created object back.
From the docs
always_return_data
Specifies all HTTP methods (except DELETE) should return a serialized form of the data. Default is False.
If False, HttpNoContent (204) is returned on POST/PUT with an empty body & a Location header of where to request the full resource.
If True, HttpAccepted (202) is returned on POST/PUT with a body containing all the data in a serialized form.
Each resource has dehydrate method. You can use it to add any data to response. Here are the docs - http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-values
You could either use the Location header (set by Tastypie by default) or you could try to make Tastypie send the newly created entity back. I believe the first one is simpler. You may also take a look at related SO question: Is it ok by REST to return content after POST?
First you need to slightly modify jQuery XHR objects,
// Required for reading Location header of POST responses.
var _super = $.ajaxSettings.xhr;
$.ajaxSetup({
xhr: function () {
var xhr = _super();
var getAllResponseHeaders = xhr.getAllResponseHeaders;
xhr.getAllResponseHeaders = function () {
var allHeaders = getAllResponseHeaders.call(xhr);
if (allHeaders) {
return allHeaders;
}
allHeaders = "";
$(["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma", "Location"]).each(function (i, header_name) {
if (xhr.getResponseHeader(header_name)) {
allHeaders += header_name + ": " + xhr.getResponseHeader(header_name) + "\n";
}
});
return allHeaders;
};
return xhr;
}
});
This is required because (after jQuery $.ajax docs):
At present, due to a bug in Firefox where .getAllResponseHeaders() returns the empty string although .getResponseHeader('Content-Type') returns a non-empty string, automatically decoding JSON CORS responses in Firefox with jQuery is not supported.
A workaround to this is possible by overriding jQuery.ajaxSettings.xhr as follows:
Then you can read the header in the successCallback, like so:
successCallback: errorAwareCall(function (data, t, textStatus, XMLHttpRequest) {
var loc = XMLHttpRequest.getAllResponseHeaders();
var pk = parseInt(loc.match(/\/(\d+)(\/)*/)[1]);
// Do something with the PK
})

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.