8

I have a html file on my localhost with a form and jquery/ajax which handles the post data. A simple php script looks up the data in a mysql database table

This is the main part:

// $.post('lookup_update.php', $(this).serialize()) //<- local part which works
   $.post('http://www.example.com/projectX/lookup_update.php', $(this).serialize()).done(function (data)
                            { etc.

But when I point to the online lookup_update.php I get the following error message in chrome

XMLHttpRequest cannot load http://www.example.com/projectX/lookup_update.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

As I understand it I need to use

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

for php. But when I add this to example.com/lookup_update.php, the file gives a 404 when the localhost file tries to call it.

I also tried to add the following to my Xampp apache config file

Header set Access-Control-Allow-Origin "*"

How do I correctly enable cross-origin resource from my local XAMPP setup??

[EDIT] This is my simple form on my localhost

<!--Begin form-->
    <div id="form" class="result">
        <form method="post" id="reg-form"  class="form-horizontal">
            <div class="controls">
                <input type="text" name="code" id="code" placeholder="Code"  class="form-control input-lg" />      
            </div>
        </form>
    </div>
    <!--End form-->

With the following form jquery code

    <script type="text/javascript">
            $(document).ready(function ()
            {
                $(document).on('submit', '#reg-form', function ()
                {
                    var tmpCode = $("#code").val();

//                    $.post('lookup_update.php', $(this).serialize())
                      $.post('http://www.example.com/projectX/lookup_update.php', $(this).serialize())
                            .done(function (data)
                            {

                                $("#reg-form").fadeOut('slow', function ()
                                {
                                    $(".result").fadeIn('slow', function ()
                                    {
                                        console.log("inner test " + tmpCode);
                                        $(".result").html(data);


                                        setTimeout(function () {
                                            location.reload();
                                            $('input').val("");
                                        }, 3000);


                                    });
                                });
                            })
                            .fail(function ()
                            {
                                alert('fail to submit the data');
                            });
                    return false;
                });


            });

        </script>

[EDIT 2]

OK, i don't think it has to do with the online lookup_update.php file, as I am using this to test in another file

            var testXHR = $.post("http://www.example.com/projectX/lookup_update.php", function (data) {
            alert("success:" + data);
        })

And in the alert popup window I see the expected data

georgeawg
  • 48,608
  • 13
  • 72
  • 95
alex
  • 4,804
  • 14
  • 51
  • 86
  • URLs in the question are rather confusing. Is it `http://www.example.com/projectX/lookup_update.php` `example.com/lookup_update.php`, or `http://www.example.com/projectX/index.php` ? – Alex Blex Jan 19 '16 at 09:39
  • @AlexBlex I meant the same file I rename index.php to lookup_update.php. It is this file that is online and which I like to call locally – alex Jan 19 '16 at 09:44
  • Could you update the question with correct file names, a snippet of the code where you add `header`, and output of the command `curl -v http://www.example.com/_correct_url_here -o /dev/null` – Alex Blex Jan 19 '16 at 09:53

4 Answers4

11

If you want to allow CORS in the httpd.conf file this is what worked for me:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "X-Requested-With, Content-Type, X-Token-Auth, Authorization"

Put it below the Listen 80 line in the httpd.conf file.

When I used only Header set Access-Control-Allow-Origin "*", GET requests worked, but POST didn't.

The enviroment it was tested is Windows 10 on Apache server using XAMPP. Apache is hosting a Laravel project.

ViníciusPJ
  • 524
  • 5
  • 13
8

You have to write below code at the beginning of your lookup_update.php

header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

Instead of * you can write just Ip address.

OR

First you have to check where is problem either on localhost or other server.

Try this code : If you getting some data in alert then problem is on localhost else on other server.

$.post( "test.php", function( data ) {
alert( "Data Loaded: " + data );
});
Monty
  • 1,110
  • 7
  • 15
  • sounds promising, but as I am calling from my localhost should I use the IP address of my current location? I mean when I take my computer to another place I get another IP addresss, correct? Oh btw what suprises me is when I google "my current ip" I get 2001:980:cb55:1:xxx:xxxx::25c9 is this IP per computer and can I use this one as well? OH, leaving under a rock this is IPv6 and not good old xxx.xxx.xxx.xx??? – alex Jan 19 '16 at 09:32
  • If you are getting data from different server then you can use IP address. On localhost there is not need. – Monty Jan 19 '16 at 09:38
  • I tried `header("Access-Control-Allow-Origin: 2001:980:xxxx:1:ec29:xxxx:fe4c:25c9");` at the beginning of my example.com/projectX/lookup_update.php but still I get the warning – alex Jan 19 '16 at 09:40
  • First let me clear one thing. you are calling ajax from localhost and getting response from different server(not localhost) ? – Monty Jan 19 '16 at 09:42
  • yes ajax call is from localhost `$.post('http://www.example.com/projectX/lookup_update.php', $(this).serialize()) .done(function (data)` and online lookup_update.php echo json format data – alex Jan 19 '16 at 09:49
  • give me code, i will check on my machine, or you can come in chat room. – Monty Jan 19 '16 at 09:53
  • you are right about the problem lays in my localhost. Not sure if I have to change the jquery code (seems to be good) see my updated question – alex Jan 19 '16 at 12:06
1

CORS requests are "secured" with preflight requests.

MDN talks about it here

Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method

This is just a guess here, but you are probably using a framework, and you forgot to enable (implement) OPTIONS route for your requests.

Worth noting, you shouldn't use the wildcard header ( allowing any site to CORS your service ), you should rather specify a whitelist.

Another header that you should be sending is allowed request method.

Access-Control-Request-Method: POST

Hope this helps.

Slytherin
  • 474
  • 3
  • 17
  • Nope, not using a framework. Just a simple 1 input field form and some jQuery javscript to post and handle the response. – alex Jan 19 '16 at 09:33
  • 1
    In that case double-check your routing. You are probably not reaching your script at all. I also edited the answer mentioning another header to send along. In any case, give that MDN article some reading to get a broader perspective on this problematics – Slytherin Jan 19 '16 at 09:39
  • ah I see lookup_update.php indeed uses a framework (Wordpress) – alex Jan 19 '16 at 09:59
  • Maybe you could accept my answer if it helped solve your problem. If you have problems implementing the solution, feel free to ask a new question regarding that particular problem. Cheers – Slytherin Jan 19 '16 at 10:06
  • Not yet solved, recreated lookup_update.php so it doesn't use Wordpress functions. Still need to dive into your link and readup – alex Jan 19 '16 at 10:09
1

this code saved me :

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "X-Requested-With, Content-Type, X-Token-Auth, Authorization"
David Buck
  • 3,752
  • 35
  • 31
  • 35