Home > Blockchain >  XMLHttpRequest and Fetch request to PHP file not working Svelte
XMLHttpRequest and Fetch request to PHP file not working Svelte

Time:11-24

I am unable to grab information from a PHP file on an external host using Svelte.

Oddly, though, the XMLHTTP request works when linking to a text file hosted on the web.

Here is my JS code:

   <script>

let content = "";

function httpGet()
{
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", "https://www.kayasuleyman.co.uk/form.php?email=example");
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlhttp.send();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
          content = this.responseText;
        };
      }
    }

  

</script>

And here is the HTML:

<div id="demo">
  <button on:click={httpGet}>Submit</button>
  <p>Output: {content}</p>
  </div>

The output from my PHP file, which should simply be "example", returns nothing. I am baffled by this problem, and using a fetch statement also does not work.

Any ideas?

CodePudding user response:

Try to add this to the top of your php file:

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");
  • Related