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.
Related
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 am working in NodeJS with CouchDB 2.1.1.
I'm using the http.request() method to set various config settings using the CouchDB API.
Here's their API reference, yes, I've read it:
Configuration API
Here's an example of a working request to set the logging level:
const http = require('http');
var configOptions = {
host: 'localhost',
path: '/_node/couchdb#localhost/_config/',
port:5984,
header: {
'Content-Type': 'application/json'
}
};
function setLogLevel(){
configOptions.path = configOptions.path+'log/level';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldLogLevel: " + responseString);
});
});
var data = '\"critical\"';
req.write(data);
req.end();
}
setLogLevel();
I had to escape all the quotes and such, which was expected.
Now I'm trying to get CouchDb to accept a setting for compaction.
The problem is that I'm attempting to replicate this same request to a different setting but that setting doesn't have a simple structure, though it appears to be "just a String" as well.
The CouchDB API is yelling at me about invalid JSON formats and I've tried a boatload of escape sequences and attempts to parse the JSON in various ways to get it to behave the way I think it should.
I can use Chrome's Advanced Rest Client to send this payload, and it is successful:
Request Method: PUT
Request URL: http://localhost:5984/_node/couchdb#localhost/_config/compactions/_default
Request Body: "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]"
This returns a "200 OK"
When I execute the following function in my node app, I get a response of:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
function setCompaction(){
configOptions.path = configOptions.path+'compactions/_default';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldCompaction: " + responseString);
});
});
var data = "\"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]\"";
req.write(data);
req.end();
}
Can someone point at what I'm missing here?
Thanks in advance.
You need to use node's JSON module to prepare the data for transport:
var data = '[{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}]';
// Show the formatted data for the requests' payload.
JSON.stringify(data);
> '"[{db_fragmentation, \\"70%\\"}, {view_fragmentation, \\"60%\\"}, {from, \\"23:
00\\"}, {to, \\"04:00\\"}]"'
// Format data for the payload.
req.write(JSON.stringify(data));
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 sending data through post function in angular and it works fine.
$scope.contact_details = [
{"name":"Username",
"email":"username#gmail.com",
"mobile":"XXXXXXXXXX",
}]
var data = {
contact_details : $scope.contact_details
};
var url = API_URL + "/addcontacts?token=" + token ;
$http({
method: 'POST',
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(response) {
console.log("MyContactDetails : ",response);
}).error(function(response) {
console.log(response);
});
When I use POSTMAN or RESTClient, I enter the url with token and select method POST. I paste the following in body
[{"name":"Username","email":"username#gmail.com","mobile":"XXXXXXXXXX",}]
This does not work and I get error in my Laravel function :-
Invalid argument supplied for foreach()
My Laravel function in controller :-
public function addContact(Request $request){
$contacts = $request->input('contact_details');
$company_id = Auth::guard('api')->user()->company_id;
foreach($contacts as $contact){
$addContact = new ContactList();
...
}
In the [{"name":"Username","email":"username#gmail.com","mobile":"XXXXXXXXXX",}] contact_details is empty.
Try:
[{"contact_details":{"name":"Username","email":"username#gmail.com","mobile":"XXXXXXXXXX"}}]
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/