I want to submit a react form making an ajax call to php server. I have used react hook but since I am new to it, I cant not figure out error actually.
function App() {
const [name, setName] = useState("");
const [result, setResult] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
const handleSumbit = (e) => {
e.preventDefault();
const form = $(e.target);
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success(data) {
setResult(data);
}
});
};
return (
<div>
<form
action="server.php"
method="post"
onSubmit={(event) => handleSumbit(event)}
>
<label htmlFor="name">Name: </label>
<input
type="text"
id="name"
name="name"
value={name}
onChange={(event) => handleChange(event)}
/>
<br />
<button type="submit">Submit</button>
</form>
<h1>{result}</h1>
</div>
);
}
const header4 = ReactDOM.createRoot(document.getElementById('header4')) ;
header4.render(<App />);
I have skipped the import part. The above code runs without any error but when I click the button, nothing happens.
This is my php code:
<?php
header('Access-Control-Allow-Origin: http://localhost:3000');
$user = $_POST['name'];
echo ("Hello from server: $user");
?>