I'm having a weird problem and any help would be appreciated..
Actually the code could be written better I'm sure, so maybe I'm just doing something fundamentally wrong here but even if that's the case I'd like to know why this doesn't work.
So I have a form with input fields like this in component AddHouse:
<form name="myForm" encType="multipart/form-data" onSubmit={this.uploadForm}>
<input type="text" name="city" placeholder={condition ? 'City' : this.props.placeholders.city} {...(condition ? {required:true} : {})}></input><br></br>
<input type="text" name="address" placeholder={condition ? 'Address' : this.props.placeholders.address} {...(condition ? {required:true} : {})}></input><br></br>
That's only a small part of the form. It has multiple similar fields and the form DOES WORK when I upload it from the mainpage, but I would also like to send this form from a modal I have made, but when I send it from the modal to the PHP file to be uploaded into the database, the $_POST array only contains the keys.. The conditions are there to give the modal the house data as placeholders and to make fields not required and both of these conditions work..
When the form gets uploaded, this function is called in AddHouse component:
uploadForm(e){
e.preventDefault();
this.setState({loading: true, errorMsg: false, successMsg: false});
var form = document.forms.namedItem("myForm");
var formData = new FormData(form);
this.props.addHouse(formData, function(bool){
if(bool){
form.reset();
this.setState({successMsg: true, errorMsg: false, loading: false, preview: null});
}
else{
this.setState({errorMsg: true, successMsg: false, loading: false});
}
}.bind(this));
}
addHouse in Parent component:
addHouse(formData, fn){
var dashboard = this;
var request = new XMLHttpRequest();
var script = this.state.modal ? "php/edit_house.php" : "php/add_house.php";
this.setState({loading: true});
request.open("POST", script, true);
request.onreadystatechange = function(){
if(request.readyState === 4){
if(request.status === 200 && request.responseText == 1){
dashboard.setState({loading: false});
fn(true);
}
else{
console.log(request.responseText);
dashboard.setState({loading: false});
fn(false);
}
}
};
request.send(formData);
Thanks if you took the time to read this wall..
Alright I solved this! I only had to refer to the form by a different name, so I changed the following lines and it works:
var form = document.forms.namedItem("myForm");
To
var form = this.props.placeholders === undefined ? document.forms.namedItem("myForm") : document.forms.namedItem("myForm2");
And added a condition to the render method to change the form name depending on where it's rendered:
form name={condition ? 'myForm' : 'myForm2'}