Search code examples
jqueryajaxjsonp

Jquery jsonp ajax callback not working


I am working on a sample example of implementing jsonp using jquery ajax .

Can someone please explain why the callback function 'customcb' is not getting invoked in below example , am confused.

From client application am making an $.ajax call to an ASP.NET MVC server application, below is the client code

$().ready(function () 
{

 $.ajax({
 url: 'http://localhost:55632/',
 type: 'GET',
 dataType: 'jsonp',
 jsonp: 'cbqs',
 jsonpCallback: 'customcb',
 success: function (data) 
 {
 alert('success');
 },
 error: function (XMLHttpRequest, textStatus, errorThrown) 
 {
  alert(errorThrown);
 }
 });

 function customcb() 
 {
  alert('customcb');
  }

});

And below is the simple ASP.net MVC action written in server application

public class HomeController : Controller
{
public string Index()
{
 Emp x = new Emp
 {
  fname = "first name",
  lname = "last name"
 };

 string json = JsonConvert.SerializeObject(x);
 Response.ContentType = "application/x-javascript";
 string str = "customcb(" + json + ")";
 return str;
 }
..............
..............

Expected Result: Both 'success' and 'customcb' alert messages should be displayed.

Actual Result : Only 'success' alert message is getting displayed.

Note : I am able to access the returned data from success function and there are no JS errors.

Please let me know why 'customcb' alert message is not getting displayed.


Solution

  • Move the jsonpCallback function out of "$().ready(function ()" code block.

    function customcb() 
    {
        alert('customcb');
    }