After authentication with Google oauth2.login getting access_token and expires_in. Everithing going great till my token expires. After expiration, when I send again request for data with old token like that:
var URLHead = 'https://www.google.com/fusiontables/api/query?sql='
var URLTable = encodeURI('SELECT id,COUNT() FROM TABLE_ID')
var URLTail = '&access_token='+ old_token +'&jsonCallback=?'
var queryURL = URLHead + URLTable + URLTail
var jqxhr = $.ajax({
type: "GET",
url: queryURL,
dataType: 'jsonp',
success: function (d) {
var max = d.table.rows[0].toString().substr(1)
localStorage.setItem('cpage', Math.ceil(max / localStorage.getItem('delimeter')))
},
error: function(){alert('token_expired')}
})
working on success and giving nothing if token expired. All over the internet can't find clear example how to handle expiration? Shouold I count myself 3600 seconds and delete old_token or is there any elegant way to handle token expiration error?
What does the response look like when the token has expired? The API is not necessarily going to throw an error, just a normal JSON response. The response probably contains something to say that the token has expired which you can therefore use to check on the fly.
Try:
success: function (d) {
if(d.error){
if(d.error == 'invalid_token'){
alert('invalid_token');
}
} else {
// local storage etc
}
}
or (with error handling) :
var request = $.ajax({
url: "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44Az%20%E2%80%8BqT3Zg",
type: "GET",
});
request.done(function(msg) {
// complete
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Heres the fiddle : http://jsfiddle.net/MFe9d/
Related
when i run below code.
it makes error and alert "fail error:StntaxError: Unexpected token < in JSON at position 0 data:undefined"
what is the problem ??
$("#a").click(function () {
st_dt = $("#st_dt").val();
end_dt = $("#end_dt").val();
lot_cd = $("#lot_cd").val();
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
var json_1 = JSON.stringify(obj);
$.ajax({
type: "POST",
url: '{{ url_for("get_operid") }}',
data: json_1,
dataType: "JSON",
success: function (data) {
alert("Success\n" + data);
},
error: function (request, status, error, data) {
alert("fail\n" + "error:" + error + "\n data:" + data);
}
});
});
Looking at the code it looks like a Laravel API request using Blade Template or the Function url_for is in Flask... In either case
That means the response for the api request is HTML string instead of
a json response...
i.e. The API request is returning a login page or some HTML page...
To check the response you can open the Chrome Devtools in the Network tab check the response of the API...
what you can try is :
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
console.log(obj);
var json_1 = JSON.stringify(obj);
console.log(json_1);
Then See in browser console what is your object and if the JSON converting your object properly.
If that is ok , Your request should be done currectly. And try to see what are the data you getting as response with:
success: function (data) {
consoel.log('response below');
console.log(data);
}
You will find the error. I hope.
I'm trying to send a user picture to my api with Slim 3, PHP 7 and JQuery 2.1.1
But when I call api in HTML page then I get couple errors in Apache log, it seems that data arguments are empty and I dont know why.
Someone could help?
-------HTML source code api call
function savePicture(){
var fID = $('#edtIDUser').val();
var fPicture = document.getElementById('img').src;
$.ajax({
type:"POST",
cache:false,
url:"index.php/user_picture/",
timeout:3000,
contentType:"application/json; charset=utf-8",
data:{'id_user': fID, 'picture': fPicture},
dataType:"text",
async:false,
error: function (request, error) {
alert("error");
},
success: function (result) {
alert("ok");
}
});
}
AND API
----API source code
$app->post('/user_picture/', function(Request $request, Response $response) {
$params = $request->getParsedBody();
$iduser = $params['id_user'];
$uploadedFile = $request->getUploadedFiles();
$img = $uploadedFile['picture'];
$data = file_get_contents($img);
$escaped = bin2hex($data);
//TO-DO
}
Error #1: Trying to access array offset on value of type null in $params['id_user']
Error #2: Undefined index 'picture'
Error #3: file_get_contents(): Filename cannot be empty
I have a REST API (served by an external server) replying JSON formatted data.
From what I read from Tableau doc, there's available:
- WebDataConnector but you have to add a JS overload on your webpages, not very suitable for REST APIs
- importing JSON data from file, but doesn't answer my issue
Isn't there a simple way to integrate JSON data requested via REST call ?
You can use WDC, you are wrong that its not suitable for REST API. So you basically need to create 2 functions for getting fields and data for your datasets from API:
myConnector.getSchema = function (schemaCallback) {
$.ajax({
url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data/one",
type: "GET",
headers: {
'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey']
},
success: function(response){
var flatten = objectFlatten(response)
var columns = []
for (var key in flatten) {
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
columns.push({
id: id,
alias: key,
dataType: tableauType(flatten[key])
})
}
var table = {
id: "digger_" + JSON.parse(tableau.connectionData)['diggerID'],
alias: tableau.connectionName,
columns: columns
}
schemaCallback([table]);
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset.");
}
});
};
myConnector.getData = function (table, doneCallback) {
$.ajax({
url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data",
type: "GET",
headers: {
'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey']
},
success: function(response){
var data = []
for (var i=0; i < response.length; i++) {
var flatten = objectFlatten(response[i])
var rec = {}
for (var key in flatten) {
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
rec[id] = flatten[key]
}
data.push(rec)
}
table.appendRows(data);
doneCallback();
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset.");
}
});
};
For complete code you can check out for source code on github: https://github.com/Diggernaut/diggernaut-wdc
I am new to HTML development.
I am developing a mobile application using phonegap- HTML5.
I want to call a web service which is written in JAVA returning SOAP message.
I am calling my webservice using XmlHttp reguest but which on execution returns null data and status as 0.
So, my question is how can I call webservice in an HTML page?
What should I do to call Java SOAP webservice from HTML page?
Please any help is appreciated.
Please suggest any method soon.
Thanks in advance.
You need to make a soap request in a js file.
In your js file you should have something like this:
function sendSOAPRequest(webServiceMethod, params, callbackMethod, isAsynchronous, callContext)
{
//Get the token from local storage
var token = window.localStorage.getItem("token");
//Get the soap envelope with given parameters
var soapEnvelope = getEnvelopeFromParam(webServiceMethod, params);
//Send the soap request
$.ajax({
url: "https://www.zzz.com/yyy/soap",
type: "POST",
dataType: "xml",
data: soapEnvelope,
context: callContext,
complete: callbackMethod,
async: isAsynchronous,
timeout: 60000,
contentType: "text/xml; charset=\"utf-8\"",
beforeSend: function (xhr) {
xhr.setRequestHeader('SOAPAction', 'http://zzz.com/yyy/uuu/Iooo/' + webServiceMethod);
xhr.setRequestHeader('Authorization', token);
}
});
}
function getEnvelopeFromParam(webServiceMethod, parameters)
{
var soapEnvelope = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><' + webServiceMethod + ' xmlns="http://zzz.com/yyy/uuu">';
$.each(parameters, function(key, value) {
if(value)
{
soapEnvelope += '<' + key + '>' + value + '</' + key + '>';
}
else
{
//Send a null value
soapEnvelope += '<' + key + ' i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>';
}
});
soapEnvelope += '</' + webServiceMethod + '></s:Body></s:Envelope>';
return soapEnvelope;
}
this is a method to call webservice. You have the specify the right adresses corresponding to your server.
Now include this js file in your html
<script type="text/javascript" src="myFile.js"></script>
Now you have to call your js function from your html page (for exemple)
sendSOAPRequest("myfunction", params, endFunction, true, this);
And you have to define the endFunction
function endFunction(xmlHttpRequest, status)
{
//Work with xmlHttpRequest and check status
}
Am trying to post json data to the server. am using visual studio 2012 RC and windowsazure for hosting the web application . On posting am getting the following errors :
OPTIONS http://*.azurewebsites.net/api/Child 405 (Method Not Allowed) jquery-1.7.1.js:8102
XMLHttpRequest cannot load http://*.azurewebsites.net/api/Child. Origin null is not allowed by Access-Control-Allow-Origin.
My client side code is :
function PostChild() {
var Chld = {};
Chld.Child_FirstName = $("#Child_FirstName").val();
Chld.Child_LastName = $("#Child_LastName").val();
Chld.Child_Age = $("#Child_Age").val();
var createurl = "http://*.azurewebsites.net/api/Child";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Chld),
statusCode: {
200: function () {
$("#txtmsg").val("done");
alert('Success');
}
},
error:
function (res) {
alert('Error');
$("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText);
}
});
}
My server side code is :
public HttpResponseMessage PostChild(Child child)
{
if (ModelState.IsValid)
{
db.Children.Add(child);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, child);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = child.ChildID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Help me please
Thanks,
The errors was due to CORS (Cross Origin Resource sharing). By default, a web page cannot make calls to services (APIs) on a domain other than the one where the page came from. This is a security measure to avoid cross-site forgery attacks and all.
To solve it follow this tutorial:
http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx