What's the use of jsoncallback argument in .getJSON()? - php

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

Related

d3 means of reading proxy data via PHP

In the existing SO literature, I have seen examples that use jquery and PHP to proxy data:
jquery
function loadTheUrl(x){
$.ajax({ url: 'loader.php',
data: {url: x},
type: 'get',
success: function(output) {
$('.loading-space').html(output);
}
});
}
PHP
<?php
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents($_GET['https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o']));
echo $doc->saveHTML();
Here is what the first few lines of the data look like at the URL seen in the PHP above. It is a page of plain text only, like this:
MARKET_OPEN_MINUTE=570
MARKET_CLOSE_MINUTE=960
INTERVAL=300
COLUMNS=DATE,OPEN
DATA=
TIMEZONE_OFFSET=-240
a1521120900,555.45
1,554.53
2,554.07
3,553.9
4,552.67
...
As far as I know, the PHP is correct. For my use case, I need to replicate the above jquery by means of d3. I was hoping that d3 would have something to use to interface with the data my php file is spitting out.
If you are wondering why I am going to such lengths, it's because my browsers are not letting me run scripts (i.e. d3.text(), d3.csv() et all) directly by say d3.text('https://www.google.com/finance...') due to the infamous access control origin header error. So my plan is to mirror the data from the google backfill off a local php file that I'm serving from my server. This way everybody is happy (or at least me).
When I try calling d3.text() on my php file, my data was not loaded correctly. In other words I tried: d3.text('my_loader.php'). But that resulted in lots of NaN errors, which I usually noticed are symptoms of a parsing error of some sort. Checking back through my code, things seem fine though. I have unary parsing in place, the strings should be cast to numbers. In fact, everything was working fine offline. I could load and parse the data directly when in my IDE. It was only when I published my d3 graph to the web did I realize I couldn't parse data from different origins. This is the point where I added the PHP component. My hunch was that d3 was actually trying to parse my PHP page and not the URL the PHP was pointing to. I later confirmed this by passing the data returned by d3.text() in the console and it was indeed the PHP page itself.
Question: In light of my cross-origin data situation, what can I do from the d3 side or the PHP side to make the two interface with each other correctly? I wonder if d3 is only suited for same origin data, or if there actually is a method to read/parse cross-origin data using a technique I'm not aware of (PHP or otherwise).
The url you are fetching does not exist within the $_GET variable.
The parameters you are submitting are an array:
$_GET = ['url' => 'some_url'];
Which means this:
$_GET['https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o]
is wrong (it's also missing a quote mark at the end of the string).
It should be $_GET['url']
With no validation:
<?php
header('Content-Type: text/plain');
echo file_get_contents($_GET['url']);
But that's neither here nor there.
The issue, I think, is with the url being passed. It contains a question mark and multiple ampersands (? and &). I think this is bjorking up the $_GET parameter so all you're getting is https://www.google.com/finance/getprices?q=.NSEI. You need to wrap the url in encodeURIComponent:
var url = encodeURIComponent('https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o');
d3.text('/path/to/myscript.php?url=' + url);
Cross origin applies to all ajax requests, instead of requesting d3.text('https://www.google.com/finance...') why not try d3.text('mymethod.php') and make sure the method returns a text file rather than html via the headers:
<?php
header('Content-Type: text/plain');
$file = file_get_contents('https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o');
echo $file;

Objective-C: json response from jquery callback

I'm building and iOS application and
trying to get the json data from a url similar to:
example.com/ajax/u.php?callback=jQuery84054761566_1389381628746
Is anyone familiar with these types of callbacks?
Typical HTTP requests in obj-c return 200 status and a null response object with this url.
That's a JSONP callback used for...well, JSONP. JSONP is used on webpages to avoid the 'same origin' restriction. That is, a webpage loaded from a certain domain (say abc.com) cannot call/access resources on a separate domain (say xyz.com).
The way they (web front-end developers) get around this is by using the <script> tag which is exempt from this restriction. However the return of a <script> tag would just be parsed - to cause it to execute something, you tell it a function name that exists in your JavaScript code, in this case, jQuery84054761566_1389381628746.
So instead of returning a regular JavaScript object, say
{key : 'value'}
the server then returns a function invocation
jQuery84054761566_1389381628746({key : 'value'})
and you have, in your webpage JavaScript, the function definition for jQuery84054761566_1389381628746 that does something:
jQuery84054761566_1389381628746 = function(data){
alert(data.key);
};
iOS does not have this same-origin/cross-site restriction so you don't need JSONP - you can call whatever server you want.

HTTP get request communication js to PHP doesn't return a result?

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.

JSON crossdomain communication with PHP file and a local javascript file

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.

Asking data in AJAX

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/

Categories