I have a Django view, named vote. It is protected by a #login_required decorator, and in normal use works completely fine.
I decided it would be a worthwhile idea to start looking into ajax and javascript to make the system more dynamic, and so I implemented something like the below for my first try:
$(function() {
$(".vote").click(vote);
});
var vote = function() {
pk = $(this).attr('pk');
$.ajax({
type: "POST",
data: "pk=" + $(this).attr("pk"),
url: "/link/" + $(this).attr("pk") + "/vote/",
});
};
Which successfully POSTS to the correct URL. When I look at the output with firebug, I find I'm getting 500 errors. I've included the snipped from https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax into my pages, which I had thought would solve the CSRF issue, however it appears not to have done so.
Wondering whether I'm missing something obvious!
Thanks!
Turns out the way that I solved this was to tidy up the above:
var vote = function() {
pk = $(this).attr('pk');
data = {
'pk': pk
};
$.ajax({
type: "POST",
data: data,
url: "/link/" + pk + "/vote/",
});
};
Thus tidied, I then checked out the view, and discovered that it was not pulling the correct value out of the DataDict passed to it by ajax, which was where the 500 error was coming from.
I had previously encountered a 403 due to the CSRF issue, for those wondering how to solve that, I simply used the script mentioned in the question above, saved in a 'csrf.js' file in the /static/js/ directory of my app, and then included that as one of the scripts, which then solved that issue.
Related
I try to store the data from a graph with jQuery but I always get a 400 Bad request.
The problem is the data_series variable isnt just an array of integers but much more. This is unchangeable since it is necessary for my chart generation to be like this.
A litle piece of it to show you what I mean:
data_series[0][data][0][]:1389975624000
data_series[0][data][0][]:91
data_series[0][data][1][]:1390003200000
data_series[0][data][1][]:446
data_series[0][data][2][]:1390089600000
data_series[0][data][2][]:429
.....
My Jquery post looks like this,
$.ajax({
url: "{{ url_for('save_graph_to_session') }}",
method: "POST",
data: {
data_series: data_series
},
success: function(data) {
console.log('Saved to session')
}
});
On flask side I read it like this, and put in a session:
#app.route('/save_graph_to_session', methods=[ 'POST'])
def save_graph_to_session():
session['data_series'] = request.form['data_series'];
return "saved"
I've tried to post with 'data_series[]:' data_series, didn't work out either.
EDIT:
Maybe the solution lies within the way to request, so :
Is there a way to request in flask that ignores the fact that this is an array of arrays
this is the way one can do this:
session['data_series'] = request.form.getlist('data_series[]');
So I have searched the forum for similar questions unfortunately I have been unlucky to find an answer that suits my problem.
I am trying to make an ajax call in my jquery using the following code;
function submitForm(formData)
{
$.ajax({
type: 'POST',
url: 'addEvents.php',
data: formData,
dataType:'json',
cache:false,
timeout:7000,
success: function(data){
$('#addEventsForm #response').removeClass().addClass((data.error === true) ? 'error' : 'success').html(data.msg).fadeIn('fast');
if($('#addEventsForm #response').hasClass('success')){
setTimeout("$('#addEventsForm')",5000);
}
},
error:function(XHR,textStatus,errorThrown)
{
$('#addEventsForm #response').removeClass().addClass('error').html('<p> There was an <strong>' + errorThrown +
'</strong> error due to <strong>'+ textStatus +'</strong> condition.</p>').fadeIn('fast');
console.log(arguments);
//alert(XMLHttpRequest.responseText);
},
complete:function(XHR,status)
{
$('#addEventsForm')[0].reset();
}
});
}
But I am getting a sysntax error. I have tried doing this to see what errors I get in chrome
console.log(arguments);
but the responseText in the [Object, "parsererror" , SyntaxError] node seems to display the entire html of the page that contains the form where I am inserting the record.
I am still getting my feet wet in ajax so I am not yet a pro in absolutely understanding the error messages and what they mean.
Is the above js/jQuery code located on the addEvents.php page -- that is, on same page that you are posting the AJAX to? (In other words, are both the form/ajax and the AJAX destination on the same physical PHP page?)
If so, you will get exactly what you describe: the entire HTML of the page spat back at you.
AJAX, by design, must post to a different physical page on the server. That's just how it works.
Also, FWIW, note that dataType: 'json', refers to the data being returned, not the data being sent. Perhaps you already know this, but it is a common misunderstanding so is worth mentioning.
Edit:
As Felix points out, this answer is not technically perfect. It is possible to post AJAX code to the same page, but you must specifically allow for that. Perhaps FK or another could edit this post to add an example of what that additional code would look like?
Jquery function:
$(document).ready(function() {
$(".checkbox").click(function(){
var selVal = $(this).val();
$.ajax({
type: "POST",
url: 'remove_task.php', //This is the current doc
data: ({sel: selVal}),
success: function(data){
//alert(selVal);
console.log(data);
}
});
});
});
My PHP function in remove_task.php:
function remove_selected_task()
{
$task_to_remove = $_POST['sel'];
echo $task_to_remove;
}
if (isset($_POST['remsubmit']))
{
remove_selected_task();
}
Not able to pass this successfully. Can anyone help me out? Thanks in advance.
try to pass the $_POST variable into the function for ex:
remove_selected_task($_POST['sel']);
function remove_selected_task($task_to_remove)
{
echo $task_to_remove;
}
Start by trying to diagnose the issue using the browser dev tools. Press F12 to get the dev tools panel, and go to the Network tab.
Now click your checkbox and watch for what happens...
Does the network panel show the request being made to remove_task.php?
If not, then there's a problem in your javascript where it registers the click event. Maybe the selector is wrong or something like that.
If the network panel does show the request being made, click on it there to get more info about it, and then look at the request data and the response data.
Does the request send the data you're expecting it to, and in the correct format?
If not, then you'll need to debug your Javascript to see why. I can't really help with that unless I actually see the data, but you should be able to get an idea of what the problem is by what's being sent incorrectly. Maybe the checkbox value is wrong?
If it does look right, then move on to the response.
Does the response contain the data you expect?
If it has a 404 response code, then your URL is incorrect. Maybe the path is wrong?
If the response includes an error message, then you should be able to debug the PHP from that. It'll have the relevant line numbers in it, so that should be enough to get you going.
If the response is blank, then your PHP code isn't sending anything back: Maybe a syntax error (with error suppression), or maybe the program ends before it gets to echo the data. Either way, further debugging in the PHP will be required.
That's about as much help as I can give, given the info you supplied in the question. I hope that's enough to get you started.
This will solve your problem, and next time add the full code in your question.
you check if "remsubmit" exists in your php file, but you don't send it ! This should work by modifying the line data: ({sel: selVal}) as below :
$(document).ready(function() {
$(".checkbox").click(function(){
var selVal = $(this).val();
$.ajax({
type: "POST",
url: 'remove_task.php', //This is the current doc
data: {sel: selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
console.log(data);
}
});
});
});
I'm working on a scraper of my bank statements with CasperJS, so far I've managed to login and get to the statements page. I accomplished to get the table with the first page of the statement, but I need to get it complete.
The bank's web have the option to export to a .txt file (sort of a CSV actually), but in order to download it I have to be able to download the file that comes as an attachment in the response header of a POST request when I submit a form by clicking a button.
So I figured that I could do the POST via AJAX, get the response and output it. I tried running the code on the firebug console and it works, but for some reason it just doesn't work in CasperJS.
Btw, I have tried using --web-security=no , still doesn't work
This is how I'm trying to do it:
this.then(function() {
eurl = "http://bankurl.com";
response = this.evaluate(function() {
params = $("#lForm").serialize();
$.ajax({
type: "POST",
url: eurl,
data: params,
success: function (data) {
return data.responseText;
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
I wasn't able to test this with the code you provided, but it looks as though you just aren't returning anything back from the evaluate().
return __utils__.sendAJAX(url, 'POST', params);
You would probably also need to call CasperJS with the following:
casperjs --ignore-ssl-errors=true /path/to/script.js
Well, after struggling finding a way to solve this I finally did, I just put the ajax call inside a try catch and found that the error was that it wasn't reading the eurl variable (I declared it outside the evaluate). I put it inside and it worked. Thanks for your help
I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers