I should make a json call with javascript:
var arr = { username: "user#user.com", password : "mypassword" , portfolioID : "xxxxxxxxxxxxxxxxx" };
$.ajax({
url: 'https://siam.eseye.com/login',
type: 'POST',
data: JSON.stringify(arr),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: false,
success: function(msg) {
alert(msg);
}
});
the error that comes back to me : CORS header " Access- Control-Allow -Origin " missing .
Attention, before saying that it is a double question , read here , I searched online and I did :
inserted header ( " Access- Control-Allow -Origin : * " ) ;
Wamp > Apache > Apache Modules > headers_module enabled
added the datatype
dataType: json or jsonp the error remain
after all of this evidence , it will not work the same .
Is there anything else I forgot to try?
with Postman the API work.
Thank you.
You may need to use dataType: "jsonp" which is use for cross site scripting.Check here for more about jsonp
I created this JSFIDDLE. The request semms to be served but the response have error. You can validate it console in developer's tool
Related
and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"
I'm new to AJAX and I want to generate a password over this API. I want to use AJAX but dont know exactly how and where to specify the parameters.
$.ajax({
url: 'https://passwordwolf.com/?length=10&upper=off&lower=off&special=off&exclude=012345&repeat=5',
dataType: "text json",
type: "POST",
data: {upper: off, lower: on, special: off},
success: function(jsonObject,status) {
console.log("function() ajaxPost : " + status);
}
});
Many Thanks, Pls don't hate my programming skills!
Having a look at their API:
You should use the GET method, not POST.
The url should be https://passwordwolf.com/api/ (notice the /api at the end).
Besides, passwordwolf doesn't accept CORS, so you should probably call that service from your server side and mirror it to your frontend with the appropriate CORS headers.
See demo below (it uses cors-anywhere to circunvent the CORS problem).
It also shows how to correctly use an object to set params.
var CORS = 'https://cors-anywhere.herokuapp.com/';
$.ajax({
url: CORS + 'https://passwordwolf.com/api/',
dataType: "json",
type: "GET",
data: {
length: 10,
upper: "off",
lower: "off",
special: "off",
exclude: "012345",
repeat: 5
},
success: function(jsonObject, status) {
console.log("ajax result: " + JSON.stringify(jsonObject));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I've looked at many similar questions on here, but I am unable to get to the bottom of this issue.
I've built a Web API, and if I post at it using curl as follows:
curl -i -H "Content-Type: application/json" -X POST -d '{"password":"abcd"}' http://<ip>:5000/api/v1.0/state
My API receives the message and records:
<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
{u'password': u'abcd'}
192.168.1.100 - - [08/Feb/2016 21:04:32] "POST /api/v1.0/stateHTTP/1.1" 200 -
So far so good....
I've built a webpage with the following code (I am brand new to web dev), which I am using to post against this API:
function myFunction() {
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
data: {"password" : "John"},
success: function(data){
alert(data);
}
});
}
When calling this function, the post is clearly recieved by my API, but without any data:
<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
None
192.168.1.120 - - [08/Feb/2016 21:09:53] "POST /api/v1.0/state HTTP/1.1" 200 -
I've tried using a $.post method:
$.post(
"http://" + document.domain + ":5000/api/v1.0/state",
JSON.stringify({"password" : "password" }) ,
function(data) {
alert("Response: " + data);
}
);
And I get the same result.
EDIT: Tried using the following code, as suggested by an answer below:
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
contentType:'application/json',
data: JSON.stringify({"password" : "John"}),
success: function(data){
alert(data);
}
});
And I receive an OPTIONS API response:
192.168.1.120 - - [08/Feb/2016 21:31:28] "OPTIONS /api/v1.0/state HTTP/1.1" 200 -
Any thoughts? I'm able to hit the server, but can't get any JSON data across.
Thanks!
By your curl snippet it looks like your endpoint is expecting a JSON request payload. jQuery does not set a content-type request header of application/json, so you have to actually tell it to do so:
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
contentType:'application/json',
data: JSON.stringify({"password" : "John"}),
success: function(data){
alert(data);
}
});
Also note if this is being used on a different domain, meaning not "http://" + document.domain + ":5000, you may end up hitting a CORS issue.
I've been reading a lot of questions about this error, but just can't seem to get around it (it's incredible how many questions can be found on the web on this topic!!). Let me be straight:
test.asmx
'Simple POST (obviously with parameters)
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json)>
Public Function TestarPost(ByVal Valor as String) As String
Dim x
End Function
'Simple GET - no parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function Testar() As String
return "ok ;>D"
End Function
'GET with parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function TestarGet(ByVal Valor as String) As String
return Valor
End Function
Trying it out in js console window:
obj = { Valor: "x" }
$.ajax({
type: "POST",
url: "test.asmx/TestarPost",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success!
$.ajax({
type: "GET",
url: "ServerSide.asmx/Testar",
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success! Returns correctly data in JSON format
$.ajax({
type: "GET",
url: "test.asmx/TestarGet",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Fails! Doing the same as in Post
The message error is "Invalid web service call, missing value for parameter: \u0027Valor\u0027." Also fails if I send object literal ("Invalide JSON primitive"). However, if I access URL .../ServerSide.asmx/TestarGet?Valor=x, it returns "opa" (maybe a clue?)
What I don't get (pardon the pun) is why, since it's the same as in POST. Maybe because the POST isn't affecting anything and I can't see the result (but it returns no errors, at least).
My goal is to create a function serverSide(asmxMethod, obj) to make a generalized bridge between client and server functions.
I've found a solution (but not an answer). According to a friend, GET doesn't accept json parameters. Unfortunately, even if I send dataType: "text" it fails.
The solution is to use always POST. POST is also able to return data (didn't know that). So with the POST example I can send and receive data in json format without a problem.
I am having problem displaying accented character in my app; It is showing ⛽ instead of ó. The string is coming from a json file retrieved from a server. Here are the technical details:
JSON: (This is the object being retrieved from the server)
notice the 3rd key "Relación" the letter "o" is accented.
[
{
"key": "Canales"
},
{
"key": "Productos"
},
{
"key": "Relación con el ejecutivo"
}
]
Ajax (here is the code to retrieve the information)
notice I already added charset=utf-8 as most answers suggest
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(uri){
alert("clintg test: " + JSON.stringify(uri));
}
}
Alert: (as you can see, it is just showing a box symbol where it's supposed to be -> ó)
To give more detail to #georg 's advice that helped me solve this issue:
Since I can't change the server side scripts, I adjusted the code on my side.
I changed the charset in my ajax request to ISO-8859-1, but since the default charset of ajax is utf-8, I had to override the charset with $.ajax.beforeSend:
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json; charset=iso-8859-1",
success: function(uri){
alert("clintg test: " + JSON.stringify(uri));
},
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('application/json;charset=iso-8859-1');
}
}
Here's a link to the question that helped me figure out and override the charset: Jquery ignores encoding ISO-8859-1