Web Service using JSONP from External Domain – PHP – JQuery

You may want to look at this previous post where I setup a PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX

OK, so this code will use php to generate the JSON code that will get delivered over the internet to the JSONP (JSON Padding) client on an external domain. This allows your webservice to be available too whoever wants to call it.

Here is the PHP Code: (Not all of it, but enough to get the idea)

//http://SERVER_domain.com/webservice.php
private function GetTriviaTag($row) {
	$t = new Tag();
	$t->id = $row['id'];
	$t->triviaid = $row['triviaid'];
	$t->tagid = $row['tagid'];
	return $t;
}
public function GetWhere($where) {
	$retArray;
 
	$sql = "SELECT * FROM trivia_tags WHERE {$where}";
	foreach ($this->pdo->query($sql) as $row)
	{
		$retArray[] = $this->GetTriviaTag($row);
	}
	return $retArray;
}
$where = " (1 = 1)";  // THIS WILL SELECT ALL
$tarray = GetWhere($where);
 
//OUTPUT JSON:
header('Content-type: application/json');
echo $_GET['callback'];  // <-- THIS IS IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!!
echo "(" . json_encode($tarray) . ")";

And now, to access it from javascript in an external domain (non – SERVER_domain.com ):
http://CLIENT_domain.com/Test.html:

<html>
	<head>
		<title>Test</title>
		<script src="http://code.jquery.com/jquery-latest.js"></script>
	</head>
	<body>
		<div id="triviaQuestions"> loading... </div>
		<script>
			$(function() {
				// THE 'callback=?' in this request is IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!!
				$.getJSON('http://SERVER_domain.com/webservice.php&callback=?', function(data) {
					var items = [];
					var htmlResult = "";
					$.each(data, function(key, val) {
						htmlResult += "<br />Q: "+ val.id +", '"+ val.question +"";
					});
					$('#triviaQuestions').html(htmlResult);
				});
			});
		</script>
	</body>
</html>

PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX

You may want to look at this previous post where I setup a Web Service using JSONP from External Domain – PHP – JQuery

The HTML that calls the Javascript:

<div id="taglist"></div>
<input name="searchTags" id="searchTags" type="text" />
<input type="button" name="searchtags" onclick="getTags()" value="search"/>
<div id="tagresult">
</div>

The JavaScript (JQuery) AJAX Request and Response Processing:

function getTags()
	{
		var q = $('#searchTags').val();
		$.getJSON('ws.php?type=tag&wN=name&wO=like&wV=' + q, function(data) {
			var items = [];
			var htmlResult = "";
			$.each(data, function(key, val) {
				//As you can see, you can access the JSON (at the bottom of the page) by doing val.PROPERTYNAME:
				htmlResult += "<br />Add : <a href=\"#\" onclick=\"addTag("+ val.id +", '"+ val.getfullname +"'); return false;\">"+ val.getfullname +"</a>";
			});
			$('#tagresult').html(htmlResult);
		});
	}

PHP Code that returns JSON in the PHP file called by the AJAX: (ws.php)

	$ta = new TagAccess();
	$tarray = $ta->GetTagsWhere(" {$whereName} LIKE '%{$whereVariable}%'");
	header('Content-type: application/json');
	echo "",  json_encode($tarray), "";

The GetTagsWhere Helper Function:

    public function GetTagsWhere($where) {
    	$retArray;
 
    	$sql = "SELECT * FROM tags WHERE {$where}";
    	// THE PDO Object was created previously
	foreach ($this->pdo->query($sql) as $row)
	{
		$retArray[] = $this->GetTag($row);
	}
	return $retArray;
    }

JSON Returned:

[{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"}]

ASP.Net Update Panel – Javascript Event – jQuery Click

I needed to add a onclick event to a textbox in asp.net to change it to remove text from a textbox onClick when it is clicked.
The normal code would look something like this:

1
<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
1
2
3
4
5
6
7
8
9
<script>
        if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
            $('.txtStoreLocatorZip_CssClass').click(function () {
                if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
                    $('.txtStoreLocatorZip_CssClass').val('');
                }
            });
        }
</script>

But, this won’t quite work because my textbox is in a UpdatePanel’s ContentTemplate and the javascript is not read on postback.

So, This is what I ended up doing (a simplified version):

1
2
3
4
5
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
	<ContentTemplate>
		<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
	</ContentTemplate>
</asp:UpdatePanel>
1
2
3
4
5
6
7
8
9
10
11
12
<script>
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
	function endRequestHandler(sender, args) {
		if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
			$('.txtStoreLocatorZip_CssClass').click(function () {
				if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
					$('.txtStoreLocatorZip_CssClass').val('');
				}
			});
		}
	}
</script>

This will add an endRequest handler to the end of the partial page postback so that you can call a nice little function at the end of it.

Hope this helps some people!

Override the window.onload javascript function

1. Creates a blank function
2. Checks onload for a function.
2a. Sets the originial onload function as temp
3. calls the new function initMap() before the originial temp onload function.

Pretty cool!

Code:

1
2
3
4
5
6
7
var temp=function(){ return 1;};
if( window.onload )
{
      //override "placeholder" with whatever already exists in onload
     temp = window.onload;
}
window.onload=function(){ TheFunctionYouWantToCall(); temp();};