Cross domain AJAX querying with jQuery

This post IS NOT about jQuery’s JSONP support. This post is about how to make AJAX queries to domains other then yours. Basically how to achieve cross domain scripting with jQuery. The technique will help you resolve the access to restricted uri denied" code: "1012 problem.

Using this method for cross site scripting you will be able to:
Make AJAX queries to any domain even those that differ from your own;
Use any of $.get(), $.post(), $.ajax(), $getScript(), etc. jQuery AJAX functions as your query method.

But all these does not come free, you will need to put a proxy to between you and the rest of the world. This cross domain querying solution works because you actually loading the content from your own domain. You request the URL and the proxy script on your server actually loading the content from the internet and passing it over to you.
I created a sample PHP proxy that I used to get related news RSS feed for one of my projects.

The PHP script to use as a cross domain scripting proxy:

<?php
// Set your return content type
header('Content-type: application/xml');

// Website url to open
$daurl = 'http://feeds.feedburner.com/jQueryHowto';

// Get that website's content
$handle = fopen($daurl, "r");

// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>

I named the file proxy.php and made my AJAX request to this url. Here is a jQuery code example:

$("#rssFeeds").load("path/to/proxy.php", function(){
// Some callback functions
});
And this is how I overcame the jQuery cross site scripting problems. The bad news is that not all web hosting companies allow fopen() to other domains, but enable it on request. My web server was very strict on security but the script above worked well on it.

If you have better solution, just tell me !

Remove table row on user click

This post is about removing a table row on user click. I needed this functionality for a project of mine. Online application had a table with data that user can dynamically add and remove. With progressive enhancement I also need to add a functionality to one of the tables that enables users to delete table rows when that table row is clicked.

jQuery code to delete clicked table row came out to be surprisingly short, only 3 lines of code.

// Select all table cells to bind a click event
$('table td').click(function(){
$(this).parent().remove();
});

Here, we are first selecting all table cells to bind our click event. On user click to any table cell click event fires. In the click event we are removing ’s parent, which is , thus removing whole row.

By popular user demand I’m including an example that lets deleting a table row on delete image click. Here is our HTML table:

<table>
<tr>
<td>row 1, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<
/table>

Here is jQuery code to delete a row on delete image click:

$('table td img.delete').click(function(){
$(this).parent().parent().remove();
});
See demos Click here.

Bonus: Also delete a table row from database

The code above is enough if you don’t need to also delete a record from your database table. In my case I had to set up a server side code to do that. With one extra AJAX call to my server side script the functionality was ready.

$('table td').click(function(){
$.get('deleteRow.php', {id: $(this).parent().attr('id')},
function(){
$(this).parent().remove();
});
});

In the jQuery code above, instead of removing table row straight away we are making an AJAX call to our server side code that also removes that row from our database and then on AJAX call completion we removing table row.

If you have better solution, just tell me !

Using jQuery For The Animation

The animation is really quite simple. We’ll use jQuery to animate the opacity of the <span> tag. Remember that the <span> tag displays the “hover” state of the image. Hence, when the <span> is visible, the link takes the “hover” appearance. We’ll need the “hover” state to be invisible when the page loads. We can do this by setting the opacity of the <span> tag to “0″:

$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// the rest of the code will go here

});

Placing the code inside of “$(function() { … });” tells the browser to execute the code when the document has loaded. The code that we’ll use to do the animation is as follows:


// on mouse over
$("ul#menu span").hover(function () {

// animate opacity to full
$(this).stop().animate({
opacity: 1
}, 'slow');

},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({

opacity: 0
}, 'slow');
});

Hence the entire Javascript used is as follows:

<!-- Include jQuery Library -->

<script src="jquery-1.2.2.pack.js" type="text/javascript"></script>
<!-- Let's do the animation -->
<script type="text/javascript">

$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, "slow");
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, "slow");
});
});
</script>

Notice that we first include the jQuery library. You can learn more about jQuery animations by reading up on the documentation One final addition to the CSS is required to ensure that the mouse cursor is display as a pointer when hovering over the <span> tag:

ul#menu li a span:hover {
cursor:pointer;

}

The full source code can be accessed via the demonstration page I should just add that whilst this code seems to work well with FireFox and IE7, IE6 might (and probably will) be a different story.

If you have better solution, just tell me !

Ajax Triple Dropdown with States Cities Database

Ajax Dropdown Menu it's make easy for user to use interface. When you choose first dropdown menu data in second dropdown will be filter and data related in first dropdown will be show automatic

For This Example Code is PHP and Database is MySQL

Example : Stated and Cities

1. Create Dropdown Menu (state_dropdown.php)

<?
echo "<form name=sel>\n";
echo "States : <font id=states><select>\n";
echo "<option value='0'>============</option> \n" ;
echo "</select></font>\n";

echo "Cities : <font id=cities><select>\n";
echo "<option value='0'>=== none ===</option> \n" ;
echo "</select></font>\n";
?>
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "state.php?data="+src+"&val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
window.onLoad=dochange('states', -1); // value in first dropdown
</script>
2. Select States and Cities to Show in Dropdown (state.php)

<?
//set IE read from page only not read from cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header("content-type: application/x-javascript; charset=tis-620");
$data=$_GET['data'];
$val=$_GET['val'];
//set database
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");
if ($data=='states') { // first dropdown
echo "<select name='states' onChange=\"dochange('cities', this.value)\">\n";
echo "<option value='0'>==== choose state ====</option>\n";
$result=mysql_db_query($dbname,"select `id`, `state` from states order by `state`");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;

}
} else if ($data=='cities') { // second dropdown
echo "<select name='cities' >\n";
echo "<option value='0'>====choose cities ====</option>\n";
$result=mysql_db_query($dbname,"SELECT `id`, `city` FROM cities WHERE `state_id` = '$val' ORDER BY `city` ");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}
echo "</select>\n";
?>

2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)



Ex 2: This is Triple Ajax Dropdown Menu - Province - Ampher - Tumbon in Thailand

<? echo "<form name=sel>\n"; echo "จังหวัด : <font id=province><select>\n"; echo "<option value='0'>============</option> \n" ; echo "</select></font>\n";
echo "อำเภอ : <font id=amper><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; echo "ตำบล : <font id=tumbon><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; ?>

<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //รับค่ากลับมา
}
}
};
req.open("GET", "locale.php?data="+src+"&val="+val); //สร้าง connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=tis-620"); // set Header
req.send(null); //ส่งค่า
}
window.onLoad=dochange('province', -1);
</script>
2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)


<?
//IE page cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header("content-type: application/x-javascript; charset=tis-620");
$data=$_GET['data'];
$val=$_GET['val'];
//ค่ากำหนดของ ฐานข้อมูล
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");
if ($data=='province') {
echo "<select name='province' onChange=\"dochange('amper', this.value)\">\n";
echo "<option value='0'>==== เลือก สังกัด ====</option>\n";
$result=mysql_db_query($dbname,"select loc_code,loc_abbr from location where loc_name = location_name and loc_code != '000000' and flag_disaster is null order by loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='amper') {
echo "<select name='amper' onChange=\"dochange('tumbon', this.value)\">\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,2);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr ");

while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='tumbon') {
echo "<select name='tumbon' >\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,4);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr, loc_name, location_name FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}

echo "</select>\n";
?>
 


PS. In ajax-dropdown.rar file Include
for states and cities (america)
state.php
state_dropdown.php
state.sql (MySQL)

for province ampher tumon (thailand)
locale.php
locale_dropdown.php
location.sql
(MySQL)

If you have better solution, just tell me !

CSS Gradients in Action

Chris Williams has been having some fun with CSS gradients on a quest to create nice looking elements without images.

He uses CSS like this:

.albumInfo {
  • background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#626262), to(#000000), color-stop(.5, #202020), color-stop(.5, #000000));
  • height: 8em;
  • padding: 1em;
  • border-top: 1px solid #858585;
  • border-bottom: 1px solid #505050;
  • }
  • .albumInfo h1 {
  • font-weight: bold;
  • text-shadow: 0px -1px 1px black;
  • font-size: 1.2em;
  • }
  • ul.tracks {
  • background: -webkit-gradient(radial, 50% -70, 0, 50% 0, 200,from(#595959), to(#0d0d0d)) #0d0d0d;
  • width: 25.7em;
  • }
  • ul.tracks li.odd {
  • background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(255,255,255,.05)), to(rgba(255,255,255,.05)));
  • }

  • This example demonstrates the power of WebKit’s implementation of gradients in css. This similar looking display to that of the iPhone album display uses a radial gradient (opposed to a linear) as the background for the track names. The overall effect is a dim light. The odd numbered tracks also use a gradient to take advantage of -webkit-gradient’s support of alpha values.

    None of the gradients will work in other browsers. Check that your background and text are not the same color. The outermost div is set to black so it's viewable in other browsers.

    Sheer Heart Attack is my favorite Queen album. I'm also quite fond of A Night At The Opera.


    If you have better solution, just tell me !

    And for a final little nugget of font goodness,

    Zach Johnson is at it again, this time giving us a fun Friday treat with CSS text shadow, all via:

    1. document.getElementById('text-shadow-box').onmousemove = function(e) {
    2. var xm = e.clientX - 300;
    3. var ym = e.clientY - 175;
    4. var d = Math.sqrt(xm*xm + ym*ym);
    5. text.style.textShadow = -xm + 'px ' + -ym + 'px ' + (d / 5 + 10) + 'px black';
    6. xm = e.clientX - 600;
    7. ym = e.clientY - 450;
    8. spot.style.backgroundPosition = xm + 'px ' + ym + 'px';
    9. }

    If you have better solution, just tell me !

    Multiple font weights via CSS 3 and more font fun

    The way @font-face works is that whatever font attributes you specify for a @font-face rule, they don’t determine how the font looks but rather when it’s gonna get used. For example if you have the following two rules.



    1. @font-face {
    2. font-family: newfont;
    3. src: local(Arial);
    4. font-weight: 200;
    5. }
    6. @font-face {
    7. font-family: newfont;
    8. src: local(Calibri);
    9. font-weight: 300;
    10. }

    We posted on TypeKit recently, and we have another playa Kernest in the "fix friggin type on the Web" game.

    And for a final little nugget of font goodness,

    Typekit looks to include jQuery, loads CSS with base64-encoded data:font/otf URLs
    for @font-face. "Safer" than a plain open .TTF, I suppose.

    If you have better solution, just tell me !