i tried these two codes but it is not functioning.. i only want to ask for the data output from another domain from http://vrynxzent.info/hello.php
first code
$.post("http://vrynxzent.info/hello.php",function(e){
alert(e);
});
second code
alert(askData());
function askData()
{
var strUrlList = "http://vrynxzent.info/hello.php";
var strReply = "";
jQuery.ajax({
url:strUrlList, success:function(html){strReply = html;}, async:false
});
return strReply;
}
is there another way for this? or is it posible to do this? i want the "Hello World!" output to store in a variable in javascript..
Same old same origin policy.
The most common way to solve this is to do query in back-end (php in your case). I.e., browser sends ajax request to your host, which sends requests to other domain, receives response and sends it back to browser.
There're also some options if you own that other domain. JSONP, for example.
edit
Forgot to tell, this jquery plugin allows cross-domain requests through YQL. Tried myself.
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
It doesn't work in all cases (in particular, if webmaster has banned robots from his site), but it's still fairly simple and usable.
Because of same origin policy you cannot make ajax requests like this to some other domain,.
i would suggest using a proxy in between,.
for that what you have to do is have a script proxy.php on your own domain and then your ajax request will be
$.post( 'proxy.php' )
then proxy.php would send a request to http://vrynxzent.info/hello.php using curl and send you back the response
By default this does not work because of the "Same Origin Policy."
There are workarounds... see: http://www.ajax-cross-domain.com/
Related
I'm looking for something.
The problem is that I want to make my app do more locally and less remote.
It needs to put a parameter in every request (or websession id)
I tried the following
$.getJSON('http://*******************.com/loginapi.php?uuid=0x1a2b3c4e', function(jd) {
var reg = jd.usrreg;
var uuid = jd.usrpin;
var usrid = jd.usrid;
});
});
That does nothing, on the server side I don't even see a request to that page.
document.write(uuid) does not give anything back, when I go in my browser to the requested page I see the following:
{"usrreg":"0","usrpin":"0x1a2b3c4e","usrid":"0"}
I also tried with form data, so when I press login it sends a request to the server, but I should still get something back like usrreg=0 or 1, because it means the person is not registered, or usrreg=2 for wrong user/pass.
How can I read the value that I get when I open the page?
Cross Domain Request with Ajax are fobidden cause of Same Origin Policy: http://en.wikipedia.org/wiki/Same_origin_policy
So what are you alternatives?
Learn to use AJAX with JSONP - will only work if the other side provides it
Write a PHP bridge running locally that provides the remote data for you
Use postMessage: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
In many example code I saw the format of .getJSON() is something like
$.getJSON("url?jsoncallback=?", function(data){
...}
And at back-end the response is written like
$response = $_GET["jsoncallback"]."(".json_encode($orders).")";
echo $reponse
I delete "?jsoncallback=?" from the url and $_GET["jsoncallback"] and square brackets at back-end and it seems that everything still works. So what is the use of that jsoncallback stuff indeed?
If you don't have the jsoncallback=? it will just do normal JSON request not JSONP*. You can do normal JSON request just fine on your own server or a server that sends CORS headers.
* forget about JSONP, this is a fancy name for inserting a script element in your document that runs code from a foreign server but with same authorization as your own scripts. The $_GET["jsoncallback"], makes it a javascript function call like this:
fn({"data": "value"});
This is the code in a script like <script src="http://foreign.org/data?jsoncallback=fn"></script>. As you can see, that's Javascript, not JSON. With this, foreign.org (or someone hacking them) can change their script to do anything with authorization on your page, so be careful when using "JSONP" and prefer CORS JSON.
The callback name is used for JSONP, which is a way to circumvent the same origin policy.
JSON callback can be used to display cross domain data with jQuery. JSONP is used to make cross domain calls since it's not allowed by the same origin policy. Check out the example below.
http://www.9lessons.info/2009/12/display-cross-domain-data-json-callback.html
So I have a little js program running in a HTML5 canvas and I have a little http get request function in my js. The function itsself works(tested it with quite a few examples on the internet and it worked), but my own webserver doesnt return the right stuff when a request is sent to it.
my PHP looks like this:
<?php echo VVV::getUser()->userID ?>
When I open it in my browser it returns me the correct values the getUser()->userID returns. However when I send a Http request from my js it gets an empty result, however it works when used on various testing pages in the internet, so it must be my PHP or my server that cause this problem. any ideas?
This sounds like a cross-domain AJAX request problem. To solve this you really have just two options:
Have PHP make the cross-domain request. So whatever site that uses your AJAX will make a request to it's own server (like to its own ajax.php script) which then makes a request to your server and then returns it to the client.
Try to use something like easyXDM JavaScript library for cross-domain AJAX requests and see if that helps.
Here is a little sample for a simple cross-domain request (JSONP style):
1) On your server side, change the response to something like:
<?php echo( 'callbackFunc(' . VVV::getUser()->userID . ');' ) ?>
2) On the client side do something like:
function callbackFunc( userId )
{
// Do something with the userId
}
// Create a script tag which will load the call to the callback function
// with the user ID generated by the PHP code.
var s = document.createElement( "SCRIPT" );
s.src = "http://yourserver/yourpath/yourscript.php?maybesome=params";
document.body.appendChild( s );
The code loaded from your server will call callbackFunc() with the user ID.
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.
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.
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.
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.
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?
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 'ajithsubramanian#gmail.com' (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.
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 .
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.
Help, if you can-
The situation:
http://foobar.com includes a remotely hosted javacript file (http://boobar.com/stuff.js).
The goal is to just get an alert from the remotely hosted php script on foobar.com
I have tried the following code in stuff.js:
$.ajax({
type: "GET",
url: "http://www.boobar.com/script.php?callback=?",
dataType: 'jsonp',
success: function(result) { alert(result); }
});
No luck.
$.getJSON("http://www.boobar.com/script.php?jsonp=?",
function(data) { alert(data); }
);
Also no luck.
On the php side I have tried both the following:
return json_encode(array(0 => 'test'));
echo json_encode(array(0 => 'test'));
In Firefox I get a security error. I understand that it thinks I'm violating the security model. However, according to the jquery documentation, I should be able to accomplish this.
The error seems to be a security feature of the Same Origin Policy: to simplify, you can only make AJAX requests for stuff on the originating server (http://foobar.com). One way around this is to make a simple facade on the originating server, e.g.:
<?php
// this file resides at http://foobar.com/getstuff.php
echo file_get_contents('http://www.boobar.com/script.php?callback=?'
. $possibly_some_other_GET_parameters );
?>
Then, from foobar.com, you can make an AJAX request for http://foobar.com/getstuff.php (which in turn makes a HTTP GET request from your web server to boobar.com and sends it back to the browser).
To the browser, the request goes to the origin server, and is allowed (the browser has no way of knowing that the response comes from somewhere else behind the scene).
Caveats:
the PHP config at foobar.com must have allow_url_fopen set to "1". Although this is the default setting, some servers have it disabled.
the request to www.boobar.com is made from foobar.com server, not from the browser. That means no cookies or user authentication data are sent to www.boobar.com, just whatever you put into the request URL ("$possibly_some_other_GET_parameters").
You can get data from another server asynchronously using script tags and json:
<script type="text/javascript" src="http://somesite.com/path/to/page/"></script>
You can use this to dynamically load a remote javascript (by created a new script element and setting the src attribute, then loading into the DOM), which could set a variable. However, you need to really trust the remote site, because the JS will be evaluated without any precondition.
There is a method called window.name transport or window.name method which uses a general browser bug(not sure if this is a bug actually). You make the request through an iFrame and the loaded page puts the information you need to the "name" property of the JavaScript window object of itself.
This method uses a "blank.htm" since it first navigates to the target page and then goes back to the blank.htm page to overcome the "same origin policy" restriction.
Dojo have implemented this and you can find a more detailed explanation here.
Also I have implemented a cross-domain XMLHttpRequest object based on this method in the library I have written which can be found here.
You may not be able to use the library since it will need 1 or 2 additional libraries which can be found here.
If you need further help in implementing it in your style, I'll try to do my best.
So what I ended up doing, since it was just a GET - no data need to be retrieved - I used JQuery to create a hidden iframe with the URL including the variables I wanted to pass set as the source. Worked like a charm. To all who provded feedback - Thanks!
How about this !! Using a php proxy.
Cross-Domain AJAX calls using PHP
http://www.phpfour.com/blog/2008/03/cross-domain-ajax-using-php/
jQuery .ajax also has a setting 'crossDomain'.
http://api.jquery.com/jQuery.ajax/
crossDomain (default: false for same-domain requests, true for cross-domain requests)
Type: Boolean
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. (version added: 1.5)