Ajax call return 301 permanently moved suddenly

11.9k Views Asked by At

The below code snippet was working fine, but it stopped all of a sudden for no apparent reason

jQuery.ajax({
            url: "http://example.com/api/getstuff.php?Location="+location+"&token="+token,              
            type: 'GET',
            dataType: 'json',
            success:function(data){
            if(data.success == '0'){
                alert("success");
            }
            else
            {
            alert(data.error);
            }

        });

when I copy the url of api being called from inspector and open in the browser it works fine, it was working fine both on development and production. any ideas?

*edit The issue was fixed, the api call was missing www so the call was redirected to use www, hence the 301 error.

Though this fixed the problem but I'm unable of explaining because this was the way used long ago, suddenly it stopped working!

Anyways I thought I should post the fix so someone can find useful.

Thanks

2

There are 2 best solutions below

0
On

Is this your API or a third-party API? This status code means that this resource was permanently moved to a new URL and can't be reached in this URL anymore. If it's not your own API, you must check the Location header to get the new resource location. Use the inspector to check this header out.

Just to clarify, take a look at the RFC below:

Link: https://www.rfc-editor.org/rfc/rfc7231#section-6.4.2

301 Moved Permanently

The 301 (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. Clients with link-editing capabilities ought to automatically re-link references to the effective request URI to one or more of the new references sent by the server, where possible.

This part talks about the Location header ->

The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI. The user agent MAY use the Location field value for automatic redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the new URI(s).

1
On

This error usually occurs when the resource or url you are trying to access has been moved or redirected to another url.

In this case, response from the web server always includes an alternate url.

Update your code to send request to this alternate url.

If there is no alternate url found in the response then there might be some issue with the web server or url redirection is not properly setup at web server end.

As you said that the same url is working when you open it in the browser, carefully note which URL actually gets displayed, because browser may silently switch to a substitute URL if it receives an 301 message from the Web server.