Friday, April 15, 2011

Stop Parent event from firing

One funny problem you might face in this web world, you might add click event to parent and also add click event to child, but when you click on child element it also fires parent event :(

don't worry :) with just single line of Javascript code you can stop parent from being access to the child.

Here we go...

<div id="parent" onClick="imYourBoss()">
     <div id="child" onClick='imEmployee()'>
    </div>
</div>

in above example you can stop your parent by using following code :
<script>
$(function(){
$("#parent").click(function(){
     alert("Im your BOSS");
});

$("#child").click(function(event){
     event.stopPropagation();
     alert("Yeah I stop my boss from accessing me :)");
});
});
</script>

using stopPropagation technique we can prevent any parent handlers from being notified of the event.

stay tune for latest stuff :)

Wednesday, February 9, 2011

Solved Cross Domain Issue

Now its very easy to fix cross-domain issue using JSONP
JSONP allows you to make an HTTP request outside your own domain
Following example will help you :
Suppose your url returns JSON data as :

            { "gender":"Male","website":"www.google.com"}

 then just wrapped this JSON inside the callback function on server side
 here we use callback function name as "functionName"

            functionName({ "Gender":"Male","website":"www.google.com"})

  now just create function on client side with this callback name

 <script>
     function functionName(result) {
            alert(" Gender : "+result.gender);
    }
 </script> 

  Now its time to use JQuery, call your url using $.getJSON function,here is the  example 
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
           $.getJSON("http://localhost/app/getJson?callback=?",
                  function(data){ }
           );

         function functionName(data) {
               alert("Symbol: " + data.token + ", Price: " + data.price);
        }
</script>
<body>
</body>
</html>

 Server side changes :
 You also need to change your server side code
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
  throws ServletException, IOException {
 String jsonData = getDataAsJson(req.getParameter("symbol"));
 String output = "functionName(" + jsonData + ");";
 resp.setContentType("application/json");
 PrintWriter out = resp.getWriter();
 out.println(output);
 // prints: jsonp1232617941775({"Gender":"Male","website":"www.google.com"});
}