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) {
}
});
Related
newbie here.
I am trying to understand how I need to structure asynchronous calls within my controller to fit my specific use case:
Consider the following code snippet from an Angular Module in "service.js" within my project:
function getSearchObjects(projectName, title) {
var payload = JSON.stringify({
"title": title
});
var request = $http({
method: 'post',
url: URL + '/search/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
};
function runQuery(projectName, fromDate, toDate, sort, direction, columns) {
var from = Date.parse(fromDate);
var to = Date.parse(toDate);
var payload = JSON.stringify({
"fromDate": from,
"toDate": to,
"sort": sort,
"direction": direction,
"columns": columns
});
console.log(payload);
var request = $http({
method: 'post',
url: URL + '/query/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
return response.data;
};
function handleError(response) {
if (!angular.isObject( response.data ) || !response.data.error) {
return( $q.reject( "An unknown error occurred." ) );
}
return $q.reject( response.data.error );
};
});
Within my controller, I am trying to troubleshoot the following function:
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date, objectProperties.sort, objectProperties.direction, objectProperties.columns)
},
function(error) {
console.log(error);
});
};
getSearchObjects matches a title ($scope.selected.search) selected in my UI and grabs the following more detailed object from an API call:
{ title: 'Duplication Example',
sort: '#_traac-timestamp',
direction: 'desc',
columns: [ '#_traac-remote_ip', 'c-platform-m-distinct-id_s', '_type' ] }
I am trying to grab the properties returned from getSearchObjects and pass them along with a few user selected values from my UI to runQuery, which then returns data from a database to the user, but when I check the values passed to runQuery using the above logic in my controller, I get the following values. All of the objectProperties values I am attempting to pass to runQuery are undefined:
project_name: "Example Project"
start_date: 1499770800000
end_date: 1499943600000
sort: undefined
direction: undefined
columns: undefined
I have been trying to debug this, but I am too new to using Angular and asynchronous calls to really understand what I am doing wrong. My best guess currently is that I am calling runQuery before the values retrieved from getSearchObjects are attached to objectProperties. Either that or I am incorrectly referencing the properties within the objectProperties variable.
Could someone help me troubleshoot this issue, and better understand what I am doing wrong?
Thank you in advance for your help!
When you do this:
var objectProperties = some async function...
You are assigning the promise of the async function to the variable, not the result of it.
The result is coming in the .then, like you declared:
.then(function(result) { ... }
So, instead of objectProperties.sort, objectProperties.direction, objectProperties.columns, try using result.sort, result.direction, result.columns :)
If you are new to Promises, take a look at this simple, but great tutorial.
EDIT
Based on your comment, you are receiving, inside the response.data, the following object:
{"objectMatch": {
"title": "doc-event",
"sort": "#_traac-timestamp",
"direction": "desc",
"columns": [
"m-doc-name_s",
"m-user_s",
"m-full-action-type_s",
"m-event-action-descriptor_s"
]}
}
So you have: response > data > objectMatch > properties you want.
The response.data you are extracting on your handleSuccess function:
function handleSuccess(response) {
return response.data;
};
So here, your result is response.data, containing the property objectMatch.
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
...
},
...
If all of that is correct, you should be able to access the values you want using result.objectMatch.<sort, direction or columns>, like:
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date,
result.objectMatch.sort, result.objectMatch.direction, result.objectMatch.columns)
I've been trying to make a request to a NodeJS API. For the client, I am using the Mithril framework. I used their first example to make the request and obtain data:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://localhost:3000/store/all"});
}
};
var Component = {
controller: function() {
var stores = Model.getAll();
alert(stores); // The alert box shows exactly this: function (){return arguments.length&&(a=arguments[0]),a}
alert(stores()); // Alert box: undefined
},
view: function(controller) {
...
}
};
After running this I noticed through Chrome Developer Tools that the API is responding correctly with the following:
[{"name":"Mike"},{"name":"Zeza"}]
I can't find a way to obtain this data into the controller. They mentioned that using this method, the var may hold undefined until the request is completed, so I followed the next example by adding:
var stores = m.prop([]);
Before the model and changing the request to:
return m.request({method: "GET", url: "http://localhost:3000/store/all"}).then(stores);
I might be doing something wrong because I get the same result.
The objective is to get the data from the response and send it to the view to iterate.
Explanation:
m.request is a function, m.request.then() too, that is why "store" value is:
"function (){return arguments.length&&(a=arguments[0]),a}"
"stores()" is undefined, because you do an async ajax request, so you cannot get the result immediately, need to wait a bit. If you try to run "stores()" after some delay, your data will be there. That is why you basically need promises("then" feature). Function that is passed as a parameter of "then(param)" is executed when response is ready.
Working sample:
You can start playing with this sample, and implement what you need:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://www.w3schools.com/angular/customers.php"});
}
};
var Component = {
controller: function() {
var records = Model.getAll();
return {
records: records
}
},
view: function(ctrl) {
return m("div", [
ctrl.records().records.map(function(record) {
return m("div", record.Name);
})
]);
}
};
m.mount(document.body, Component);
If you have more questions, feel free to ask here.
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)
Parse.com with JavaScript SDK - unnecessary duplictions
Every time I create a Parse object of "message", it duplicates that object in my Parse Core. It is so bizarre. The first time I run the code, everything is fine and Parse will create only one object. But when I run the code again, it will duplicate the most recent object twice. If I run it a third time, it will duplicate the most recent object five times. The number of duplications increases based upon how many objects have already been created. Does anyone have any idea how to make sure that it create one object in my Parse Core backend? Thank you so much!!! I wish I could post a picture, but I am a newbie and stackoverflow wont let me
This is where I create the Parse object:
App.Models.Message = Parse.Object.extend({
className: 'Message',
idAttribute: 'objectId',
defaults: {
name : '',
email : '',
subject : '',
message : ''
}
});
This is where I create an instance of the Parse object, and where I save it to Parse:
App.Views.Contact = Parse.View.extend({
el : '#middle',
template : _.template($('#contactTemp').html()),
events: {
'click .submit' : 'submit',
},
initialize : function () {
this.render();
},
render : function () {
this.$el.html(this.template);
},
submit : function (e) {
e.preventDefault();
var message = new App.Models.Message({
name: $('.nameVal').val(),
email: $('.emailVal').val(),
subject: $('.subVal').val(),
message:$('.messVal').val(),
});
message.save(null, {
success:function() {
console.log("Success");
},
error:function(e) {
alert('There was an error in sending the message');
}
});
}
});
Yes! So I figured out the problem with the help of Hector Ramos from the Parse Developers Google group.
https://groups.google.com/forum/#!topic/parse-developers/2y-mI4TgpLc
It was my client-side code. Instead of creating an event attached to my App.Views.Contact(); a.k.a. - an instance of Parse.View.extend({}), I went ahead and created a 'click' event using jquery within the sendMessage function that I recently defined. If you declare an event in the events object within the Parse view, it will recur over itself if the view wasn't re-initialized or destroyed and recreated properly.
So what happened with me was the submit function that I declared in the events object kept recuring over itself and making duplicate calls to Parse.com. My view was static, it wasn't destroyed properly, re-initialized, or reloaded. You will see what I did below:
Originally I had this:
events: {
'click .submit' : 'submit',
},
& this
submit : function (e) {
e.preventDefault();
var message = new App.Models.Message({
name: $('.nameVal').val(),
email: $('.emailVal').val(),
subject: $('.subVal').val(),
message:$('.messVal').val(),
});
message.save(null, {
success:function() {
console.log("Success");
},
error:function(e) {
alert('There was an error in sending the message');
}
});
} /*end of submit*/
Now I have I completely removed the events object that I had and declared a sendMessage function:
initialize : function () {
this.render();
},
render : function () {
this.$el.html(this.template);
this.sendMessage();
},
sendMessage : function () {
$('.submit').on('click', function(){
var message = new App.Models.Message({
name: $('.nameVal').val(),
email: $('.emailVal').val(),
subject: $('.subVal').val(),
message:$('.messVal').val(),
});
message.save(null, {
success:function() {
console.log("Success");
},
error:function() {
alert('There was an error in sending the message');
}
});
}); /*end of jquery submit*/
}/*end of send message function*/,
And now it works perfectly fine. Credit is due Hector Ramos who is a Parse.com Developer and who helped me realize that the problem was the actual event. If you guys have any easy way of stoping an event from making several duplicate calls to the back or from reoccurring several times, then please let me know.
I am using the select2 plugin and I need to to use the transport-function to perform the ajax request on my own, because I need to set API Keys in the request-header. But as soon as I do this, select2 responses the results correctly and also formats and displays it like I want, but the results shown are not selectable. I can neither click at them, nor navigate to them with the arrow-keys, nor is there any mouseover effect when I go over them with the mouse.
Here's some code (I want to show suggestions for usernames):
ajax: {
data: function (term, page) {
return {
Searchtext: term
};
},
transport: function(queryParams){
// Api.Ajax delivers { Ajax: *the $.ajax object*, RequestId: *some requestId* }
var req = Api.Ajax("/api/suggestion/share/" + queryParams.data.Searchtext, "POST", { UserOnly: true }, queryParams.success);
return req.Ajax;
},
// parse the results into the format expected by Select2.
results: function(resp, page) {
return {
results: resp.Data,
more: false
};
}
},
Like I said, as soon as I use my own Ajax-function by implementing the transport-function, the results in the dropdown list are all shown, but not selectable.
Is this a bug, or am I doing something wrong?
#thnew This Answer will show you how to set request headers without requiring the transport function.