couchdDB dbroot issue - javascript

I am using couchdb. I am new to it. I don't know what to have in dbroot value in place of "db/". I have taken this code from one of coucdb tutorial.
Thanks in advance for your help.
//Use a namespace to protect the scope of function and variable names
var poq = {
//Some variables global to the local namespace ("poq")
root: "http://localhost:5984/",
dbroot: "db/",
max_quotes: 6,
//Invoked when the HTML page is first loaded
loadPage: function()
{
var six_latest = poq.root + "poquotes/_design/document/_view/by_year?&limit="
+ poq.max_quotes + "&descending=true&callback=?";
$.getJSON(six_latest, poq.handleMainQuotes);
$('#donewquote').click(function() {
var db_link = poq.dbroot + "poquotes";
var record = {
"type": "quote",
"author": $("#author").val(),
"text": $("#text").val(),
"work": {
"title": $("#title").val(),
"link": $("#link").val(),
"year": parseInt($("#year").val())
}
};
$.ajax({
url : db_link,
data : JSON.stringify(record),
contentType : "application/json",
type : 'POST',
processData : false,
dataType : "json",
success : function(resp) {
alert("New document created: " + JSON.stringify(resp));
}
});
return false;
});
//Set up the collapsible form for adding new quotes
$('#popup').click(function(){
$("#newquote").slideToggle();
});
//Start out with the create quote form collapsed
$("#newquote").slideToggle();
},
//Invoked with the result of the AJAX call to load quote documents
handleMainQuotes: function(json)
{
//Load up to six records, as available
quote_count = Math.min(poq.max_quotes, json["total_rows"])
for (var i=0; i<quote_count; i++) {
var doc = json["rows"][i]["value"]
var year = doc["work"]["year"].toString()
var title = doc["work"]["title"].toString()
var link = doc["work"]["link"].toString()
//Create an HTML snippet from the fields of each quote document
qblock = $("<div class='span4 featured-quote'></div>")
.append("<h2>" + doc["author"] + "</h2>")
.append("<p style='font-size: 80%; height: 8em;'>" + doc["text"] + "</p>")
.append("<p>" + year + "</p>")
.append("<p><a href='" + link + "'>" + title + "</a></p>")
.append("<p><a class='btn' href='#'>View details »</a></p>")
//jQuery's eq selector to find the target div corresponding to the loop index
$('div.featured-quote:eq(' + i.toString() + ')').replaceWith(qblock);
}
},
}

Looks like dbroot here is meant to be the name of your database. If you haven't created a database yet, you can do so with:
curl -X PUT http://localhost:5984/mynewdatabase
Being new to CouchDB I recommend you start with The Definitive Guide (http://guide.couchdb.org)

Related

Displaying Column Description on Hover

I would like to display the column description of my sharepoint list when the user hovers the mouse over the column header. Currently there is no out of the box solution for this and I followed this guide. However this guide does not work for SharePoint 2013. Any help or direction would be helpful!
Here is the list view that I am trying to apply this to.
The exact steps depend on if you plan to use a Content Editor web part or directly edit the View page. Let me know if you aren't sure how to do either.
The result:
The JavaScript:
Notes: Use the jQuery library version of your choice. Change the "Tickets" list name to your list name.
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
var testresults
function test() {
var headings = document.getElementsByClassName('ms-vh-div')
for (var i=0;i<headings.length; i++)
{
var columnName = headings[i].getAttribute("name");
columnName = columnName.replace("_x0020_"," ");
var head = headings[i].getElementsByTagName('a')[0];
//head.title = head.title + "\nhello world"
$.ajax({
"url": _spPageContextInfo.webServerRelativeUrl +
"/_api/web/Lists/getbytitle('Tickets')/fields?$select=Description&$filter=Title eq '" + columnName + "'",
"method": "GET" ,
"theHeading": head,
"headers": {
"accept": "application/json;odata=verbose"
},
"success" : function(data) {
var xml = arguments[2].response;
var description = "" + $(xml).find("content").text()
this.theHeading.title += "\n" + description;
},
"error" : function(e) { console.log("error " + e.message) }
});
}
}
// delay script until SharePoint "stuff" is finished.
_spBodyOnLoadFunctionNames.push("test")
</script>

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

How to use AJAX & JSON with an API to call multiple URLs?

I have several areas in which I need to take information and append it to my main HTML document, from separate pages that are generated with a weather API.
For instance, in the Current Conditions section, I need to reference "http://api.wunderground.com/api/6905d444cd421efb/forecast/geolookup/conditions/q/CT/New_Haven.json" but in my Hourly Forecast, I would need to be drawing the JSON info from "http://api.wunderground.com/api/6905d444cd421efb/hourly/q/CT/New_Haven.json" and then I need to repeat that same process again in a third separate section with another url for a 10 day forecast. Each time I call to a new URL, I will be creating new variables and appending their results to the DOM.
The code that I have below works, but if I try calling to the ajax method a second or third time, it does not work and things either show up as "undefined" or absolutely nothing shows on the page in the other sections. The only thing that remains displayed on my web page is the Current Conditions.
$.ajax({
url : "http://api.wunderground.com/api/6905d444cd421efb/forecast/geolookup/conditions/q/CT/New_Haven.json",
dataType : "json",
success : function(parsed_json) {
var current_icon = parsed_json['current_observation']['icon_url'];
var current_weather = parsed_json['current_observation']['weather'];
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var current_feels = parsed_json ['current_observation']['feelslike_f'];
var current_humidity = parsed_json ['current_observation']['relative_humidity'];
var current_windDirection = parsed_json ['current_observation']['wind_dir'];
var current_windMPH = parsed_json ['current_observation']['wind_mph'];
$("#icon").append("<img src=' " + current_icon + "' alt='weather icon'/>" );
$("#currentCond").append("Current Conditions: " + current_weather);
$("#currentLoc").append("Location: " + location);
$("#currentTemp").append(" Temp: " + temp_f + "ºF");
$("#currentFeel").append("Feels Like: " + current_feels + "ºF");
$("#currentHumid").append("Humidity: " + current_humidity);
$("#currentWindDir").append("Wind Direction: " + current_windDirection);
$("#currentWindMph").append("Wind Speed: " + current_windMPH + " MPH");
}/* Close Success */
}); /* Close Ajax */
I try adding something like this after the first call is closed out.
$.ajax({
url : "http://api.wunderground.com/api/6905d444cd421efb/hourly/q/CT/New_Haven.json",
dataType : "json",
success : function(parsed_json2) {
var hourly_icon = parsed_json2['hourly_forecast']['icon_url'];
var hourly_icons = parsed_json2['hourly_forecast']['icon'];
$("#icons").append("Icon Type: " + hourly_icons);
$("#icons").append("<img src=' " + hourly_icon + "' alt='weather icon'/>" );
}/* Close Success */
}); /* Close Ajax */

Set div html to display contents of array

i'm doing a simple php chat application that sends the message input to the server via ajax and saves it in a text file. Now after it retrieves all data in the text file and sends it to the client in an array form via ajax. Now what i want to do is populate a div called "chat-box" with the contents of the array as html but nothing happens and ii don't get any errors in firebug apart from ": undefined".
This is the code:
<script type="text/javascript">
// setInterval(function(){alert("Hello");}, 5000);
$(document).ready(function() {
function getchat(messages)
{
var chat = $(".chat-box").html();
for (var i=0; i < messages.length; i++)
{
var msg = messages[i].split(':');
var name = msg[0];
var post = msg[1];
$(".chat-box").html(chat + "<div class='bubble'>" + name + " : " + post + "</div>");
}
}
$("#btnPost").click(function() {
var msg = $("#chat-input").val();
if (msg.length == 0)
{
alert ("Enter a message first!");
return;
}
var name = $("#name-input").val();
var chat = $(".chat-box").html();
//$(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");
var data = {
Name : name,
Message : msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(chat) {
getchat(chat)
}
});
});
});
</script>
Try this instead for updating the chat box:
var index = messages[i].indexOf(':');
var name = messages[i].substring(0, index);
var content = messages[i].substring(index + 1);
var $newMessage = $('<div>')
.addClass('bubble')
.text(name + " : " + content);
$(".chat-box").append($newMessage);
If this doesn't work, check if the messages returned by the server are correct by using console.log(messages).
You said the div is called chat-box. Perhaps it's this:
$(".chat-box")
maybe you intended to write it as $("#chat-box")

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Categories

Resources