0

I have my JavaScript files on my main domain and I want to do some calls from the subdomain.

I have added:

url: "http://domain.com/ajax.php" 

So the full code is:

 $.ajax({ type: "POST", url: "http://domain.com/ajax.php", data: { var1: var1, var2: var2 }, success: function(data){ } }); 

But on Firebug it shows the request as red and it fails to respond. Also the POST parameters are there as they should.

Should I create a new JS file on the subdomain and add the necessary codes and do from there the AJAX calls?

EDIT: using JSONP code

I am using this on localhost/ajax.php, which I call from sub.localhost

 $.ajax({ dataType: 'jsonp', data: 'id=10', jsonp: 'jsonp_callback', url: 'http://localhost/ajax.php', success: function (data) { console.log(data); }, }); 

and the ajax.php contains:

<?php echo $_GET["id"]; ?> 
3
  • what are the 2 domains? is your server erroring out? Commented Jun 11, 2011 at 15:54
  • at the moment i am testing at localhost, no errors, just doesnt return anything back. Commented Jun 11, 2011 at 15:55
  • try testing on the actual domains. localhost to domain is more problematic, though see possible solutions below. Commented Jun 11, 2011 at 16:04

3 Answers 3

4

You can use Access-Control-Allow-Origin header to enable cross-domain requests.

Read this: Cross-Origin Resource Sharing (CORS)

Sign up to request clarification or add additional context in comments.

Comments

2

Assuming you have jQuery 1.5+ you can use:

$.ajax({ crossDomain:true, type: "POST", url: "http://domain.com/ajax.php", data: { var1: var1, var2: var2 }, success: function(data){ } }); 

From the DOCS:

crossDomain(added 1.5)

Default: false for same-domain requests, true for cross-domain requests

If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain

Comments

0

For subdomain calls you have two options:

  1. Use document.domain on both sides.

  2. Use jsonP, either via jQuery 1.5's crossDomain ajax specification, or directly.

7 Comments

with jsonp it doesnt even execute the ajax request on the subdomain
post your jsonp code (on both the caller and callee sides) and i'll take a look.
Ah, your response needs to be json formatted: {id: 5} for example.
updating the votes.php to $array = array( 'id' => $_GET["id"] ); echo json_encode($array); , gives the formatted json.. but on the subdomain it seems like it doesnt even see that there is an ajax request when i click the button because nothing happens on firebug... it doesnt even show the request
I see that you specified a jsonp callback. Do this for simplicity sake for now: $.getJSON('http://localhost/ajax.php?id=10&callback=?', function(data) { console.log(data)});
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.