简体   繁体   中英

Javascript event.prevent default not working on wordpress

I am making a custom HTML page to add to a WordPress website. I created a form so I could call an API on the submit of that form and log the response to the console but on submitting the page reloads. How can I fix this?

HTML

<div>
  <div>
  <form id="form">
    <input class="input" placeholder="address" type="text">
    <button type="submit">Submit</button>
  </form>
  </div>
</div>

<script>
const form = document.querySelector('#form');
const addressValue = document.querySelector('.input').value;
form.addEventListener('submit', (event)=>{
  const xhr = new XMLHttpRequest();
  xhr.open('GET', http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=<X1-ZWz171ov3ap3pn_4hjdy>>&address=addressValue);
xhr.onload = ()=>{
 console.log(xhr.response);
}
xhr.send();
event.preventDefault();
})

</script>

I see in this line you haven't put the xhr url request between quotes it maybe do to that.

 xhr.open('GET', http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=<X1-ZWz171ov3ap3pn_4hjdy>>&address=addressValue);

it should be like that

xhr.open('GET', 'http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=<X1-ZWz171ov3ap3pn_4hjdy>>&address=addressValue');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM