AJAX Callback not being called - javascript

This is my ajax function:
function ajax_call(call_method,data_to_send) {
logger("function ajax_call. var data_to_send: ");
logger(data_to_send);
$('.clickable save_button').hide()
$.ajax({
type: 'POST',
url: call_method,
data: data_to_send,
success: function(data){
logger("data returned to page after ajax call: ");
logger(data);
$('.error_msg').html("Successfully saved record to database.");
$('.error_msg').fadeIn('slow');
setTimeout("$('.error_msg').fadeOut('slow');",5000); // 5 secs to give user enough time to read
$('.clickable save_button').show()
response_dispatcher(data); // This should contain object type at least
},
failure: function(){
$('.error_msg').html("There was an error while saving this information. Please try again. " +
"If the error persists, please contact us using the contact form.");
$('.error_msg').show;
$('.clickable save_button').show()
},
dataType: 'json'
});
}
And, this is the data sent to my method on the backend:
{
'display_order':"3",
'goal':"dummy goal",
'id':-1,
'object_type':"goal"
}
I've verified within my application that this same data is received.
Here is my Django view method:
#login_required
def update_goal_view(request):
if request.method == 'POST' and request.is_ajax:
# Example data sent from AJAX Request
#qd = {u'display_order': [u'23'], u'object_type': [u'goal'], u'goal': [u'dummy goal'], u'id': [u'-1']}
qd = request.POST
goal = qd.get('goal','')
display_order = qd.get('display_order',99999)
id = int(qd.get('id',''))
object_type = qd.get('object_type','')
# For now, just return something to test populating data to the page
id = '100'
goal = 'goal returned'
object_type = object_type
data = {'id':id,'goal':goal,'object_type':object_type}
return HttpResponse(data,mimetype="application/json")
In Firebug, I see this after the ajax call:
POST http://127.0.0.1/xml/update_goal 200 OK 12ms
The issue is, when that it appears that my success callback is never called... I say that because as you can see from above, I there should be a message written to my logger but there isn't one. I know my logger works because of all the other messages outside of the callback that do get written to my logger.

I don't think Django does automatic serialization for dictionaries. You'll have to serialize them to JSON by hand.
import simplejson
# ...
return HttpResponse(simplejson.dumps(data), mimetype="application/json")

You don't show the code that triggers the ajax_call function. If it's as part of the onclick event for a submit button, or the onsubmit event for a form, the usual cause is that you've forgotten to prevent the form from submitting normally - so the page refreshes and the Ajax call is lost.
Use event.preventDefault() in your event handler to fix this.

Related

How to get checkbox value in AJAX

I want to get the value of my checkbox in Ajax so that I can save it in database as a preference for each of my user. I've never done AJAX before so i'm quite lost about it.
My javascript file :
$(document).ready ->
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'click', (e) ->
E.accounts.changeUnmarkVisibility()
$('#label-letters-visibility').on 'click', (e) ->
if $('#letters-visibility').is(':checked')
$('#letters-visibility').prop('checked', false)
else
$('#letters-visibility').prop('checked', true)
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'change', (e) ->
$.ajax
url: "/backend/accounts/{#id}"
type: 'POST'
data:
isChecked: $('#letters-visibility').is(':checked')
success: (data, status, request) ->
console.log data
E.accounts =
changeUnmarkVisibility: ->
unmarkLines = $('.active-list .unmark').closest('tr')
if unmarkLines.is(':visible')
unmarkLines.hide()
else
unmarkLines.show()
)
My post request send me back a 404 error, I think the error is in my 'Data' option
Yeah Deckerz is right normally you have an ajax call which has a 'Data' option and then a success option. The data is an array/object of values that you want to send.
There are lots of options on the jquery ajax page and it's quite easy to get lost in them. This though is the norm. Done is called after some.php (in this case) has finished and msg has the data that is sent back from msg. Normally you'll want this in a json format. This is good practise for if you want to send back 2 variables. e.g Status (success/error) and ErrorMessage = ""
if you're using php json_encode is the function to use to achieve this.
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I'm not sure I've understood where you're stuck at: it seems to me you've already read the checkbox's value without problems, so I'll assume you don't know what to do with the AJAX call.
The AJAX call is really just a request to your server: you probably want to call a script (pointed to by the URL you pass), with the parameters you need to identify the user and the option, that writes the checkbox's value to the database.
One thing that may be useful to know: you don't need to construct a query string to pass your parameters along with a GET request, you can just pass them in the data parameter of the jQuery.ajax call as a regular JSON object.
AJAX doesn't do that. AJAX returns the value. And then you look at the value to decide what to check. If you are doing this in jquery, then look here: https://api.jquery.com/checked-selector/

Can't see AJAX call in proxy/chrome's dev tools

The following code snippet is used by a coworker to get an URL from a DB and then submit a "virtual" form to that URL.
$.ajax({
url: location.origin + location.pathname + "data/getURL.php",
method: "POST",
data: {
userName: user
},
success: function( data : any, textStatus : string, jqXHR : JQueryXHR){
console.log(data);
var url = (JSON.parse(data)).url;
if(url !== undefined && url !== null && url !== ""){
var sender : HTMLFormElement = document.createElement("form");
sender.setAttribute("action", `http://${url}/receive`);
sender.setAttribute("method", "POST");
var userSenderField = document.createElement("input");
userSenderField.setAttribute("type", "hidden");
userSenderField.setAttribute("name", "user");
userSenderField.setAttribute("value", user);
sender.appendChild(userSenderField);
var passSenderField = document.createElement("input");
passSenderField.setAttribute("type", "hidden");
passSenderField.setAttribute("name", "password");
passSenderField.setAttribute("value", password);
sender.appendChild(passSenderField);
document.body.appendChild(sender);
sender.submit();
Using either Burp Suite or just Chrome's Dev Tools, I can see the call to getURL.php but then I can't see the call to http://url/receive. Why?
For the sake of argument, let's say your ajax call to data/getURL.php succeeded, but delivered bad or unexpected data.
You then end up in your ajax call's success handler.
The success handler immediately creates a new form, populates it with (the bad) data, and submits the form.
This causes a postback to happen.
Chrome's dev tools clear the network panel upon postback by default, also clearing the call to "data/getURL.php", so you never actually saw the call succeed, and could not see in the net panel what it did. (ergo, you had no idea that data/getURL.php delivered the wrong data to you.
if you put a breakpoint in your ajax success handler before it submits the form, you can actually see what is going on.

Django submit a form->redirect to a new page->auto update new page

Ok as the title describes, Im trying to create a webpage(test.html) where in after the form is submitted it should redirect me to a new page(say status.html).And after this page loads It should shows some continuous updates on the submitted task. I was able to accomplish this on a single page , when Im trying to redirect this to a new page Im out of luck.
test.html
<form action="status/" method="POST" id="start-form">
.....
<input type="submit" value="Start" class="tbutton">
views.py
def status_page(request):
print("Inside redirect")
return HttpResponseRedirect(request,'my_app/status.html')
url.py
url(r'^test/status/$', 'status_page'),
jav.js
$('#start-form').on('submit',function(event){
event.preventDefault();
status();
});
function status() {
$.ajax({
url : "status_page/", // the endpoint
type : "POST", // http method
data:{' ': '',}, // data sent with the post req
headers: {Accept: "application/json"},
success : function(json) {
//on success display the rendered page,so what coding is needed here?
},
error : function(xhr,errmsg,err) {
//error handling code }
});
}
On execution the new page is not loaded, but if I bypass javascript then the form action gets executed and the new page rendering through the view happens. But with JavaScript, on success what happens ? how does the return statement from the view get captured in the success and how is the page displayed?
I need to use javascript and AJAX as once the new page is loaded I need to display continuous updates on the same page. So basically how do I implement redirection to a new page with the above code using javascript and Django? Any help will be truly appreciated!
In your views.py, HttpResponseRedirect is used incorrectly. If you want to redirect to a new page, then you should use,
return HttpResponseRedirect('/url-where-you-want-to-redirect/')
As HttpResponseRedirect expects url paramter instead of template name.
See here: https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponseRedirect
Better approach would be to return a JSON response from your status_page view and then in success method of ajax, you can go to next URL:
window.location.href = '/url-where-you-want-to-redirect/';
I hope this helps.

Django, update part of the page

I'm trying to implement a simple code testing server. The client will submit their code on the webpage and we will run it with two test cases (which could take several minutes) and we'll post the results. The page will be simple with a submission form and an output box.
My problem is with updating the output box. I'm looking for the simplest way to implement the output box so that we show results as we run different test cases.
I tried googling for solutions and I found some like socket.io but my experience with ajax and socket.io or even js is very limited so I'm looking for the simplest way to do this.
In case you are looking for code to auto-update a field in HTML here is the code which you could use. The setInterval in JavaScript schedules get_log view to be pulled every 1 second for result of get_log_from_disk method.
urls.py
url(r'^get_log/$', 'myapp.views.get_log', name='get_log'),
url(r'^submit/$', 'myapp.views.submit', name='submit'),
views.py
def submit(request):
## Handle POST
## Your code comes here
return render(request, 'submit.html', {})
def get_log_from_disk():
## Your code comes here
return "Test 1 OK; Test 2 OK"
def get_log(request):
results = get_log_from_disk()
return HttpResponse(results)
in submit.html add
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
[<div id="output_box"></div>]
<script>
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
var my_refresh = setInterval(function() {
$('#output_box').load('/get_log/');
}, 1000); // the "1000"
});
</script>
</body>
You could modify "$('#output_box').load('/get_log/');" to test for status of request and when "204 No Content" is returned you can remove the function (clearInterval(my_refresh );)
see Stop setInterval call in JavaScript
Modify get_log view to return "204 No Content" when there is no more content to be sent.
Here I have uploaded working version
https://github.com/lukaszszajkowski/Django-jQuery-Example-update-part-of-page/tree/master
Some reading
Auto-refreshing div with jQuery - setTimeout or another method?
This could be what you are looking for:
var ajaxForm = function() {
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: '/path/to/django/controller',
// The data sent to the Django view in JSON format
data: JSON.stringify({
formField: $('#body').val()
}),
success: function (data) {
$('#output-box').html(data);
}
});
}
$('#form').on('submit', function (e) {
e.preventDefault();
ajaxForm();
});
The implementation of a Django controller can be something like:
import json
from django.http import HttpResponse
def ajax_view(request):
if request.method == 'POST':
request_data = json.load(request.raw_post_data)
# do something
response_data = {}
response_data['result'] = 'Failed'
response_data['message'] = 'Your test not ended well'
return HttpResponse(
json.dumps(response_data),
content_type='application/json'
)

Using ajaxForm plugin on view that is itself an AJAX response

I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});

Categories

Resources