Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making jquery AJAX POST to resful API

Tags:

rest

jquery

I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.

The REST API code:

@Path("/track")
public class TrackResource {  
   ...

The method in TrackResource class i'm trying to hit :

@POST
@Path("{trackid}")
@Consumes("application/json")
@Produces("application/json")
public Response addToResource(@PathParam("trackid") String trackid, String bodyJson) {

The AJAX code:

var trackingJSON = JSON.stringify(tracking_data);
var urlAjax =  "http://localhost:7001/ds/resources/track/" + trackid;

$.ajax({
    type: "POST",
    url: urlAjax,
    data: trackingJSON,
    beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
    complete: function() { $.mobile.hidePageLoadingMsg() },
    success: function(data) { alert("ajax worked"); },
    error: function(data) {alert("ajax error"); },
    dataType: 'json'
});

I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.

I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.

like image 707
user1209575 Avatar asked May 21 '26 22:05

user1209575


1 Answers

If you're posting a JSON string make sure you also set contentType: "application/json".

var trackingJSON = JSON.stringify(tracking_data);
var urlAjax =  "http://localhost:7001/ds/resources/track/" + trackid;

$.ajax({
    type: "POST",
    url: urlAjax,
    contentType: "application/json",
    data: trackingJSON,
    beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
    complete: function() { $.mobile.hidePageLoadingMsg() },
    success: function(data) { alert("ajax worked"); },
    error: function(data) {alert("ajax error"); },
    dataType: 'json'
});
like image 146
clav Avatar answered May 23 '26 11:05

clav