Hi there are already lots of threads related to this problem.
But still i got stuck into the same . When I am trying to access this REST api, I couldnt able to get the response. I cannot control server side response header because its public API .can any body help on this.
Below is my code
$(document).ready(function() {
$("#medication").autocomplete({
select : function(request, response) {
//$(this).value(response.item.value);
getMedicationIdByName(response.item.value);
},
search : function(){$(this).addClass('working');},
open : function(){$(this).removeClass('working');},
source : function(request, response) {
$.ajax({
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
type : "GET",
url : "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data : "name="+ request.term,
crossDomain: 'true',
dataFil ter : function(data) {
return data;
},
success : function(data) {
try {
//alert("success!!"+JSON.stringify(data));
data = data.suggestionGroup.suggestionList["suggestion"]+ "";
data = data.split(",");
response($.map(data,function(item) {
//alert("success!!"+JSON.stringify(item))
return {
value : item
};
}));
} catch (e) {
alert(e);
}
},
error : function() {
alert('Cannot connect to REST API!!!');
}
});
},
minLength : 4
});
});
You need to set dataType to jsonp in your ajax request.
type: "GET",
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url: "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data: { name: "bard"},
dataType: "jsonp",
crossdomain: true,
Related
I have this code on my JavaScript file:
temp="string";
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: myJson,
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(temp.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
console.log(errorThrown);
ConnectionChanged();
}
});
And this controller:
[HttpPost]
public string updateStatus(string updatedJson)
{
var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json")));
... }
I tried to change $.ajax to $.post method, also changed
public string updateStatus
to
public JsonResult updatedStatus
But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?
temp="string";
// (0)
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '', // (2)
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(response.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
ConnectionChanged();
}
});
Or if this does not have to be passed as a parameter, then do the following:
(0) var formData = new FormData(); formData.append('updatedJson', temp);
(1) url: '/MemoryGame/updateStatus',
(2) data: formData,
$.ajax is a fonction from the jQuery library, does your project include it ?
You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.
I have an openIDM program and when users submit for update new password , it show "X-openIDM-Reauth-Password" which include my old password that i need to retype. Following is the screen shot from openidm side.
So, i have my own UI and i was request from javascript ajax side with following ajax call.
$.ajax({
contentType: "application/json; charset=UTF-8",
datatype: 'json',
url: targetHost+"openidm/managed/user/"+userId,
xhrFields: {
withCredentials: true,
},
headers: {
"X-Requested-With":"XMLHttpRequest" ,
"X-OpenIDM-Reauth-Password": oldPassword
},
crossDomain:true,
data: JSON.stringify(data),
type: 'PATCH',
success:function(result) {
console.log("success");
swal({
title: updateSuccessMsgs.formSubmit.slogan,
text: updateSuccessMsgs.formSubmit.success,
type: "success"
}, function() {
window.location = "my-profile.html";
});
},
error:function (error){
sweetAlert(updateErrorMsgs.updateError.slogan, updateErrorMsgs.updateError.fail, "error");
console.log(error);
}
});
and it throw me this error.
XMLHttpRequest cannot load http://localhost:9090/openidm/managed/user/09096425-4ff1-42d4-8a4d-3a6b5004afca. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Can someone explain me why? Appreciate it.
I found the solution. I try to add one more value in servletfilter-cors.json as follow. I added the value of "X-OpenIDM-Reauth-Password" in "allowedHeaders" and it is success.
{
"classPathURLs" : [ ],
"systemProperties" : { },
"requestAttributes" : { },
"scriptExtensions" : { },
"initParams" : {
"allowedOrigins" : "*",
"allowedMethods" : "GET,POST,PUT,DELETE,PATCH",
"allowedHeaders" : "accept,x-openidm-password,x-openidm-nosession,x-openidm-username,content-type,origin,X-OpenIDM-Reauth-Password,x-requested-with",
"allowCredentials" : "true",
"chainPreflight" : "false"
},
"urlPatterns" : [
"/*"
],
"filterClass" : "org.eclipse.jetty.servlets.CrossOriginFilter"
}
I have a javascript code that calls a web service from another server, it's working, but i need to call it from code behind due to an http call request issue, following my code :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://10.8.111.12:7181/CatchEventLink.asmx/CollectDataLink",
data: JSON.stringify({ "pDataDictionnary": lDataCollected }),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
//alert('success');
}
},
error: function (exception) {
//alert('Exeption : ' + exception);
}
});
Any suggestions please??
I'm sending this request, and it is perfectly fine as long as it's successful. However, if I try to create a user with existing username or email, I should get 400 bad request and response detailing what's the problem.
Thing is, when I send this request and get 400, nothing gets written to console/console (not even the 'fail!' string), but I can see that response is correct in console/network tab so the problem is probably not in the backend.
$("#registerForm").submit(function(e){
e.preventDefault()
$.ajax({
type: "POST",
url: "./register",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
"username": formcontent['username'],
"email": formcontent['email'],
"password": formcontent['password'],
}),
success: function(e) {
window.location.href = './login'
return false
},
fail: function(e) {
console.log('fail!')
console.log(e)
//react to error
return false
},
})
})
I think 'fail' is a invalid function, Please try with below structure
$.ajax({
type : "POST",
url : "/register",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : JSON.stringify({
"username" : formcontent['username'],
"email" : formcontent['email'],
"password" : formcontent['password'],
}),
success : function(response) {
console.log(response);
},
error : function(response, status, err) {
console.log(response);
console.log(status);
console.log(err);
}
});
I have WCF service method:
[WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
[OperationContract]
bool validateLogin(Login objLogin);
I am calling this method through my phonegap code ajax as:
var parameters = {
"EmailID": EmailID,
"Password": Password
};
$.ajax({
url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
data: JSON.stringify(parameters),
contentType: "text/xml;charset=utf-8",
dataType: "json",
headers: {
SOAPAction: ''
},
type: 'POST',
processdata: false,
cache: false,
success: function (Data) {
alert("asdsad");
},
error: function (response) {
var value = JSON.stringify(response);
alert("Error in Saving.Please try later."+value);
}
});
But service method is not getting called.
On Network tab it gives me error:
And On Console:
EDIT1:
When i change contenttyp to :appplication/json;charset=utf-8
http://api.jquery.com/jquery.ajax/
crossDomain point in doc
Check it, u send cross domain ajax. It's not allowed by default.
Most probably because of Parameters which you are passing and return type of WCF service. The method should return Object instead of bool. The .Net framework will convert the returned object to the JSON string automatically for you.
Service Side :
[WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
[OperationContract]
Object validateLogin(String Email, String Password)
{
//Do your stuff return bool value
}
AJAX Call :
$.ajax({
url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
data: function ( {
return JSON.stringify({
Email: "abc#xyz.com",
Password: "XXXXXXXXXX"
});
},
contentType: "text/xml;charset=utf-8",
dataType: "json",
headers: {
SOAPAction: ''
},
type: 'POST',
processdata: false,
cache: false,
success: function (Data) {
alert("asdsad");
},
error: function (response) {
var value = JSON.stringify(response);
alert("Error in Saving.Please try later."+value);
}
});