-1

I took a code from stackoverflow and created a "index.htm" page where it will also send a json data from html page to php here it is "test.php"

When I am trying to submit the data and seeing in web develop tool I am always getting this error:

jquery.min.js:4 Access to XMLHttpRequest at 'file:///C:/Users/1701053/Desktop/ClientServer%20demo/test.php' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Here is my code

<!DOCTYPE html>
<html>

<head>

 </head>
<body>

<form id="form" action="" method="post">
 Name: <input type="text" name="name"><br>
 Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>

<script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> 
</script>
 <script>
   $(document).ready(function(){
      // click on button submit
       $("#submit").on('click', function(){
          // send ajax
           $.ajax({
              url: 'test.php', // url where to submit the request
              type : "POST", // type of action POST || GET
              dataType : 'json', // data type
              data : $("#form").serialize(), // post data || get data
              success : function(result) {
                  // you can see the result from the console
                  // tab of the developer tools
                  console.log(result);
              },
                 error: function(xhr, resp, text) {
                  console.log(xhr, resp, text);
               }
             })
      });
   });

     </script>
     </body>
     </html>

Test.php

<?php

   // this is just a test
    //send back to the ajax request the request

   echo json_encode($_POST);
?>

Note: this is not my own work I am using it as a reference to understand how to actually send a Json object to server using javascript only

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • 2
    Possible duplicate of [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – franiis Aug 16 '19 at 05:20

1 Answers1

0

Simply we can say that XMLHttpRequest() not works when URL starts with file:///. Also $.ajax() function would no useful.

XMLHttpRequest() works with http:// or https:// URLs, So try to run this page from any Web Server like XAMPP

Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30