コンテンツへスキップ
メニュー
この質問にフラグが付けられました
1 返信
18701 ビュー

I want to handle a form submission with javascript and ajax so when the CSRF or session expires it won't show 400: Bad Request, but that the page needs to be refreshed or even refresh the page.

My onClick function

function submitForm(){
var form = document.getElementById('form');
var current_url = window.location.pathname;

console.log('Current URL ' + current_url);
console.log('Action URL ' + form.action);
console.log('Form method URL ' + form.method);

var fd = new FormData(form);

$.ajax({
url: form.action,
type: "POST",
data: fd,
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function(data){
console.log('Success! ' + data);
form.submit();
},
error: function(data){
document.getElementById('form_error').innerHTML = "Stran je potrebno osvežit!";
console.log(data);
}

});

}

My controller

@http.route('/my-controller', type='http', auth='public', website=True)
def my_controller(self, **kwargs):
base_value = 0.0
value = 0.0
show = False

data = {
'base_value': base_value,
'show': show,
'value': value,
}
if request.httprequest.method == 'POST':
base_value = request.params['base_value']
value = request.params['value']

# some operations with the gotten the data...

data = {
'base_value': base_value,
'show': True,
'value': value,
}

return request.render('madule_name.template', data)


The Qweb template has a <t t-if="show == True"> that shows the processed data.

Now I'm getting only the ajax error function. 




アバター
破棄
著作者 最善の回答

OK I've got it. Had to change the ajax code dataType to 'html' and so I could finally test the success/error. The @http.route doesn't return the 400 code but the html content to display the text on the site. So the error doesn't work. That's why I checked if there is an ID in the returned html code from ajax.

My success function

success: function(data){
console.log(typeof data);
console.log('Success! ' + data);

var doc = new DOMParser().parseFromString(data, "text/html");
var tmp_element = doc.getElementById('form');
console.log('Element ' + tmp_element);
if (tmp_element == null){
document.getElementById('form_error').innerHTML = "The page needs to be reloaded!";
}else{
form.submit();
}

},

 


アバター
破棄
関連投稿 返信 ビュー 活動
2
9月 23
3791
1
10月 18
6201
0
4月 23
442
1
2月 22
2893
0
11月 16
10852