0

I was debugging ajax to figure out why it wasn't working and in the developer tools I got this log

XMLHttpRequest cannot load http://'WebsiteInQuestion.php'. No 'Access-Control-Allow-Origin'  
header is present on the requested resource. Origin 'http://ServiceHostingMyWebpage.com' 
is therefore not allowed access.

I read about XMLHttp in passing but didn't think it was relevant and I honestly have no clue about it.

My code doesn't even have a header and it seems that there is some XML code missing.

Here's my ajax code

<script type="text/javascript">

$(document).ready(function() {

$("#my_form").submit(function(event){
    alert ("submited");

    event.preventDefault("#my_form");

    var post_url = $(this).attr("action"); //get form action url
    var request_method = $(this).attr("method"); //get form GET/POST method
    var form_data = $(this).serialize(); //Encode form elements for submission



    console.log (post_url + "" + request_method + " " + form_data);

    $.ajax({
        type: request_method,
        url: post_url,
        data: form_data,
        success: function( data ) {
            alert (data);
            $('#server-results').html(data);

        }
    });
 });
});

and basically all of the HTML

<body>

<form id="my_form" method="post" action="http://comicspot-com.stackstaging.com/ajax-php.php">
    <input type="text" id="fullname" name="fname">
    <input type="submit" id="submit_post" value="Post" >
</form>

<div id="server-results"></div>

BTW, I checked and the link to ajax-embedded-link and it seems to work, pressing submit activates the javascript code and it correctly collects the data, action and method. It just seems like ajax itself isn't being activated. Most likely the XML problem.

  • You can work around this by using `url: 'https://cors-anywhere.herokuapp.com/' + post_url` in your code. Try it. And for an explanation of what that does, see the *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems* section of the answer at https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Sep 16 '17 at 23:25
  • The origin IS the same. Its hosted under the same domain – AnotherAccount Sep 17 '17 at 19:38
  • No. If the origin were the same, your browser wouldn’t be showing you that error message. It’s important to understand this. If the scheme+host+port isn’t an *exact* match, it doesn’t matter if they’re hosted on the same server. I don’t know what the real origin is, but even the dummy `http://WebsiteInQuestion.php` origin & `http://ServiceHostingMyWebpage.com` URL the request is being sent to aren’t the same origin, right? They must *exactly* match. One can’t be a subdomain of the other & they can’t be on different ports & one can’t be https while the other http. – sideshowbarker Sep 17 '17 at 21:53

0 Answers0