jquery is this a valid http request - javascript

I have this http request
GET /deals/couchbaseDocument/_search
{
"query" : {
"match" : {
"amenities" : "Maids "
}
}
}
when i put it in curl, it gives me results, i want to build a web app to call that request.
what i did is removing the newlines and put the whole text in .getjson()
as this:
var query = $("#query").val();
query = query.replace(/(\r\n|\n|\r)/gm,"");
$.getJSON(query, function (results) {
alert("success");
alert(results);
})
.success(function () { alert(" second success"); })
.error(function () {
alert("error");
alert(query);
});
i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request
I read this
I found that .getJson could be like this:
$.getJSON('httpURL',
{ parameter1: "parameter value", parameter2: "parameter value" })
i wonder if i should pass my json request as a parameter
in case of the whole picture** i am working on sense elasticsearch plugin

According to the documentation of jQuery's getJson, you can pass a javascript object (jQuery.getJSON() | jQuery API Documentation) so you can do something like this
var queryData = {
"query" : {
"match" : {
"amenities" : "Maids "
}
}
};
$.getJSON('httpURL', queryData)

Related

POST a string value to firebase using angular-1 $http

I using angularjs1 in ionic-1 application and Firebase Database.
And I am trying to post a string to the database using firebase REST API.
I want the data to be in the following format:
Firebase generated Key: "My string"
But what I actually get is :
Can anyone help me to know how to send the data in http post function as a string ?
Here is my code:
.service('postFollowedUser', ['$http', '$q','baseURL', function($http, $q,baseURL){
var deferObject,
myMethods = {
postUser: function(uid,followedUid) {
var myPromise = $http({
method:'POST',
url: baseURL+'users/'+uid+'/followedUsers.json',
data:{followedUid}
}),
deferObject = deferObject || $q.defer();
myPromise.then(
// OnSuccess function
function(answer){
// This code will only run if we have a successful promise.
//alert('answer in servics'+JSON.stringify( answer));
deferObject.resolve(answer);
},
// OnFailure function
function(reason){
// This code will only run if we have a failed promise.
//alert(JSON.stringify( reason));
deferObject.reject(reason);
});
return deferObject.promise;
}
};
return myMethods;
}])
I tried to removing the curly braces but I got the following error:
"Invalid data; couldn't parse JSON object, array, or value."
Not sure if this is supported by firebase, but you are sending payload with object (data:{followedUid} is the same as data:{followedUid: followedUid}).
Try removing the curly braces:
$http({
method:'POST',
url: baseURL+'users/'+uid+'/followedUsers.json',
data: JSON.stringify(followedUid) // payload will be just the value of `followedUid`
})
Btw I am not sure what dark magic are you trying to do with the deferObject :] You can simply return the $http call, its return value is already a promise. You can still call then on it to process the results:
return $http.post(baseURL + 'users/' + uid + '/followedUsers.json', JSON.stringify(followedUid))
.then(function(answer) {
console.log(answer);
// return the answer so you can work with it later (again via `then`)
return answer;
}, function(error) {
console.log(error);
// throw the error so you can catch it later (possibly via `catch`)
throw error;
});

How do I retrieve an async value for a restangular parameter?

I need to retrieve a value from an async service to add as a parameter to every rest call. The casService.getProxyTicket() is an $http call...
I have the following code :-
myFactories.factory('myFactory', [
'Restangular'
, 'casService'
, function (Restangular
, casService) {
return Restangular.withConfig(function (config) {
config.setBaseUrl('https://host:port/somecontext/rest');
config.addFullRequestInterceptor(function (element
, operation
, route
, url
, headers
, params
, httpConfig) {
... What do I need to do here?
casService.getProxyTicket(url).then(function(st){
console.log('proxyTicket = ' + st.data.ticket);
});
params.ticket = ?????? <= st.data.ticket
...
return {
element: element
, headers: headers
, params: params
, httpConfig: httpConfig
}
});
}).service('myCollection');
}]
);
...thanks in advance!!!!
Ok, my lack of understanding coming from a backend developer's background...
This can/should NOT be done this way! I was trying to make the call to get a proxy ticket synchronous.... DON'T DO IT!
What I did was to rearrange my code thus ...
function readItem(id) {
var endpoint = myFactory.one(id);
return casService.getProxyTicket(endpoint.getRestangularUrl())
.then(function (response) {
return endpoint.get({ticket: response.data.proxyTicket});
}).then(function (response) {
return response.plain();
});
}
...works like a charm!

Didn't get json array in App js file

My service code look like belowed :-
data.service('SmartLearnerService', function ($http) {
//Get Single Records
this.get = function (id) {
return $http.get("/api/Category/");
}
});
Here is my controller code for App.js:-
$scope.questionlist = SmartLearnerService.get();
$scope.questionlist.then(function (pl) {
var res = pl.data;
$scope.que = res.QuestionLabel;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
console.log($scope.questionlist);
Here is Controller code for web api controller :-
public class CategoryController : ApiController
{
CommonDb db = new CommonDb();
public JsonResult Get()
{
var Result = db.GetQuestionById().ToList();
string message = "No Data Found";
if (Result.Count() != 0)
{
return new System.Web.Mvc.JsonResult()
{
Data = Result,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
else
{
return new System.Web.Mvc.JsonResult()
{
Data = message,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
}
}
}
And here is div tag where i want to bind questions from json result using ng-repeat directive.
<div class="question" align="center">{{Questions.QuestionLabel}}</div>
i am facing problem while binding json array in controller's $scope.questionlist and i am successfully getting json result from web api controller.
Ok, if I had to guess (and that's exactly what I'm doing), you want something like this in your controller...
SmartLearnerService.get().success(function(questions) {
$scope.questionList = questions;
});
or, if you're not a fan of the add-on success / error callbacks
SmartLearnerService.get().then(function(response) {
$scope.questionList = response.data;
});
and in your template
<div ng-repeat="question in questionList">
<div class="question" align="center">{{question.QuestionLabel}}</div>
<!-- and so on -->
</div>
This is totally assuming your C# controller returns JSON that looks something like...
[{
"QuestionID": "1",
"QuestionLabel": "Why are mirrors often slightly curved (convex) ?",
"Image": "zibra-crossing.jpg",
"Correct": "two",
"Explaination": "Question one explaination is goes here"
}, {
...
}]
Can you try this?
SmartLearnerService
.get()
.success(function (data, status) {
if (status === 200) {
//your code to process data is here
}else{alert(status)}
})
.error(function (data, status) {
//TODO: Use nice alert.
alert('Server request failed with status ' + status + ' while getting area in the ' + $item.Name);
});
You will get the status code that you are receiving and then you can change the code accordingly.
The approach that I took in my case was to serialize using JsonConvert from NewtonSoft and then return the string of Json object instead of Json object itself to improve the speed.

jquery.couchdb.js Ajax success/error not being called

I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});

Node.js - Can't post nested/escaped JSON to body using Fermata REST client

The problem may be with the actual client, but he's not responding on github, so I'll give this a shot!
I'm trying to post, in the body, nested JSON:
{
"rowkeys":[
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"{\"date\":\"2011-06-21T00:53:10.309Z\",\"disk0\":{\"kbt\":31.55,\"tps\":6,\"mbs\":0.17},\"cpu\":{\"us\":5,\"sy\":4,\"id\":90},\"load_average\":{\"m1\":0.85,\"m5\":0.86,\"m15\":0.78}}",
"ttl":10000
},
{
"columnname":"cn",
"columnvalue":"cv",
"ttl":10000
}
]
},
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"fd"
},
{
"columnname":"cn",
"columnvalue":"cv"
}
]
}
]
}
When I remove the columnvalue's json string, the POST works. Maybe there's something I'm missing regarding escaping? I've tried a few built in escape utilities to no avail.
var jsonString='the json string above here';
var sys = require('sys'),
rest = require('fermata'), // https://github.com/andyet/fermata
stack = require('long-stack-traces');
var token = ''; // Username
var accountId = ''; // Password
var api = rest.api({
url : 'http://url/v0.1/',
user : token,
password : accountId
});
var postParams = {
body: jsonString
};
(api(postParams)).post(function (error, result) {
if (error)
sys.puts(error);
sys.puts(result);
});
The API I'm posting to can't deserialize this.
{
"rowkeys":[
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":{
"date":"2011-06-21T00:53:10.309Z",
"disk0":{
"kbt":31.55,
"tps":6,
"mbs":0.17
},
"cpu":{
"us":5,
"sy":4,
"id":90
},
"load_average":{
"m1":0.85,
"m5":0.86,
"m15":0.78
}
},
"ttl":10000
},
{
"columnname":"cn",
"columnvalue":"cv",
"ttl":10000
}
]
},
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"fd"
},
{
"columnname":"cn",
"columnvalue":"cv"
}
]
}
]
}
Dual problems occuring at the same occurred led me to find an issue with the fermata library handling large JSON posts. The JSON above is just fine!
I think the real problem here is that you are trying to post data via a URL parameter instead of via the request body.
You are using Fermata like this:
path = fermata.api({url:"http://example.com/path");
data = {key1:"value1", key2:"value2"};
path(data).post(callback);
What path(data) represents is still a URL, with data showing up in the query part. So your code is posting to "http://example.com/path/endpoint?key1=value1&key2=value2" with an empty body.
Since your data is large, I'm not surprised if your web server would look at such a long URL and send back a 400 instead. Assuming your API can also handle JSON data in the POST body, a better way to send a large amount of data would be to use Fermata like this instead:
path = fermata.api({url:"http://example.com/path");
data = {key1:"value1", key2:"value2"};
path.post(data, callback);
This will post your data as a JSON string to "http://example.com/path" and you would be a lot less likely to run into data size problems.
Hope this helps! The "magic" of Fermata is that unless you pass a callback function, you are getting local URL representations, instead of calling HTTP functions on them.

Categories