This question has been flagged

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. 




Avatar
Discard
Author Best Answer

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();
}

},

 


Avatar
Discard