tips

How to make cross-domain ajax request using jsonp & jquery

1

As you may know AJAX request cant be done across domain (even across subdomain). This is a security feature but sometimes It can pretty usefull to make call between domains.

Luckily for us AJAX allows us to make cross domain request for javascript contents. That is how JSONP works, basicly instead of passing plain json you pass json inside a javascript function.

I’m going to show you how you can do this very easily using jQuery.

first of all make the call using jquery.

$.getJSON("http://someurl/somepage.php?jsoncallback=?",function(data){
  alert(data.msg);
});

As you can see we have to set jsoncallback=? in the url for this to work.

Now In your php file.

<?php
	$array = array("msg"=>"hello"); //some bogus data
	echo $_REQUEST['jsoncallback']."(".json_encode($array).")";
?>

The output will be something like :

jquery65456456456({“msg”:”hello”})

As you can see It now looks like a javascript function.

That’s all there is too it !

Share

Related Posts:

How to disable context menu on right click with jQuery

1

Today I had to make a simple script that changed the class of an element when you “right clicked” on it but I struggled for hours trying to disable the right click contect menu from showing.

Finally I found a simple solution so I decided to share :)

I tested it on FF 3.6 & IE7

the magical line is

$(el)[0].oncontextmenu = function() {
			return false;
		}

For a concrete example here is my code

$(".besoin").bind('mousedown',function(event){
		switch (event.which) {
	        case 3:
			        if($(this).hasClass("mild")){
						$(this).removeClass("mild");
						$(this).addClass("hot");
					} else if($(this).hasClass("hot")){
						$(this).removeClass("hot");
						$(this).addClass("superhot");
					} else if($(this).hasClass("superhot")){
						$(this).removeClass("superhot");
					} else {
						$(this).addClass("mild");
					}
	        break;
		}
		$(this)[0].oncontextmenu = function() {
			return false;
		}
	});

Have fun !

Share

Related Posts:

Looking for a great alternative for templateMonster ?

0

Even if you are the best web developper around , your work is not worth much if you dont have a killer design right ?

Of course you can make your own but I know many devs you arent made for designing ! (me included…)

A lot of websites offers templates that you can download for 50$ but with my experience they are almost always just referals for templateMonster.
TemplateMonster sometimes offers nice looking website but they so poorly coded that they are almost unusable !

So I just wanted to share with you some good alternatives…

(more…)

Share

Related Posts:

Go to Top