Using JSONP in jQuery Ajax

PHP Server Side

    $callback = $_GET['callback'];
    $result = array();
    $result[0]['id'] = '111';
    $result[0]['title'] = 'Event1';
    $result[0]['start'] = '2014-05-10';
    $result[0]['end'] = '2014-05-12';

    $result[1]['id'] = '112';
    $result[1]['title'] = 'Event2';
    $result[1]['start'] = '2014-05-10';
    $result[1]['end'] = '2014-05-12';
    $jsdata = ($callback.'('.json_encode($result).');'); 
    echo $jsdata;

When using jsonp, it is very important to wrap the data with the callback. Try to look at the $jsdata variable, it is being wrapped by the $callback variable. That’s just how jQuery Ajax works. If you won’t wrap it with that one, you’ll get an error in your console.

Front End (Ajax and jQuery)

  jQuery.ajax({
    type:"GET",
    dataType:'jsonp',
    url: "http://mysite.com",
    error: function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.log(error);
    },
    success:function(data){
      console.log(data);
    }
  });

JSONP is important when trying to call an external domain in your ajax. It’s like when you’re in your http://localhost/myproject/index.php , then calling a domain at http://facebook.com/apiv1/something using ajax.

Subscribing an RSS Feed using Google Reader API

For the past 3 days i’ve been looking for a good documentation on how to subscribe an RSS Feed using Google Reader API, unfortunately there was none. However, I found a PHP class that was created by dimmduh but still it lacks the functionality to Subscribe an RSS Feed. So to cut the long story short, I modified his code.

Here’s what I did, been using Ajax to fetch the value from google’s server but to be honest this should be done using JSON, I just didn’t changed it…

RSS: <input type='text' name='url' id="url" />
	<input type="button" id="click" value="Submit" /> <br/>
	<div id="result"></div>

<script>
jQuery("#click").click(function(){
	jQuery.ajax({
		type: "POST",
		url: "grab_rss.php",
		data: "url="+jQuery("#url").val(),
		success: function(data){
			jQuery("#result").html(data);
		}
	});
});

/* GRAB_RSS.PHP FILE */
	require_once("google-reader-api.php");

	$username = "googleUsername"; #do not include the '@gmail.com'
	$password = "googlePassword";
	$url = $_POST['url'];

	$r = new GoogleReaderAPI( $username, $password );
	echo $r->subscribe_rss( $url );

/* ADD THIS CODE AT GOOGLE-READER-API.PHP FILE */
public function subscribe_rss( $rss_url )
{
  $ck = time();
  $client = $this->client;

  $post_fields = array (
		'quickadd' => $rss_url,
		'T' => $this->token
		);

  $this->request2google( 'subscription/quickadd?ck=$ck&client=$client', "post", false, $post_fields );
}
</script>

You will get a JSON format result.

So that’s how easy to subscribe an RSS Feed using Google Reader API.

Have a Happy Coding!