I would like to send an AJAX request to the router function below with parameters start and end respectively.
Those variables would influence the results I get back from the request.
router.get('/winnerlist', function(req, res) {
var db = req.db;
var start = "20140621";
var end = "20140623";
db.collection('userlist').find({"timestamp": {"$gte": start, "$lt": end}}).toArray(function (err, items) {
res.json(items);
});
});
This is my AJAX GET call
function populateWinners() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/winnerlist', function( data ) {
userListData = data;
console.log(data);
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.id2+ '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>' + this.code + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#winnerList table tbody').html(tableContent);
});
};
I have read this question, but I haven't figured out how to make it work within Node.js
For GET requests, parameters are usually passed in the url's query string http://en.wikipedia.org/wiki/Query_string . In this case, your AJAX URL should be
'/users/winnerlist?start=20140621&end=20140623'
Then, on the server side, you can use the variables as:
req.query.start //This equals "20140621"
req.query.end // This equals "20140623"
Related
I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")
I have a test script to update a county drop down list whenever the year or state is updated. When I used a literal string when year is selected, the county list updated fine. However when I tried to the county list using an ajax call and used a (var options) to build the list, the drop down list value changed to an empty list even though I verified the value of (var options) contains valid drop down list options.
Please help!
Thanks,
$('#State').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year:year
};
alert("State changed:" + state + ":" + year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
$('#DataId').html("<option value='Select'>Select-S</option><option value='16'>Alameda-S</option>");
alert("Statitical Areas(S): " + options);
//$('#DataId').html(options); //This should work. How to get the value of options into the string
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
$('#Year').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year: year
};
alert("Year changed:" + state +":"+ year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
//$('#DataId').html("<option value='Select'>Select-Y</option><option value='16'>Alameda-Y</option>");
$('#DataId').html(options); //This should work. How to get the value of options into the string
alert("Statitical Areas(Y): " + options);
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
return $.ajax({
url: url,
type: type ? type : 'GET',
data: data,
contentType: 'application/json'
});
}
Instead of using another function to call your $.ajax why not call it immediately. There’s no performance improvement on what you had done. Try to revert your code and just add async property if you want to wait the response before proceeding to your lower conditions.
I hope this will help you
I have a problem in the approach for validation in server side and display the error if exist. I use before Save Row function to achieve this.
$.extend(true, $.jgrid.inlineEdit, {
beforeSaveRow: function (options, rowid) {
//alert("called");
jQuery('#' + rowid + '_statusFlag').css('background','red');
jQuery('#' + rowid + '_statusFlag').attr('title','error messages goes here...');
return false; // return false break submiting
}
});
Here inside the function, I wish to perform an ajax call with the row data. How will I serialize or get the postdata so that I can send the data.
Here you can see an example to how you can get your postdata:
$.extend(true, $.jgrid.inlineEdit, {
beforeSaveRow: function (options, rowid) {
$(this).find('input').each(function () {
var name = this.name;
var value = $(this).val();
});
alert("called");
//jQuery('#' + rowid + '_statusFlag').css('background', 'red');
//jQuery('#' + rowid + '_statusFlag').attr('title', 'error messages goes here...');
return false; // return false break submiting
}
});
I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});
I have two functions that make $.getJSON calls - one looks at JSON stored on server, and the other one makes a call to Flickr.
I have this:
$(document).ajaxStart(function(){
alert('requeststart');
//$('#loading').show();
});
which works when $.getJSON is called with some given path, but it does not raise an alert when $.getJSON makes the call to Flickr. The Flickr call works, and everything loads as it should... it doesn't fire ajaxStart however. (I'm using ajaxStart and ajaxStop to show a loading-gif)
Any ideas?
Here is the function that calls Flickr :
$('#submit').on("click", function (evt) {
evt.preventDefault();
var tag = $('input').val();
if (tag == "") {
alert("please enter a tag");
}
else {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",{tags: tag, tagmode: "any", format: "json" },
function(data) {
$.each(data.items, function(i,item){
var name = names[index];
$("#" + name).empty();
$('<img src="' + item.media.m.replace("_m.jpg", ".jpg") + '" />').appendTo("#" + name);
$(' ' + item.title + '').appendTo("#" + name );
index ++;
if (i==5) {
index = 0;
}
});
});
}
});
jQuery only fires those events (ajaxStart and ajaxStop) if it internally uses the XMLHttpRequest object.
However if you request data from a different domain using a callback parameter (JSONP), jQuery does not use XMLHttpRequest, instead it accomplishes that by inserting a <script> tag.
That's why the events get not fired.
As a workaround you could start your loading animation just before the $.getJSON call, and stop it inside the function(data) {.. block.
for multiply requests you have too count them individually. I did it like this:
var loader = 0;
function showloader(cnt){
loader = loader + cnt;
if(loader < 1) {
$('#loading').hide();
} else {
$('#loading').show();
}
}
increase by 1 and call it before $.getJSON and decrease it and fire again when its done. like:
showloader(1);
$.getJSON(
[...]
}).done(function() {
showloader(-1);
[...]
});