0

Currently, I am trying to create a formResult when Submit is called, but it is some I think I want to do with GetData. Is this just something I can place after getData?

How do you suggest I reformat this?

const form = document.getelementbyid('Submit')
const formResult = new FormData(form);
const url = '/' + encodeURIComponent(formResult.get("search")); 
const button = document.getElementById('search');
const sendHTTPSRequest = (method, url, data) 

    function Submit(e) {
      e.preventDefault();
      alert(button.value)
    }
    return fetch(url, {
      method: method,
      body: JSON.stringify(data),
      headers: data ? {' Content Type': 'application/json'} : {}
    }).then(response => {
      if (response.status >= 200) {
        return response.jsomn ();
      }
      if (response.status >= 500) {
        return response.json().then(errResData => {
          const error = new Error ('Something went wrong');
          error.data = errResData;
          throw error;
        });
      }
      return response.json ();
      });
    
   
const getData = () => {
  sendHTTPSRequest('GET', '/url').then(responseData => {
    console.log(responseData);
  });
};

button.addEventListener('search', getData)
Terry
  • 63,248
  • 15
  • 96
  • 118
Max.California
  • 207
  • 1
  • 2
  • 7
  • 3
    `return response.jsomn ();` will not work, spelling matters in programming – CertainPerformance Jan 02 '21 at 23:38
  • Also, `if (response.status >= 500)` will never be executed (because if it's 200 or above, you return before getting to that statement). Also, `sendHTTPSRequest` is not a function, there are syntax errors in the way you wrote it. Also, you're not catching the errors (`.then().catch()`). An error 500 will likely not go through your `then` – blex Jan 02 '21 at 23:40
  • @blex Should I use ```xmlHttpRequest``` instead? and so change the res status to ```(response.status <= 500) ```? – Max.California Jan 02 '21 at 23:45
  • No, `fetch` is fine, the way you wrote it is just not quite right. I was wrong about the status 500, by the way, it does go through the `then`. But a nicer way to check that the status is in the `200-299` range would be `if (response.ok) {/* ok */} else {/* error */}`. [Using fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) – blex Jan 02 '21 at 23:53
  • @blex awesome, thanks! But if I want the function to be triggered on ```getData```. how should I format this? Does it matter? – Max.California Jan 02 '21 at 23:57

0 Answers0