MENU
usePost
Below, we extract out a jQuery AJAX POST function so that we have a function that can pull data from an arbitrary URL path from a server.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><head></head><body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://unpkg.com/react@17/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
const usePost = (path) => { // AJAX POST
const [response, setResponse] = React.useState(null);
const [loading,setLoading] = React.useState(false);
const [error,setError] = React.useState(null); // Runs whenever the dependency path changes React.useEffect(() => {
setLoading(true);
$.ajax({
url: 'http://quizjungle-app.com/' + path,
data: {password:'xxx'},
method: 'POST',
timeout: 0,
cache: false,
ifModified: false,
crossDomain: true,
success: (res, textStatus, jqXHR) => {setResponse(res); setLoading(false); },
error: (jqXHR, textStatus, err) => {setLoading(false); setError(err); }
}); }, [path]); return { response,loading,error };
};
const DisplayUsername = () => {
const {response,loading,error} = usePost('getUsername.php');
return (<div>{loading ? "Loading ..." : <h1> Username : {response} </h1>}
{error && <h2> {error} </h2>}
</div>);
}
ReactDOM.render(<DisplayUsername />, document.querySelector("div"));
</script>
<div></div>
</body></html>