دنبال کننده ها

۱۳۹۶ مرداد ۲۸, شنبه

ajax - React+Django sending forms and recieving responses

[ad_1]



I have django as backend and I use it also on the fronted with one exception: one big input form is made in react. After submiting the form, some calculations are made and the server returns pages of text including css, javascript (event listeners,bootstrap popovers, etc. ). The following gives me headaches: how to sumbit the form and recieve full page results in this setup?



What I am currently doing when the user hits the submit button is to assemble the form data to a dict and then it goes to the server via ajax. All of this happens in the react part (see example below). If I don't send it as ajax I can not fill the error handlers in the react form. If I do send it via ajax I also need to handle the valid result via ajax.



So, if there is errors, missing fields or whatever the server responds and it gets fed to the react form. If everything is okay the server sends a full html page response and I replace the whole page with it. This of course is very suboptimal and besides weird-feeling solution it also creates more technical issues, like disrupting event handlers and the need to recreate those handlers in react (including popovers that have nothing to do with the form).



This function handles sending form data and recieving the response:



calculate(dict,target_url) 
return this.handleCalculate(when(request(
async: true,
url: target_url,
method: 'POST',
type: 'html',
data: dict //dict with assembled form values
).then(function(data)
//if returned data has declared doctype it's a full page
//and can be pasted in the browser
if (data.indexOf('<!DOCTYPE html>') > -1)

var parser = new DOMParser();
data = parser.parseFromString(data, "text/html");
var x = data.getElementById('content');
document.getElementById('content').innerHTML = x.innerHTML;
//below one of many technical issues caused by this
//solution, here the form get's reintialized, without this
//there would be no form available after calculation
ReactDOM.render(<Form />, document.getElementById('react-form'));
//this is to reinitialize the popovers in the
//returned html pages
window.createEvents();
window.scrollTo(0,0);

else
//if there is no doctype declared the response contains erros and is fed to error routines
FormActions.calcFailed(JSON.parse(data));

).catch((err) =>
var errResp = err.response;
if (typeof(errResp) == 'object')
FormActions.calcFailed(errResp);
else
alert("An error occured, please check your inputs");


)
));



Form state is relevant only as long there is no valid response. So, I need the form intact with state as long as the user is filling it in or recieiving erros from the server. When the user submits the form and everything is ok, I don't need the previous state and it can be all reseted. So, my question is how to do this cleaner?




[ad_2]

لینک منبع