2

I am a JSON newbie, but have good experience in PHP and javascript. The question is simple, and the answer might be simpler. I am having trouble sending data from the PHP file on the server, to another PHP file that I have locally which would receive the data in JSON format from the server. What am I doing wrong?

Javascript Frag ( Local )

$(document).ready(function(){
//attach a jQuery live event to the button
$.getJSON('http://www.xpal.com/ws_users.php?action=get_user_data&user_id=33',function(data) {

        alert(data); //uncomment this for debug
        $('#showdata').html("<p>Username= "+data.username+"<br> Email= "+data.email+"<br> Firstname="+data.firstname+"<br> Lastname="+data.lastname+"</p>");
    });

});

PHP Frag (Server @xpal.com) :

$users=new users;

if($_GET['action']=="get_user_data")
{
$user_id=$_GET['user_id'];
$assoc=array(
                "username"=>$users->return_username($user_id),
                "email"=>$users->return_user_emailid($user_id),
                "firstname"=>$users->return_user_firstname($user_id),
                "lastname"=>$users->return_user_lastname($user_id)
            );
echo json_encode($assoc);
}   

Edit :

The error message : XMLHttpRequest cannot load xpal.com/ws_users.php?action=get_user_data&user_id=33. Origin localhost is not allowed by Access-Control-Allow-Origin.

5
  • Nothing as far as I can see. I followed the URL and got a nice JSON string back containing user data (which I hope is test data). What exactly is going wrong. What is hapening and what do you expect to happen?
    – vascowhite
    Aug 25, 2011 at 2:06
  • XMLHttpRequest cannot load xpal.com/ws_users.php?action=get_user_data&user_id=33. Origin localhost is not allowed by Access-Control-Allow-Origin. is the error i am getting. Yes thats a test database :)
    – sniper
    Aug 25, 2011 at 2:09
  • This is probably due to your browser's security policies. See : en.wikipedia.org/wiki/Same_origin_policy Aug 25, 2011 at 2:15
  • Ahh! How do I go about and fix this?
    – sniper
    Aug 25, 2011 at 2:16
  • Reading your comments to answers here I am not clear on what access you have to the xpal server. Are you developing on/for that server?
    – vascowhite
    Aug 25, 2011 at 2:40

7 Answers 7

3

You can't make ajax calls to a different domain that the page is hosted on. See the Same Origin Policy that browsers implement for security reasons.

There is a way to make cross domain ajax calls and it involves using JSONP. Basically, you inject a script tag into your own frame and that script tag points to server endpoint anywhere on the web. Since the src value of a script tag is not restricted by the same origin policy, you can reach that server. But, now you need to have a way to get that result back. That is done using JSONP where you specify in your server request a javascript function that you want the returned javascript to call. That returned javascript can have javascript data in it that is then passed to the desired function. JSONP requires cooperation between both client code and the server code since a normal ajax call might not support the extra part of JSONP. But, with this cooperation of both sides, you can get around the same origin policy for server endpoints that support JSONP.

4
  • Thanks for that jfriend. How do other API's work? All of them use JSONP? I thought all I have to do is echo a JSON package from the server side and catch it at the client using the necessary javascript function. Looks like its not that easy.
    – sniper
    Aug 25, 2011 at 2:23
  • @sniper - I don't follow what you're asking in your comment. It's easy to communicate with the host server using ajax because that is the same origin.
    – jfriend00
    Aug 25, 2011 at 2:29
  • Yes, I totally understand that point. Lets say I want xpal.com to send data to facebook.com(one way). So facebook.com will have a to make a few API calls to xpal.com, and xpal.com would return a JSON object right? Also assume a week down the line, xpal.com should send data to a mobile app that we are building. Both these scenarios are possible only if I use JSONP?
    – sniper
    Aug 25, 2011 at 2:35
  • 1
    Servers can talk to each other to their heart's content. They aren't restricted by same origin. But if a page on xpal.com wants to communicate with facebook, then it can do so using the facebook API which manages the cross domain communication for you. If an xpal.com webpage viewed on a mobile phone wants to communicate with your own xpal.com server, it can do so using normal ajax because it's same origin.
    – jfriend00
    Aug 25, 2011 at 2:48
3

As already explained in the other answers, this doesn't work because of the Same Origin Policy.

Now, JSONP (see jfriend00's answer) is one way around it, but it has its drawbacks. (see the end of this page).


There is another way around it: and that is have PHP query the remote server and send a response back to the client. See this page:

Cross domain AJAX querying with jQuery

The main drawback of this method is that all the traffic will go through your server, since you have to call the remote page, fetch the response and send the response back to the client.

3
  • Hey NUE. I did as chris suggested. Here goes my new code lines : PHP Frag : echo $_GET['callback']. '('.json_encode($assoc). ')'; JS FRAG : $.getJSON('xpal.com/…?', function(data) That works! But is that secure and the right way to do it?
    – sniper
    Aug 25, 2011 at 2:42
  • @sniper Well, if it works and you are aware of the drawbacks JSONP has, then go for it. The major security issue here is that this opens your server to potential XSS attacks from xpal.com, but if you trust them enough it shouldn't be a problem. Aug 25, 2011 at 2:50
  • 1
    @sniper See: james.padolsey.com/javascript/… Aug 25, 2011 at 2:51
2

To use jsonp, as other suggest, you must either put "callback=?" at the end of your URL, or use $.ajax() and specify the dataType is jsonp. Examples here.

2
  • That worked like a peach. :) But is that a secure solution? Looks like it returns some immediate executable!
    – sniper
    Aug 25, 2011 at 2:40
  • From what I understand, returning "some immediate executable" is precisely what jsonp is designed to do! See en.wikipedia.org/wiki/JSONP
    – Chris
    Oct 11, 2012 at 20:21
1

Its called the Same Origin Policy. In short: the domain that your code is on, is the only domain your javascript can communicate with (by default)

JQuery won't get json?

0

You could run a php script on your own server if that is an option.
This:-

<?php
    $details = file_get_contents('http://www.xpal.com/ws_users.php?action=get_user_data&user_id=33');
    var_dump(json_decode($details));

returned this:-

object(stdClass)[1]
    public 'username' => string 'sniper' (length=6)
    public 'email' => string '[email protected]' (length=26)
    public 'firstname' => string 'Ajith' (length=5)
    public 'lastname' => string 'Ravi' (length=4)

Does that put you on the right path? You could do an AJAX call to a script based on this on your server.

2
  • If I am building a web service, that will be used by a mobile App to fetch data from my server how would this solution scale up? I am seeking a solution that will make it more like a API function call that will return the result, in the end. :)
    – sniper
    Aug 25, 2011 at 2:30
  • That's information that wasn't in your question. However, I don't see an issue with it, its up to you to write your code in a manner that will scale and be robust. You're going to have more issues trying to do this in jQuery, believe me.
    – vascowhite
    Aug 25, 2011 at 2:36
0

You should take a look at CORS and its implementation.

In your case, the possible solution would be to use header(Access-Control-Allow-Origin:http://localhost) in your php file. Replace localhost with the domain which is restricted by SOP.

A good reference on CORS can be found at https://developer.mozilla.org/en/HTTP_access_control .

0

You could use the same jQuery to make a cross-domain request, Just check the link cross-domain request, they have demo how to implement the cross-domain request...

In your code, Make sure that the following things are correct,

  • the www.xpal.com output should be in json format
  • if there is any error in your output, jsonp technique doesnt display error (poor error handling).

  • Your json output should be covered with echo $_GET['callback']." ".json_encode($array).")"; as in the mentioned link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.