In my webpy app I have a function:
def POST (self):
signal = web.input()['signal']
if signal == 'next':
errMessage = self.cinstall.testConnection()
print signal
print errMessage
return errMessage
According to the python console it works correctly; it receives and returns strings as I expect it to.
In a template I have a script like this:
<script src="/static/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$$(function() {
var value = $$('#continue').attr('value');
$$("#continue").click(function(){
jQuery.ajax({
type: "POST",
data: {signal : value},
success: function(html) {
jQuery('#errmessage').html(html).hide().fadeIn(1500);
},
});
});
});
</script>
I know that the request is successful, because if I put an alert in the success handler it works well, but the function jQuery('#errmessage').html(html).hide().fadeIn(1500); doesn't execute. I have a <p> tag with id=errmessage in my template.
So I have several questions:
Why it doesn't work?
Can I isolate the data recieved from POST in JS for further iterations and if statements?
Can I put if statements inside the jQuery.ajax success function?
Unfortunately, jQuery API gives limited info about success().
Related
I am trying to execute some ajax requests in the pdf.html file for a ruby app using WickedPDF. I have the javascript outputting some append statements to keep track of the functions reached.
The first ajax call is successful, as I have outputted the json result in the pdf file. However, in that same success call, I call another function, which for now, I only have it outputting an append statement to indicate it is being executed. However, it does not happen. Any ideas?
HTML:
<div id="data"></div>
Javascript:
<script>
function getData(data) {
$('div#data').append('<p>getData function called</p>');
}
</script>
<script>
$(function() {
var assays = '';
$.ajax({
type: 'GET',
url: 'http://www.url.com/data.json'
})
.done(function(result) {
$('div#data').append('<p>First ajax call called!</p>');
data = result['DataList']['list'];
getData(data);
})
.fail(function() {
$('div#data').append('<p class="center">Data is unavailable.</p>');
});
});
</script>
Thanks for your help.
wkhtmltopdf will by default stop slow running JavaScripts if they are delaying rendering.
Try experimenting with the following options: --no-stop-slow-scripts, --javascript-delay <msec>
More options are listed here
In this ajax call, I am calling a servlet in which I set an attribute value.
Now, once I receive the response I am trying get the value of the attribute.
I am struggling for the getAttribute value code.
<script type="text/javascript">
$('#PartNo').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
varPartCode = $('#PartNo').val();
$.ajax({
type: "Post",
url: "submit",
data: "PartCode="+varPartCode,
success: function(result){
alert($(this).attr("DescAttr"));
}
});
}
});
</script>
I got the below function from the net. But it is not working. Requesting your help in this.
$(this).attr("DescAttr")
Below is my code for setting the attribute value in servlet.
String varPartDescription = descBean.getPartDescription();
request.setAttribute("DescAttr",varPartDescription);
this in the success function isn't an HTML element. It does not make sense to pass it as an argument to the jQuery function.
Java attributes have nothing to do with HTML attributes. Setting an attribute on the Java request object isn't going to give any data back to the browser.
You need to put the data in the response and then read it from the argument to the success function in JavaScript that you have named result.
For example (and I don't do Java so I just cribbed this from the first tutorial I found on Google):
res.setContentType("text/plain");
PrintWriter pw=res.getWriter();//get the stream to write the data
pw.println(descBean.getPartDescription());
and
success: function(result){
alert(result);
}
For more complex data, consider outputting JSON instead.
Okay here's my problem.
I have an html page that has a javascript variable initialized in it.
<html>
<script>
MyVaribale = "Random Data";
</script>
<!-- Then I include an external js file to handle the processes in this html file -->
<script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script>
</html>
Now, inside that script. I used the MyVaribalevarible in one of the ajax request there, like this :
$(document).ready(function() {
$.ajax(
url : '/some/random/url',
data : { MyVariable : MyVaribale }
etc ...
);
});
So, on page load, that ajax code is executed immediately.
In the url specified above, i checked for the existence of MyVaribale, then flag an error that it is a required value if it doesn't exist.
Backend code like this (in Perl):
my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax.
if ( $MyVariable ) { # Test if it exists
# Display something
}
else {
# Flag an error, which is my problem
}
Now I am sure that in the html page, that variable is always populated (yes 100% sure). But I always get flag errors that that value doesn't exist in my backend code (url above).
So question,
Does ajax have some issue with document.ready, maybe it executes before the variable has finished assigning a value? Any idea why this happens? Because sometimes my ajax request is successful, sometimes it's not
Thanks
The syntax of your ajax call is not correct. Have a look here and then try this code (note the addition of {, } and ,):
MyVaribale = "Random Data";
$(document).ready(function() {
$.ajax({
url: '/some/random/url',
data : { myVariable : MyVaribale }
});
});
Did not you try out some complete ajax calls? Like this.Sometimes no need to use JSON.stringify for MyVariable.
$.ajax({
url: "/some/random/url",
type: 'POST',
dataType: 'json',
data: JSON.stringify(MyVaribale),
contentType: 'application/json',
mimeType: 'application/json'
}).done(function(data) {
}).fail(function(error) {
}).always(function(){
});
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'
)
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.