Tag Archives: easy

JSONP First Timer

You already know ajax is one-man’s-girl, no way to make it work cross-domain(not even subdomain) due to browsers’ same origin policy security restriction. But using ajax is so sleek, you can’t even resist yourself using it under different domains. There is always a way around for everything. Do I sound contradictory? Ajax is based on the XMLHttpRequest and as long as we use it we can’t do cross-domain data transfer. Let’s think something else other than ajax.

We are used to loading images, css, javascript files from other domains and it’s okay if we use any server-side dynamic link as the src, this is a common phenomena on web. For example:

<script type="text/javascript" src="http://www.other-domain.com/dynamic-js.php?id=5&name=Matt"></script>

There is no security restriction including javascript source from different domains, and fortunately enough you can pass GET variables (don’t over-expect for POST) with the url. This is how JSONP (JSON with padding) works, thanks to the open policy for <script> tag. May be you’r already thinking how to implement this idea, hold on! you don’t need to reinvent the wheel.

Here comes jQuery’s $.getJSON(), with this function you can pass url of another domain and get JSON data. Lemme warn you, for the very first time most of you won’t be able to make it work. Here is an example:

$.getJSON("http://www.other-domain.com/dynamic-js.php?id=5&name=Matt&jsoncallback=?",
function(data){
    // your code goes here
});

You need to understand this “jsoncallback=?” bit clearly. From your firebug Net panel you can see the “?” is replaced with “jsonp1277557614558″ (random value on each request).

JSONP Net Panel screen shot

The common mistake you’re gonna do is you expect to see something on firebug’s Console tab, but nothing there, once again JSONP is NOT Ajax request. This is merely an external javascript file being added to your document dynamically, if you don’t believe me on your firebug panel click the JS from Net tab to filter out the JS only(marked in the screen-shot above). You’ll definitely see the JSONP url there. This is the client-side part of $.getJSON(). The confusion still remains with the server-side code.

Back to “http://www.other-domain.com/dynamic-js.php?id=5&name=Matt&jsoncallback=?”, the file being called is dynamic-js.php. Put this one line of code in that file:

<?php print_r($_GET); ?>

And check the Response output from firebug’s Net tab. It’ll be something like:

Array
(
    [id] => 5
    [name] => Matt
    [jsoncallback] => jsonp1277557614558
)

In Ajax when the dataType is json the response from server-side script is just the json string:

{
	// your json data
}

Here is the most important part, unlike ajax for JSONP the $.getJSON() expects the response like:

 jsonp1277557614558({
	// your json data here
})

So you must wrap the json output with jsonp1277557614558( ). If you don’t do it the callback will fail silently without any error, which makes it tough to detect the exact problem. Remember the jsonp1277557614558 is a random string. For php the code will be something like this:

<?php
// your code here
// get the output in an array say $output_array
$jc = $_GET['jsoncallback'];
echo $jc . '(' . json_encode($output_array) . ')';
/*
// For ajax response, simply
echo json_encode($output_array);
// is enough
*/
?>

This is the most crucial thing, most programmers do the mistake for their very first time as there is no clear elaboration on $.getJSON documentation page. FYI, json_encode() function is not available on older version of php. You can get the php class from json.org.

Hope your $.getJSON() is now working! :)

Comments, criticism are most welcome.

How to get currently logged on windows username in PHP and Javascript

It is very simple to get the current windows username in PHP. The following one line of code will output the username of the system where the server is running. If you are running this from localhost then your system login name will be shown. But you can not get the visitor’s system login username.

<?php echo getenv("username"); ?>

By using javascript (actually VBscript) you can get the visitor’s windows username. But there are also limitations. It only works on IE.

<script language="VBscript">
Dim X
set X = createobject("WSCRIPT.Network")
dim U
U=x.UserName
MsgBox "username: " & U
</script>
<script language="Javascript">
var a = U;
alert("Hello, " + a.toString());
</script>

This code will show you the current windows username. But won’t work if run from http://. Open the page from your computer with IE and it’ll work, otherwise not.

Actually it is not possible to get the windows username of your website visitors as it is a security issue. So don’t waste your time if you are trying to do that.

Simplify your query easily

It’s always boring and time consuming writing long INSERT/UPDATE query. Generally when you need to insert a form data with a large number of fields into a single table it does not make any good sense to write the full query manually. For example “INSERT into tbl set name = ‘$_POST[name]‘ , email = ‘$_POST[email]‘ , ….. may be 30 fields! So how can you minimize your effort?

I have written a very simple PHP function for this:

<?php
function genquery($table, $data, $mode = 'insert into', $condition = '', $raw = '') {
	$res = mysql_query("select * from $table limit 1");

	$field_arr = array();
	for($i=0; $i < mysql_num_fields($res); $i++) {
		$field_arr[] = mysql_field_name($res, $i);
	}
	mysql_free_result($res);

	$qstr = $mode." ".$table." set ";
	$arr = array();
	foreach($data as $k => $v) {
		if(!in_array($k, $field_arr)) continue;
		$arr[] = $k." = '".$v."'";
	}
	$qstr .= implode(', ', $arr);

	$qstr .= ' ' . $raw;

	if($mode == 'update' && $condition != ''){
		$qstr .= ' where ' . $condition;
	}
	return $qstr;
}
?>

You must follow a simple way for using this function. The name of the input fields in the form should be same as the fields in the table of your database. I assume your form will be submitted in POST format. In fact a form with many fields is always submitted in post method.

Here is how to use this function:

<?php
include("qfn.php");
if(isset($_POST['submit'])){  // if the form is submitted

$q = genquery("tableName", $_POST, "INSERT INTO", '', '');
mysql_query($q);
}
?>

For updating use:

$q = genquery("tableName", $_POST, "UPDATE", " id = '$_SESSION[id]' ", '');
// the 4th parameter is the condition for update. Use your own condition.

You can use more than one condition like:

$q = genquery("tableName", $_POST, "UPDATE", " id = '$_SESSION[id]' AND uid = '$_SESSION[uid]' ", '');

The 5th parameter is for raw values like

"entry_date = CURDATE(), status = '1' "

You can use the 5th parameter both for INSERT and UPDATE query. But the 4th parameter is only for UPDATE query.

Hope this will help you a lot and save your time & energy.

Download the php file in zip format.