I need to make a ajax call to retrieve data(json) from the RESTfull Web Service which is running in the different domain(KARAF using cxf) and the client from which the ajax call is being made, is on different domain(Apache Tomcat).
The Web Service is returning the data in the form of MediaType.APPLICATION_JSON but due to cross domain call I am receiving the data in the form of jsonp object.
$.ajax({
url: "http://localhost:8181/cxf/view/ID_123",
type: "GET",
crossDomain : true,
contentType: "applicaion/json",
dataType : "jsonp",
jsonpCallback : 'myJsonCallBack',
sucess : function(json) {
alert("Success Called");
},
error : function(xhr) {
alert("Error");
}
});
and the myJsonCallBack funcation is as below..
function myJsonCallBack(data) {
alert("Callback Called");
}
The web service method is as below..
#GET
#Path("/view/{userid}")
public ViewPreference getViewPreference(#PathParam("userid") String userId) {
ViewPreference viewPreference = new ViewPreference("GRID VIEW");
return viewPreference;
}
which is returning json object as below..
{
"viewPreference": {
"preference": "GRID VIEW"
}
}
The problem is when ever I make a ajax call neither the success callback runs nor the myJsonCallBack only error is run.
while checking in firebug it is showing some syntax error telling SyntaxError: missing ; before statement {"viewPreference":{"preference":"GRID VIEW"}}.
How to resolve this problem..?
here's what you should do:
you should return this from the server:
'myJsonCallBack({"viewPreference": {"preference": "GRID VIEW"}})'
rather than this: {"viewPreference": {"preference": "GRID VIEW"}}
this will call the myJsonCallback function and others without syntax errors
hope this helps :)
Related
I am calling .net core action via ajax request. It's not even waiting for the return statement but as soon as I am calling Auth0 management api it's returning error.
[HttpPost]
public async Task<IActionResult> Create([FromBody]ConnectionCreateRequest model)
{
try
{
var result = await _managementApiClient.Connections.CreateAsync(model);
return Ok();
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
It's returning error after result statement.
Here is the ajax call:
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Connection")',
contentType: "application/json charset=utf-8",
data: JSON.stringify(model),
success: function (result) {
alert('Connections has been created successfully');
},
error: function (result, err) {
alert(err);
},
complete: function () {
hideLoadingGif();
}
});
});
What am I doing wrong?
The problem is that in $.ajax method you didn't specify dataType property. In this case $.ajax makes an "intelligent guess" based on response content type:
dataType (default: Intelligent Guess (xml, json, script, or html))
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.
Ok() method in .net core returns empty response without MIME type specified in response header. That's why $.ajax triggers error callback with statusText "parseerror".
The solution is:
to set $.ajax dataType option to "text", and $ajax will accept empty reponse and trigger success callback
in .net core to return Json(true) or Json(null) for successful response, and $.ajax will automatically recognize it as json response and trigger success callback.
Documentation for $.ajax dataType option for json response:
As of jQuery 1.9, an empty response is also rejected if dataType is
json; the server should return a response of null or {} instead. (See
json.org for more information on proper JSON formatting.
The problem is that your Controller is returning Content in the exception Which is a 200 status code result in the terms of IAction Result.
Your controller is catching the exception correctly but still returning a 200 because of the Content return Statement.
I use ajax jquery call to fetch data about tests from Jenkins test report's REST API. However, I want only those tests for which 'status' is not PASSED and FIXED. Now, can I configure my Ajax call such that this filtering is already done on the server side, so that passed tests are not returned as a part of the response ? My Ajax call so far :
function getTestResultsForJob(jobTestResultsUrl){
var listOfFailures = {};
$.ajax({
type: 'GET',
dataType: 'json',
url: jobTestResultsUrl,
async: false,
error: function() {
alert("Request has failed for " + jobTestResultsUrl);
},
success: function(data){
console.log('Request is success for ' + jobTestResultsUrl);
listOfFailures = data;
}
});
return listOfFailures;
}
It isn't possible to do such filtering with json on the server side.
The following returns the build numer and result:
job/Test/api/json?tree=builds[number,result]
And doing the filtering inside the success method of you ajax call.
If you can switch to xml the query would be like that:
job/Test/api/xml?tree=builds[number,result]&exclude=mavenModuleSet/build[result="PASSED"]
I'm having an issue with my JavaScript being able to contact the HttpPost service. I can access the same signature using the "Advance Rest Client Application" for chrome. However when I run my code in Console in Chrome I am unable to reach the service. Any thoughts? What am I missing from the signature on one vs the other? Please let me know if you need any more information.
JS AJAX Request (Stuck in Pending status)
$.ajax({
type: 'POST',
url: 'http://local/r/GetSettings',
data: '[{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]',
dataType: "json",
success: function(data){
alert(data)
},
error : function (error) {
alert("Error: " + error);
console.log("ERROR. not working", error);
}
});
C# Service
[HttpPost]
public ActionResult GetSettings(List<Source> sources)
{
return new ContentResult
{
Content = "{}",
ContentType = "application/json"
};
}
Advanced Rest Client Application (Success in returning {})
http://local/r/GetSettings
Content-Type: application/x-www-form-urlencoded
Payload::: [{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]
Change your URL for ajax request
AppContextRootName: Your application context root
$.ajax({
type : 'POST',
url : '/AppContextRootName/GetSettings',
dataType : 'json'
});
Thanks for the answers. I found out my issue why the Ajax call was not executing. I found out you can execute a AJAX statement while paused in the debugger!!! So don't try! It will execute and return and object but it will show pending in the network. Once you unpause the actual call is executed. You should just use Alert("Hello world") in the success and error and you will see it come back once you unpause.
I've looked around for a while now, seen many similar problems, but none that help. I have a getJSON call that calls my Spring controller and responds with JSON text (Verified that JSON text is indeed being returned), but the callback is never executed (Based that nothing executes within the callback function and I don't receive errors with bad JavaScript).
In my jsp file:
function getUserText(str)
{
$.getJSON("selectUser.htm", { id: str }, function(user)
{
//Doesn't matter what's here
});
}
In my controller:
#RequestMapping(value="/selectUser.htm")
public #ResponseBody String SelectUser(#RequestParam String id)
{
Users user = userMap.get(id);
if (user == null)
return null;
return createUserJSON(user);
}
I'm not sure about this, but my guess is the function you provide is the success function that gets called when ajax returns. It is possible that the request is not returning successfully.
It means the JSON is invalid. It could be the content is invalid or the content-type is not correctly set....
$.getJSON has no error callback
http://api.jquery.com/jQuery.getJSON/
to see what the problem is you need to use
$.ajax({
url: "myurl",
type: "GET",
dataType: "json",
success: function() {
//called when successful
},
error: function(e) {
//called when there is an error
},
});
Found the answer. Turns out that the JSON needs to be valid. I made a mistake so the JSON wasn't formatted correctly. I didn't know that the format mattered even before the callback function.
I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});