As a little side-project I created a Django-based Web Application. So far I have created my webpage with basic Javascript. I can successfully get data from the database and create an AJAX POST-request via Javascript. Everything is working BUT there is something that really bothers me:
Every second POST-request takes a significantly longer time to reach the server. For example: Request1 returns successful after 29ms. Request2 needs (for the exact same task!) over 300ms. This goes on and is 100% replicable. I have no idea what the reason for that issue is. I hope someone can guess what the root for this problem is.
Image of "request-waterfall" from the developer tool.
Used Code:
//THIS IS THE POST REQUEST IN THE JS-SCRIPT (CLIENT-SIDE)
$.ajax({
type: "POST",
url: '/update_database',
data: {
"habit_name": habits[h].habit_name,
"meta_data": meta_data
},
success: function(result) {
update();
console.log('Successful');
}
});
Server-side handling of the POST-request:
def update_database(request):
post_dict = dict(six.iterlists(request.POST))
habit_name = post_dict["habit_name"][0]
meta_data = post_dict["meta_data"][0]
change_meta_data(habit_name, meta_data)
data = {
"Habits": Habit.objects.all().values()
}
return JsonResponse(list(data["Habits"]), safe=False)
Update: The problem only occurs when I launch the server on localhost. If I runserver on local IP-adress, it works fine..
Related
I've got a few similar POST request on a website. In one case, the request is working (data is stored on the server), but then, there's an unexpected redirect. I send/receive data using jQuery. On the backend, I use the PHP framework Laravel.
Let's say I'm on myapp.dev/clients/123. Then I click the store-data-button and data is sent to/received from the server (Let's assume $('#resubmission_note').val() === 'abc'):
// AJAX request
$('#store-data-button').on('click', function() {
let ajaxRequest = $.ajax({
url: '/resubmissions',
type: 'POST',
data: {
// An integer, some text, and a date
'client_id': $('#id').html(),
'resubmission_note': $('#resubmission_note').val(),
'resubmission_due_date': $('#resubmission_due_date').val()
}
});
ajaxRequest.done(function(returned_id) {
// Removed all code here for testing. Browser still redirecting.
});
});
But then the browser is redirected to myapp.dev/clients/123?resubmission_note=abc.
The network tab in Chrome devtools says
Name:123?resubmission_note=abc
Status: 200
Type: document
initiator: Other
There's data appended in the URL, that should only be the case with GET request, AFAIK. I checked whether some other JavaScript code might interfere, but couldn't find store-data-button or resubmission_note in any unexpected files.
Any advice on how to fix the problem or how to debug it?
I'm really curious if someone can better explain the internal workings of excel's addin caching of javascript functions? I'm running a flask app on my own internal website behind a SSL cert. My addin pulls in this functionfile.html, and makes an ajax call back to mysite:
<script>
// After the Office library builds, it will look for Office.initialize
// which must be passed a function. It doesnt have to do anything though.
Office.initialize = function (reason){
$(document).ready(function(){
registerBindings();
});
}
function getData(){
return Excel.run( function (context) {
// request bindings
var state_nbr = context.workbook.bindings.getItem("state_nbr").getRange().load("values");
// and the rest for the ajax call
return context.sync().then( function () {
$.ajax({
type: "GET",
url: "https://example.com/excel/function",
data: {
"state_nbr": state_nbr.values[0][0]
}
}).done( function (data){
context.workbook.bindings.getItem("test").getRange().values = [["done"]];
return context.sync();
}).fail( function (result){
context.workbook.bindings.getItem("test").getRange().values = [["fail"]];
return context.sync();
});
});
});
}
</script>
When I click my button, I can see the request with the right payload going to example.com/excel/function, which is a flask route that pumps out a bunch of CLI junk (hundreds of logging commands).
What gets weird though, is that after that first click every time I click the button I don't get any new ajax requests, I only get a request for the functionfile.html. But SheetA1 still pops up "done".
I thought this was just storing the results in cache, but even with flask running in debug mode, if I change functionfile.html, say [["done"]] to [["finished"]], no new ajax call is detected in my logs. BUT THE SHEET UPDATES?!
I'm using Google App Engine for a backend service and I'm trying to upload a file using an AJAX post and their Blobstore API. I got that part working. If you are not familiar with the service, is quite simple. Blobstore API uploads is a two step process: You need to get an upload url and then upload into that url.
Now, I'm implementing an editor, medium.com-like.
The thing is this plugin needs an endpoint for the upload. As my endpoint is not static and I need to update that URL each time, I have prepared an API in the backend that responds with a JSON file with that URL. I'm trying to do an AJAX request to get that URL but I'm getting an error, as the POST request is done to bad url.
This is the POST requet:
INFO 2014-10-19 08:58:22,355 module.py:659] default: "POST /admin/%5Bobject%20Object%5D HTTP/1.1" 200 2594
An this is my Javascript code:
function getURL(callback) {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
dataType: "json",
success: callback
});
};
$('.editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: getURL().done(function(json){return json['url']})
},
embeds: {
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});
I guess I'm doing something wrong with the AJAX return, but if I console.log it I get the result I want. I've read this answer and try to apply it, but I didn't manage to get it working.
Thanks for your time and your help ! :)
If someone ever has the same problem this is the way I solved it. If you are reading this and you now a better one, please, every help is appreciated.
var url; // Set a global variable
// Define the AJAX call
function AJAXURL() {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
success: function(response){
// Sets the global variable
url = response['url'];
}
});
};
// Gets a first upload URL doing an AJAX call while everything keeps loading
AJAXURL();
$('#editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: function getURL() {
// makes a request to grab new url
AJAXURL();
// But returns the old url in the meanwhile
return url;
}
},
embeds: {
urlPlaceholder: 'YouTube or Vimeo Link to video',
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});
I have a pyramid application that runs perfectly on a local server, but when I move it over to a web server (Dreamhost), I get the following error:
400 Bad Request:
Bad request (GET and HEAD requests may not contain a request body)
The code in question is the following ajax in Javascript:
function summary_ajax(sName){
$.ajax({
type: "POST",
url: "summary",
dataType: "json",
data: {
'ccg_name': sName,
},
async: false,
success: function(data) {
//alert("In ajax success function") <----------- This never executes
lValues = data.lValues;
lLabels = data.lLabels;
},
});
};
return (lValues, lLabels);
And is handled in views.py:
#view_config(route_name="ccg_map_summary_ajax",renderer="json")
def ccg_map_summary_ajax(self):
sCCG = self.request.POST.get('ccg_name')
fData = open('pyramidapp/static/view_specific_js/ajax_summary_data.js')
dData = json.load(fData)
lLabels = dData[sCCG].keys()
lValues = dData[sCCG].values()
return {
'lLabels' : lLabels,
'lValues' : lValues,
}
I did some testing by placing alert() functions (its slow, because the server only reloads the script every so many minutes), and everything executes fine except for alerts in the ajax call. So it seems that either the post fails, or something goes wrong in the view. Any ideas?
So is there something in this code that works in my local server (in Pyramid) but breaks down in the web server (Dreamhost)?
The file structure is the same in the local and web server. I don't see why it shouldn't, but will fData still open the file for reading?
For anyone else out there, I found the problem:
The path I specified above was a relative path that worked on my system but not on the server because the working directories are obviously different. So instead of using a relative path, I just changed the script to have the correct absolute path.
To find the current working directory path, just enter pwd into terminal.
This question might seem a bit odd, the problem arised when the page went through webtests.
The page uses an AJAX call (async set to true) to gather some data. For some reason it won't swap pages before the AJAX call has returned - consider the following code:
console.log("firing ajax call");
$.ajax({
type: "POST",
url: "requestedService",
data: mode : "requestedMethod",
cache: false,
dataType: "json",
success: function() { console.log("ajax response received") },
error: null,
complete: null,
});
console.log("changing window location");
window.location = "http://www.google.com"
The location only changes after AJAX returns the response. I have tested the call, it is in fact asynchronous, the page isn't blocked. It should just load the new page even if the AJAX call hasn't completed, but doesn't. I can see the page is trying to load, but it only happens once I get the response. Any ideas?
The console output is:
firing ajax call
changing window location
ajax response received
This seems to work fine for me. The location is changed before the code in the async handler executes. Maybe you should post some real code and not a simplified version, so that we can help better.
Here is a demonstration that works as you expect: http://jsfiddle.net/BSg9P/
$(document).ready(function() {
var result;
$("#btn").on('click', function(sender, args) {
setInterval(function() {
result = "some result";
console.log("Just returned a result");
}, 5000);
window.location = "http://www.google.com";
});
});
And here is a screenshot of the result: http://screencast.com/t/VbxMCxxyIbB
I have clicked the button 2 times, and you can see in the JS console that the message about the location change is printed before the result each time. (The error is related to CORS, if it was the same domain, it would navigate).
Bit late but maybe someone else will have the same issue.
This answer by #todd-menier might help: https://stackoverflow.com/questions/941889#answer-970843
So the issue might be server-side. For eg, if you're using PHP sessions by default the user's session will be locked while the server is processing the ajax request, so the next request to the new page won't be able to be processed by the server until the ajax has completed and released the lock. You can release the lock early if your ajax processing code doesn't need it so the next page load can happen simultaneously.