Home > Net >  React hook failed to call php server via ajax
React hook failed to call php server via ajax

Time:06-20

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");
?>

CodePudding user response:

I verified that your react code is working fine, and if you check in network tab in developer tools in any browser, there is a POST request going to http://localhost:3000/server.php. The reason you see nothing happening is that this url might not be what you server is listening to. If we don't provide the absolute url, relative path causes your request to be handled by react at http://localhost:3000/server.php and it errors out as there is no resource to handle it. To fix the issue, change form action attribute to:

http://<serverhost>:<serverport>/server.php

This should work for localhost based servers. For production applications, you might consider making POST request to a server instead of form submission. Please try and let me know if this fixes your issue.

  • Related