function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mmahmmmahm 

How to use JSONP format with apex REST?

Hi,

 

I need to implement a REST service that returns data in JSONP format (JSONP format required for cross-domain ajax calls). I'm calling this service by jQuery ajax. But it always raises error : Error jQuery17109439062654184185_1342893046903 was not called.

The reason is that REST API only supports JSON and XML. In this case JSONP always returned as a XML. I'm wondering is there any workaround for this?

 

Here is my apex code:

 

@RestResource(urlMapping='/BookingService/*')
global class noqBookingService {

global class BookingStatus {
    global String ReferenceId { get; set; }
    global integer Threshold { get; set; }
}

@HttpGet
    global static String getQueueStatus() {
        String referenceId = req.params.get('referenceId');
        String jsonp_callback = req.params.get('callback');
        
        BookingStatus status = new BookingStatus();
        status.ReferenceId = referenceId;
        status.Threshold = 8;
        System.debug(jsonp_callback+'(['+JSON.serialize(status)+'])');
        
        return jsonp_callback+'(['+JSON.serialize(status)+'])';        
    }    
}

 Visualforce code:

 

$(document).ready(function() {
        $.ajax({
            url:'https://My-Site-Domain/services/apexrest/BookingService?callback=?',
            type:'GET',
            dataType: 'jsonp',
            contentType: 'application/javascript',
            success: function(status){ alert('success');},
            error:function(xhr, ajaxOptions, thrownError){ alert('error:'+thrownError);}
        });
    });

 

JitendraJitendra

Hi,

I have also faced same problem, however was not able to resolve.

 

As per my knowledge it is bug in JQuery. Please read more at - http://stackoverflow.com/questions/2414899/why-isnt-jquery-automatically-appending-the-jsonp-callback

 

Please post here if you find any solution.

laura.mckevitt@bakertilly.comlaura.mckevitt@bakertilly.com

I am experiencing the same - wondering if you've had any resolution?

Scott KrauseScott Krause
You cannot get there from here.  Meaning that it cannot be done.  The REST API must return JSONP in order for the browser to execute the script.  XML or JSON will not work.  I've tried in JQuery and with hand coded JavaScript.  Sorry.
Jane_BolesJane_Boles
I know this is a really late answer but anyone looking for this solution please use this for any GETs with REST: http://peterknolle.com/accessing-apex-rest-from-site-com/ It worked great for me (follow the guide closely)! If you want to do POSTs with REST, you will have to make some authentication with something like force.tk https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit (using php or something else for a proxy) since it is now spring 15+