not going through the django view through ajax post data - javascript

I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.

I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.

I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.

You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});

Related

Why Ajax is triggering 500 internal error in django?

Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});
If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.

handle form request with ajax in django

i have problem with ajax when i send a request from my form it doesn't get the value from the form
this is my view code
def create(request):
if request.method == 'POST':
msg_text = request.POST.get('the_massage')
data = {}
form = ChatApp(message=msg_text, user=request.user)
form.save()
data['message']=form.message
data['user']=form.user.username
return JsonResponse(data)
else:
return JsonResponse({'nothing coming thrue'})
it shod get the_massage variable but it give me null value
this is my ajax function :
$(function () {
$('#main-form').on("submit" ,function () {
console.log("create function is here");
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: {the_massage:$('#msgbox').val()},
dataType: 'json',
success: function(json) {
console.log(json);
console.log('success');
},
error: function(error){
console.log('we have error');
},
});
});
});
when i console log the value it just come through in the console
please help me
and show me this in the console :
Resource interpreted as Document but transferred with MIME type
application/json: "http://localhost:8000/create/".
Call the function in your event:
$('#main-form').on("submit" ,function (event) {
event.preventDefault();
console.log('submited');
console.log($('#msgbox').val())
created();
});
I see many possibles problems here.
1) just for dev propose, delete #login_required (if you have) from your view and add #csrf_exempt to avoid this problem on dev.
2) Please look inside request.body on your view.
3) if point 1 and 2 doesn't work, please put the server response of this call: POST localhost:8000/create 403 (Forbidden)
this is the write answer : i solve this and its on git hub now https://github.com/mhadiahmed/tinypice

AJAX showing error message

I have one form ,when i click submit button am saving those values and on button click am calling "SaveData() " method.
So when i try to add data and click on submit button and nothing is happening am getting following errors in my browser log.
My onclick function code
function requestReferral() {
var nameperson = $("#namefield").val();
var contact1 = $("#contact").val();
//Till this part working i mean alert is printing .
$.ajax({
url: '/mycontroller/myfunction',
data: 'name='+nameperson+'&contact='+contact1,
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
});
}
my error is
Failed to load resource: the server responded with a status of 500 (Internal Server Error) with my controller url www.example.com/mycontroller/myfunction
First of all, check if your url is ok, for example, if you are using php with codeigniter your url need to be like this:
url: <?php echo base_url()?>mycontroller/myfunction
and second, when I used ajax, I send data like this
postData = {
name: nameperson,
contact: contact1
}
$.ajax({
url: '/mycontroller/myfunction',
data: postData
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}

how to call web service rest based using ajax + jquery

I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.

Not getting proper response from server using jquery?

I am not getting server response from server using jquery.But when I check from server end server end guy get the response .I am sending same value in parameter ,But not getting the response ?
can you please help me out ?
This image is when server person check .It is getting response.
But
http://jsfiddle.net/ravi1989/LsKbJ/4/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax
({
type: "POST",
//the url where you want to sent the userName and password to
url: "http://dd.c-dd.de/cc/REST/Login",
type: "POST",
dataType: 'json',
async: false,
crossDomain: true,
//json object to sent to the authentication url
data: {Application:"61136208-742B-44E4-B00D-C32ED26775A3",
Device:"null",
LoginKind:"0", Password: "1",Username:"qus"},
success: function (t) {
alert(t+"df")
},
error:function(data){alert(data+"dfdfd")}
})
}
XMLHttpRequest cannot load http://isuite.c-entron.de/CentronService/REST/Login. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
Cross Origin Policy restricts connecting to different domain name

Categories

Resources