user1311776
user1311776

Reputation: 243

How to sending an ajax request

I am trying to sending an ajax request from javascript to get data from the salesforce using the following code, but I keep getting Error:0 message. It seems my request is not sending properly. I do not know what is wrong with my code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    var $j = jQuery.noConflict();
    $j(function(){  
        var url = 'https://myorg-developeredition.na14.force.com/services/apexrest/clsapi';
        $j.ajax({
            url: url,
            type: 'POST',
            success : function() { 
                alert('Hello'); 
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert('Error: ' + jqXHR.status);
            },                
        });
    });
</script>

But when I type the same url in the browser, I got the response from the salesforce. It shows

<response>myresponse</response>

Thanks

Upvotes: 2

Views: 4448

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You are sending a cross domain request which your browser is preventing due to the Same Origin Policy.

To send a cross domain request, you must use jsonp.

var url = 'https://myorg-developeredition.na14.force.com/services/apexrest/clsapi';
$j.ajax({
    url: url,
    type: 'POST',
    dataType: 'jsonp', 
    success : function() { 
        alert('Hello'); 
    },
    error : function(jqXHR, textStatus, errorThrown) {
        alert('Error: '+jqXHR.status);
    } // <-- remove the trailing comma you had here
});

Upvotes: 1

Related Questions