jQuery ajax doesn't work on url without www - javascript

The jQuery ajax script below doesn't work on my site if url is without www. I checked Firebug and it doesn't send the ajax call.
$.ajax(
{
type: "POST",
url: "http://www.mysite.com/beta/products.php",
data: "page_type=index&sort=relevancerank&CartId=<?php echo $CartId;?>&HMAC=<?php echo $HMAC;?>",
success: function(msg)
{
$('#content-holder').html(msg);
},
error: function()
{
alert("An error occurred while updating. Try again in a while");
}
});

I'm assuming the calling document URL is referenced as "mysite.com", or "subdomain.mysite.com"? The XMLHttpRequest object (the engine that powers jQuery Ajax calls) can not perform "cross-domain" requests. A subdomain (e.g. 'www') qualifies. Make sure your requests are to the same subdomain.

You don't need to provide an absolute URL, you can simply provide a relative one, and it will work regardless if the your page is loaded with the www. subdomain or not:
//...
type: "POST",
url: "/beta/products.php",
//...

Is your server redirecting to the "www" domain possibly? This is probably just the same-origin policy preventing your outer page from accessing a different domain.

www. is just a naming convention - ajax will load on any address that can be looked up via dns, or it will work on an ip address as long as there is a server to respond to the request.
BUT - your page location and the ajax request need to be in the same domain for security reasons. To get round this restriction, you need to use something called JSONP

Related

Ajax Cross-domain Php proxy 403 error

I'm trying to consume a third party Api using javascript and a PHP proxy as seen in this Tread, i'm able to use the proxy but the response I get, is always:
Failed to load resource: the server responded with a status of 403 (Forbidden)
http://MYDOMAIN.co/php/ba-simple-proxy.php?url=http://jsonplaceholder.typicode.com/posts&_=1471620448707
my javascript code is:
function getLocationSimple(){
var proxy = 'php/ba-simple-proxy.php',
url = proxy + '?url=' + 'http://jsonplaceholder.typicode.com/posts';
console.log(url);
// Make JSON request.
$.getJSON( url, function(data){
console.log(data);
});
}
I thought it was about permissions on the third party server, so i decided to change it to an open one - http://jsonplaceholder.typicode.com/posts -, but i still get the same error, it might be permissions in my own server? -my host is hostgator-
Let's try once this piece of code
function getLocationSimple(){
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: "http://jsonplaceholder.typicode.com/posts"
}) .done(function( data ) {
console.log( data);
});
}
this happens due to Cross-Domain Policy. Cross site access is not available in the api side . So we can use dataType: 'jsonp' to overcome this issue
This has something to do with the Cross-Domain Policy. You can't do ajax requests to another domain due to security reasons, because a malicous attack could also involve to do a request via ajax to load additional script to hack you.
Even though Wikipedia might not be the best link to provide, it'll give you an idea.
https://en.wikipedia.org/wiki/Same-origin_policy

consuming PHP service returning valid json with $.ajax

I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link

cross-domain jquery 1.6.2 ajax call is trying to call from same domain

I have an api set up on another domain, domain B (api.domainb.com), and want to make a call to it from domain A (www.domaina.com). However, when I do a call from domain A to domain B via jquery ajax, jquery ends up trying to call www.domaina.com/api.domainb.com which obviously will return an error. Here is the relevant javascript code
$.ajax(
url: 'http://api.domainb.com',
type: 'GET',
dataType: 'jsonp',
data: {hello: 'world'},
crossDomain: true,
success: function(data){
alert(JSON.stringify(data))
},
error: function(error){
alert(JSON.stringify(error))
});
Eventually, the code in domain A and domain B will be on the same domain, but for now, I need to make a cross-domain call. Any suggestions as to how to make this work?
You're just missing the protocol so that the Ajax call knows it's a different domain and not a relative URL. Try using url: 'http://api.domainb.com'.
You cannot make cross-domain calls; browsers simply do not allow it in general. However, the reason you're seeing the behavior you describe is that your URL is missing the "http://" prefix.
There are some things you can do with fairly new HTML5 APIs to sort-of "get permission" to do cross-domain calls.
edit #Dan points out correctly that while XMLHttpRequest (what people usually call "ajax") won't do cross-domain stuff (CORS aside), it's possible to leverage the fact that <script> tags can reference other domains in order to put together a service. The server-side code has to be different, however. (That's usually called "JSONP".)

Can't make get request using ajax

Here is the error message:
XMLHttpRequest cannot load (the url1). Origin http://localhost:8081 is not allowed by Access-Control-Allow-Origin.
Here is the code:
$.ajax({
url: (the url2),
async : false,
data: { fbId : eh,
fbSecret : meh,
key : bleh
},
datatype: "json",
success: function(result){
console.log(result);
}
});
I know the url is correct because when I click it it gives me the data I need, which is like {"names" : ["blah"]}
Do I need to give out any more details?
I've tried various things like using jsonp/html instead of json, putting data directly into the url instead of separately as data, and using $.get instead of $.ajax, along with editing $.ajaxsetup....
the error message says it all, you cannot make cross domain ajax requests (exception in case of jsonp but that also has to be supported by the server) due to same-origin-policy
this may help you here http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/
ports mismatch ;) the page that tries to establish the request has to be on the same port ;)
I think you are trying to access a server different than the one you served the script from - the JavaScript code inside a page served from server A can access only server A using XmlHttpRequest.
If this is the problem there is no easy solution - you have to use proxy or avoid XmlHttpRequest altogether.
same-origin-policy is a browser security measure that restricts JavaScript code from talking with resources originating from other websites i.e resources loaded from any other domain and/or port. eg. JS running in a web page on http://google.com:80 cannot interact with data loaded from http://cbs.com or even http://cbs.com:8081
Working around SOP
a) Proxy in your server: you create a end point in your app that talks to the external url and returns the result
b) Load the JSON response into a <script> tag otherwise jsonp i.e json with padding
eg:
var url = "http://localhost:8081/?queryString=asdsa&callback=jsonCallback";
var script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("type", "text/javascript");
window.jsonCallback = function(jsonObj) {
// use JSON object here
// cleanup
document.body.removeChild(script);
delete window[callback];
}
document.body.appendChild(script)
In your case since you are running it of a different port it is not valid and hence the error thrown by the browser..
and there are some server side changes that go along with this.. read up on how to do it for your scripting language..
basically the response should be something like:
jsonCallback({"Name": "Random", "Id" : 2432, "Rank": 453})
Use dataType: "JSONP" to overcome the limitation you encountered; check out the documentation to implement it correctly. You also have to provide a callback function for it.

Ajax calls to subdomain

I have one server located at example.com running apache, serving my static html files.
I also have a json service located at api.example.com running python with cherrypy.
The user requests example.com and get the index html page. On that page I make an ajax request with jquery to the json service. document.domain returns example.com
$.ajax({
type: 'GET',
url: 'http://api.example.com/resource/',
dataType: 'json',
success: successCallback,
error: errorHandler
});
However, I can't see the response body for the ajax request in firebug. This leads me to believe that the browser (FF) doesn't support this.
What are the best methods to achieve this? I would prefer not to use any proxying on the apache backend for example.com if possible.
You can also use JSONP by adding callback=? to the end of the url. jQuery already knows how to handle these type of requests but it does require some server side changes to handle the callback param.
AJAX request is only supported on the same domain. However, you can write an http proxy in your preferred scripting language and make calls to that http proxy. You can check out this little tutorial on an AJAX proxy written in php.
try changing your domain in your sub-domain, like this
<script type="text/javascript">
document.domain = 'example.com';
</script>
if does not work, change your document.domain in your domain page too.
As far as I know, you can't do AJAX cross-domain.
Why is cross-domain Ajax a security concern?
Though I guess you could do an IFRAME workaround
Cross Sub Domain Javascript
Use document.domain to make the domain be the top level domain instead of the subdomain.
document.domain="example.com"
This is described in detail on MDN.

Categories