I have a controller written in python cherrypy that should check if a db url is valid by attepting to make a connection. I'm having problems however passing the parameter to the method. My ajax call is:
$.ajax({ async : false,
type: 'POST',
url: "/settings/check_db_url/"+db_url ,
success: function(r) { alert(r) },
error: function(r) { alert('failure') }
});
Now the problem the urls that I need to test are in the form of:
'sqlite':'sqlite:///Users/Home/tvb-database.db' or
'postgresql+psycopg2://postgres:root#127.0.0.1:5432/tvb?user=postgres&password=postgres'
For the sqlite part I managed to pass it if I do something like:
db_url = db_url.split('/').join('__')
db_url = db_url.split(':').join('x_xxx_x')
And then replace back in python. But this seems so hacky to me and for the postgress part I guess I'll have to replace some more. So what is the correct way to handle this?
Send it as part of a POST parameter and not as part of the url using the data option:
$.ajax({
async : false,
type: 'POST',
url: '/settings/check_db_url',
data: { db_url: db_url },
success: function(r) { alert(r) },
error: function(r) { alert('failure') }
});
And in your server read the db_url POST parameter.
Related
I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
I am currently using the dark sky forecast api https://developer.forecast.io/ to retrieve json object via jquery get request.the required url parameters format is (api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE") while the valid format with the parameters is:
https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115
inputting this url in your browser will show you a json object.
First thing i tried was a jquery get request :
$.ajax({
type: 'GET'
, data: ''
, url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115"
, success: function (data) {
alert("works");
}
, datatype: 'json'
, error: function (err) {
alert("Could not get forecast");
}
});
this is not succesful- it triggers the error function. i try again using a post request it doesnt work either.please help
This is a simple CORS issue which can be easily resolved by using jsonp datatype:
$.ajax({
url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115",
dataType: "jsonp",
success: function(data) {
console.log(data.latitude, data.longitude);
console.log(data.timezone);
console.log(data.daily.summary);
},
error: function(err) {
console.log("Could not get forecast");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<em>Loading . . .<em>
I am stumped as to how to solve/diagnose ajax/jquery error.
This is my function:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
I get this error:
jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.
So basically you will need to use GET instead:
type: "GET"
Also since the data is sent as query string parameters you should remove the content type:
contentType: "application/json",
and do not JSON.stringify the data.
And here's the full example:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
Of course this will work only if the remote endpoint supports JSONP and the GET verb.
Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "¶m2=" + param2 + "¶m3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);
I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.