I'd like to use ajax to retrieve a token.
In accordance to this documentation, below is the URL, request headers, and request body
POST https://api-production.august.com/session
Request Headers:
x-august-api-key: 727dba56-fe45–498d-b4aa-293f96aae0e5
x-kease-api-key: 727dba56-fe45–498d-b4aa-293f96aae0e5
Content-Type: application/json
Accept-Version: 0.0.1
User-Agent: August/Luna-3.2.2
Request Body: (JSON Encoded)
{
"installId": <Random UUID>,
"password": "XXXXXXXX",
"identifier": "phone:+15555551234"
}
I've tried to implement this with ajax as such
$.ajax({
type: "POST",
url: "https://api-production.august.com/session",
dataType: "json",
headers:{
"x-august-api-key":"727dba56-fe45–498d-b4aa-293f96aae0e5",
"x-kease-api-key":"727dba56-fe45–498d-b4aa-293f96aae0e5",
"Content-Type": "application/json",
"Accept-Version": "0.0.1",
"User-Agent": "August/Luna-3.2.2"
},
data: JSON.stringify({installId: "7fb17963-21a8-4c23-8f81-121ed3298ad8",
password: "password",
identifier: "phone:+18885554444"})})
However I dont get the token and I get the following response:
abort: function abort()
always: function always()
catch: function catch()
done: function add()
fail: function add()
getAllResponseHeaders: function getAllResponseHeaders()
getResponseHeader: function getResponseHeader()
overrideMimeType: function overrideMimeType()
pipe: function pipe()
progress: function add()
promise: function promise()
readyState: 0
responseJSON: undefined
setRequestHeader: function setRequestHeader()
state: function state()
status: 0
statusCode: function statusCode()
statusText: "error"
then: function then()
The error is the following:
my error: ajax TypeError: Cannot convert string to ByteString because the character at index 13 has value 8211 which is greater than 255.
I've also tried running this in google chrome, but I get the following error:
"TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': Value is not a valid ByteString."
I've also tried the following to no avail as I get the same error:
$.ajax({
type: "POST",
url: "https://api-production.august.com/session",
dataType: "json",
beforeSend: function(request) {
request.setRequestHeader("x-august-api-key", "727dba56-fe45–498d-b4aa-293f96aae0e5");
},
data: JSON.stringify({installId: "7fb17963-21a8-4c23-8f81-121ed3298ad8",
password: "password",
identifier: "phone:+18885554444"})})
Your first error is kinda vague but it does mention "the character at index 13" (aka the 14th character). Your second error helps you see that the problem comes from setRequestHeader. So you should look at the strings that you pass to setRequestHeader and more specifically, the 14th character in those strings.
x-august-api-key
727dba56-fe45–498d-b4aa-293f96aae0e5
Now we ask ourselves, which one of these characters k or – is more likely to be causing us issues? It should be intuitive that the – is more likely to be the offending character so we take a closer look at it.
At this point we should be suspecting that we aren't using a hyphen character (ascii value of 45) but some other character that looks like a hyphen. Indeed, if we look up the ascii value 8211 (8211 comes from your first error) we see that the associated character is the en dash.
Some editors/viewers make the characters look different while others make it look the same. For me using Google Chrome to view this question, I can compare the hyphens in your key and I can see that the 2nd "hyphen" does not look like the rest. It's a tad longer.
hyphen: -
en dash: –
So you should replace the en dash character with the hyphen character in your key. Then your string should be able to be converted to ByteString no problem.
Related
Trying to make fast queries to the Bing search API (azure marketplace).
The goal is to call the bing api and return the search results to the page. However, I need to make it really fast, possibly as fast as the end-user search on bing.com. Here is my code:
<div id="id01"></div>
<script>
$.ajax({
url: "https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27martin%27",
password:"XXXXXXXXXXXX",
success: function(data){
$("id01").html(data);
}
});
</script>
The password is filled with my account key. User should be blank. The above code does not return a result - not sure why. I included Ajax.
I'm aware of same-origin policy, but I assume for the API they set appropriate X-headers.
It looks to be problem with your ajax call, try doing it as follows:
$.ajax({
url: "your-url",
type: 'GET',
dataType: 'jsonp',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic bHVpZ2lAZ21haWwuY29tOmFiYzEyMzQ1');
},
success: function(data){
$("id01").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
})
Where second field inside xhr.setRequestHeader() is calculated as follows:
The username and password are combined into a string separated by a
colon, e.g.: username:password
The resulting string is encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line.
The authorization method and a space i.e. "Basic " is then put before the encoded string.
For example, if the user agent uses Aladdin as the username and OpenSesame as the password then the field is formed as follows:
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
In your case you may need to use your api key as username as well as password both.
We have an ios application built with trigger.io. this application is using forge.request.ajax to send data to our servers. one of our requests occasionally throws an error and returns this:
{"message":"Invalid parameter not satisfying: url","type":"UNEXPECTED_FAILURE"}
since the input parameters are sent in json format I suspected that some characters inputted by users, could break the structure and cause this error. my code looks like this:
forge.request.ajax({
url: "someurl.php",
dataType: "json",
data:"some=data&and=some&more=data&which=is inputted by user",
success: function (data) {
},
error: function (error) {
forge.request.ajax({
url: "errorlog.php",
dataType: "json",
data:"data=" + encodeURIComponent(JSON.stringify(error)),
success: function (data) {
},
error: function (error) {
}
});
}
});
this code gives the above error half the time. and work on the other half. are there any limitations for input parameters in ajax request? since i can't edit objective-c code, i need a solution - preferably a filter- which ensures this function to work with whatever input is entered.
Using encodeURIComponent may help:
var data = "some=data&and=some&more=data&which=is inputted by user";
forge.request.ajax({
url: "someurl.php",
dataType: "json",
data: encodeURIComponent(data)
...
Passing request data as URL Parameters has more than it's share of gotchas though so it may also be worth taking a look at this StackOverflow question: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
I've read a couple of posts here regarding how to do this and I can get it working only half-way.
This works (sending json object as text):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: '{"reqid":0,"iid":2,"description":"adsf"}',
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
This does not (sending object as json):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: {"reqid":0,"iid":2,"description":"adsf"},
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
And what I really want to do is something like this (I've already set up the proper combinators):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: #Html(Json.stringify(Json.toJson(item))),
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
My controller looks like this:
def addItem(id: Long) = Action (parse.json) { implicit request =>
Logger.info("add item")
request.body.validate(Item.itemReads).map { item =>
thing.addItem(item)
Ok("Succesfully added item.")
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
In the second case, it never gets to the logging code. Instead it returns a 400 Bad Request immediately (this is likely something triggered in the Action (parse.json) bit I think).
I'd rather send the object as json because when I convert to string and description happens to have an apostrophe in it (') that messes things up. I could probaby escape the apostrophe, but hoping that I'm missing something simple about how to do this with an object rather than a string.
Thanks
As described in the API the dataType param is for setting:
The type of data that you're expecting back from the server.
For sending the json use your second approach (don't send it as a String). Use web browser inspector to validate if correct data were send. AFAIK you shouldn't have problem with Handling the JSON request after receiving valid JSON object
If you are trying to send a non-stringified JSON object in Jquery, $.ajax automatically tries to process it with $.param,
If your data in the ajax call looks like this:
data: {"reqid":0,"iid":2,"description":"adsf"}
This is what $.ajax is doing under the hood before sending:
$.param({"reqid":0,"iid":2,"description":"adsf"})
// "reqid=0&iid=2&description=adsf"
It takes the JSON and serializes it into a form-url-encoded format. Whereas your server is expecting JSON. I would suggest the best way to get around this is to just stringify before sending:
data: JSON.stringify({"reqid":0,"iid":2,"description":"adsf"})
Source: http://api.jquery.com/jQuery.ajax/#sending-data-to-server
I am making a cross browser jsonp call in which my backend to which i am sending some values is made using django and getting some after callback to my front end which is in php . The problem is its giving Uncaught SyntaxError: Unexpected token : error The data is being send from the django and i have checked that. i am using the code below to make jsonp calls
$(document).on('click', '.miloginme', function(event) {
var username = $('#username').val();
var password = $('#password').val();
var token = $('#token').val();
var dataString="uid="+username+"&token="+token;
$.ajax({
type: 'POST',
url: "http://localhost:8000/b/authenticate/",
crossDomain: true,
data: dataString,
async: false,
dataType: 'jsonp',
success: function(data) {
alert(data);
}
});
});
the values in callback that i am getting is in format
{"token": "KAMWMS151UWPR4Q", "authenticate": "1", "userid": "brad", "fname": "rahul", "booster_number": "1"}
tldr; The server is not sending back JSONP.
Value reported in the post is JSON (and it is valid JSON) - it is not JSONP. If it were to be treated as JSONP (i.e. evaluated by a <script>) then it would be a syntax error because it is not a valid JavaScript program.
Try this in a JavaScript console:
{"token": "KAMWMS151UWPR4Q", "authenticate": "1", "userid": "brad", "fname": "rahul", "booster_number": "1"}
Error look familiar? (Different browses can return different error messages: Chrome -> "Unexpected token :", FireFox -> "invalid label", IE9 -> "Expected ';'".)
A valid JSONP result would look similar to:
theCallback({"token": "KAMWMS151UWPR4Q", "authenticate": "1", "userid": "brad", "fname": "rahul", "booster_number": "1"})
(The name of theCallback is taken from the jsonp variable passed to the server and the client - e.g. jQuery - creates this function before the injecting <script> element is created so that the function can be invoked using the above syntax.)
Valid JSONP works because the "JSON" data is then run in an expression context (in which it is treated as a valid JavaScript Object Literal), not a statement context (where it is treated as a label and then "some junk" leading to a syntax error).
Common approaches to return JSONP from Django utilize View Decorators:
Django JSONP Decorator
Returning JSON/JSONP from a Django view with a little decorator help
jsonp_decorator.py
I upgraded my page from using jquery 1.4.4 to jquery 1.9.1 and suddenly my ajax calls stopped working. If i revert to jquery 1.4.4 it works again. I am getting below error.
No conversion from text to string
Below is my code
$.ajax({ url: "/Reporting/RunQuery",
type: "Post",
data: { prm_Query: qrytxt }, dataType: "string",
error: function (XMLHttpRequest, status, error) {
debugger;
alert("The following error occured while adding data: " + error);
},
success: function (data) {
debugger;
$('#divQuerytextarea').html('').append(data);
}
});
My call to /Reporting/RunQuery succeeds and it has valid return string in the RunQuery method. Then it falls into error: of ajax call with 'No conversion from text to string' error.
Not finding much in google for this. Any help is appreciated.
I agree with Kevin. I was having the same problem just because I've put :
dataType: JSON
instead of :
dataType: "json"
after what everything worked fine.
Be aware that this "dataType" property commes from the HTTP head where there is the MIME type wich is the type of the resource called by the HTTP request. So there is no "string" type. You should use "text" instead (if you want a string, of course).