Přejít na obsah
Menu
You need to be registered to interact with the community.
This question has been flagged
1 Odpovědět
18233 Zobrazení

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
Zrušit
Autor Nejlepší odpověď

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
Zrušit
Related Posts Odpovědi Zobrazení Aktivita
2
zář 23
3285
1
říj 18
5722
0
dub 23
442
1
úno 22
2543
0
lis 16
10467