Learner Learner - 1 month ago 11
Javascript Question

get empty request while posting

I was just trying to understand the connection between ajax request with django views but i am getting an error while toggling the switch on and off. I have a simple switch which is used for on and off. When user on the switch, django view should get on value through request.post but it is not able to get the data from my ajax request. What have i missed or done wrong?

def toggle(request):
status = {}
if request.method=="POST":
print('request', request.POST.get('toggle', ''))
status['message'] = 'success'
else:
status['message'] = 'error'
return HttpResponse(json.dumps(status), content_type="application/json")


frontendForm

class App extends Component {
constructor() {
super();
this.state = { toggled: true };
}

getChildContext() {
return { muiTheme: getMuiTheme(Style) };
}

handleToggle = (event) => {
// console.log(event.target.getAttribute('data-isToggled'));
console.log(event.target.value);
this.setState({
toggled: !this.state.toggled
});
axios({
method: 'POST',
url: '/toggle/',
headers: {
'X-CSRFToken': CSRF_TOKEN,
'Content-Type': 'application/json'
},
data:{
toggle:this.state.toggled
},
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}

render() {
return (
<div className="automation" style={automationStyle}>
<form>
<Card style={{ padding: '5em' }}>
<CardHeader
title="Turn on/off light"
titleStyle={{fontSize: '24px'}}
/>
<CardText>
<Toggle
label="On/Off"
id="toggle"
onToggle={this.handleToggle}
data-isToggled={this.state.toggled}
toggled={this.state.toggled}
labelStyle={{ fontSize: '24px' }}
labelPosition="right"
className="toggle"
/>
</CardText>
</Card>
</form>
</div>
);
}

}

Answer

You are posting JSON, but request.POST will only contain form encoded data.

You have a couple of options. The first is to use application/x-www-form-urlencoded as the content type, then you can use request.POST.

Alternatively, you can get the json string from request.body and deserialise it.

data = json.loads(request.body.decode('utf-8'))
toggle = data.get('toggle', '')
Comments