how to save parameters in session in nodejs. nowjs example - session

I use nowjs and have an issue with sessions.
here is the code:
now.on('connect', function(){
if(this.user.session){
this.user.session.views++;
console.log(this.user.session.views);
}
});
app.get('/', function(req, res){
var body = '';
body = body+' <script src="/nowjs/now.js"></script>';
if (req.session.views) {
++req.session.views;
} else {
req.session.views = 1;
body += '<p>First time visiting? view this page in several browsers :)</p>';
}
res.send(body + '<p>viewed <strong>' + req.session.views + '</strong> times.</p>');
console.log("body");
});
no the problem is that I can write anything into "this.user.session" but on next call everything is erased. in my example it counts how many times you have entered the site. and "views" is increasing by one each time, but it should be increasing by 2 because I of "this.user.session.views++;". I'm missing something or it can't be done?
if you have some examples of nowjs+sessions post is please
thank you

I was using nowjs with sessions and Passport for authentication... I wrote a simple gist for making them work together ...
https://gist.github.com/2266544

Related

Anyone used to work with Web Scraping in laravel

Route::get('/api', function() {
$crawler = Goutte::request('GET', 'https://www.alibaba.com/product-detail/wholesale-magnetic-charging-cable-flowing-light_62127638796.html?spm=a2700.details.deiletai6.5.472ada1akNmbnG&bypass=true');
$crawler->filter('.ma-title')->each(function ($node) {
dump($node->text());
});
});
I don't always receive data and sometimes I need to refresh 10 times to get data.
Can anyone advise why this might be?

There must be an easier way

I am trying to create an JQM app and are doing so by getting a lot of data from database. When I click on a link from a ajax/json generated calendar list I should then be able to get the info for that event by calling the server and get the data. As it is now I do this in 2 steps like this.
My ajax generated event list:
$.each(groupcalendar, function (i, val) {
output += '<li><h2>' + val.matchformname + '</h2><p><strong>' + val.matchday + '</strong></p><p>' + val.coursename + '</p><p class="ui-li-aside"><strong>' + val.matchtime + '</strong></p></li>';
});
When I click on one of the links I want to goto a page called prematchdata.html and get the data fro that specific event. I do so by first calling the click and get the eventid from data-id like this:
$(document).on('click', '#gotoMatch', function () {
var matchid = $(this).attr("data-id");
$.get("http://mypage.com/json/getmatchinfo.php?matchid="+matchid, function(data) {
localStorage["matchinfo"] = JSON.stringify(data);
$.mobile.changePage( "prematchdata.html", { transition: "slide", changeHash: true} );
}, "json");
});
I save the returned data as localStorage and then uses this data in my pageinit like this:
$(document).on("pageinit", "#prematchdata", function() {
var matchinfo = {};
matchinfo = JSON.parse(localStorage["matchinfo"])
var content = '<h2>'+matchinfo["matchname"]+'</h2>';
$('.infoholder').html(content);
});
It works, although for me it seems like the last 2 steps should be done in one, but i am not sure how to do so? It seems a little bit wrong get data, save locally and then use it? Can't this be done without the $(document).on('click', '#gotoMatch', function () {});?
Hoping for some help and thanks in advance :-)
You could try sending it up using a query string. When you're using changePage, change your code like this :
$(document).on('click', '#gotoMatch', function () {
var matchid = $(this).attr("data-id");
$.get("http://mypage.com/json/getmatchinfo.php?matchid=" + matchid, function (data) {
paramData = data[0];
$.mobile.changePage("prematchdata.html", {
transition: "slide",
changeHash: true,
data: paramData //added this extra parameter which will pass data as a query string
});
}, "json");
});
When you're getting it back,
$(document).on("pageinit", "#prematchdata", function() {
var url = $.url(document.location);
var name= url.param("matchname");
var content = '<h2>'+ name +'</h2>';
$('.infoholder').html(content);
});
Another easy way would be use a singlepage template instead of a multi page template. Then, you could just use a global variable to get and set data.
That said, what you're doing right now is more secure than this query string method. By using this, anyone can see what you are sending over the URL. So I advise you keep using localStorage. For more info on this, look into this question.

How to query cosm json feed using the cosm javascript library

I am new to web development and I have bit off more than I can chew.
So far, I successfully have created a website to query the latest data at cosm.com
Now I am trying to save the last 10 data points from the cosm.com feed to an array using the cosm javascript library. I can't get the right syntax and I can't find examples to guide me.
cosm.feed.history( 12068, duration:'30seconds', callback(data) );
console.log(data);
http://jsfiddle.net/spuder/29cFT/12/
http://cosm.github.com/cosm-js/docs/
UPDATE 2013-4-14
After implementing #bjpirt's solution, I noticed I wasn't getting 'every' value returned inside the specified duration.
Solved it by adding "interval:0" to the request.
cosm.datastream.history( cosmFeed1, cosmDataStream1, {duration:'60seconds', interval:0}, getHistory );
http://jsfiddle.net/spuder/ft2MJ/1/
#lebreeze is correct with his advice. I got your JSFiddle working so that it is now fetching data from the Cosm API:
http://jsfiddle.net/nLt33/2/
I had to make a few changes to get it working, any of which would have been causing you errors:
The feed ID and datastream ID were incorrect
You didn't have a callback function
The options weren't in a javascript object
Also, that feed doesn't seem to have been updated recently.
Here's the updated code which seems to be working fine now:
//read only key
cosm.setKey("-Ux_JTwgP-8pje981acMa5811-mSAKxpR3VRUHRFQ3RBUT0g");
var cosmFeed = 120687;
var cosmDataStream = "sensor_reading";
$(document).ready( function() {
var success = function(data){
for(var datapoint in data.datapoints){
var dp = data.datapoints[datapoint];
$('#stuff').append('<li>Value: ' + dp.value + ' At: ' + dp.at + '</li>');
}
}
//Print out the last 10 readings or so
cosm.datastream.history( cosmFeed, cosmDataStream, {duration:'1day'}, success );
})
It's difficult to get just the last x datapoints (that's something we should change in the API I think) - what you'd normally do is ask for a specific time period.
Hope this helps.
You may need to wrap your duration:'30seconds' json options in {}
Try something like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://d23cj0cdvyoxg0.cloudfront.net/cosmjs-1.0.0.min.js"></script>
<script>..
cosm.setKey( "APIKEY" );
cosm.feed.history(40360, {duration:'30seconds'}, function(data){
console.log(data);
console.log(data.datastreams);
});
</script>

jQuery — a .live() > each() >.load.() finella

EDIT - URL to see the issue http://syndex.me
I am dynamically resizing images bigger than the browser to equal the size of the browser.
This was no easy feat as we had to wait for the images to load first in order to check first if the image was bigger than the window.
We got to this stage (which works):
var maxxxHeight = $(window).height();
$(".theImage").children('img').each(function() {
$(this).load( function() { // only if images can be loaded dynamically
handleImageLoad(this);
});
handleImageLoad(this);
});
function handleImageLoad(img)
{
var $img = $(img), // declare local and cache jQuery for the argument
myHeight = $img.height();
if ( myHeight > maxxxHeight ){
$img.height(maxxxHeight);
$img.next().text("Browser " + maxxxHeight + " image height " + myHeight);
};
}
The thing is, the page is an infinite scroll (I'm using this)
I know that you are not able to attach 'live' to 'each' as 'live' deals with events, and 'each' is not an event.
I've looked at things like the livequery plugin and using the ajaxComplete function.
With livequery i changed
$(".theImage").children('img').each(function() {
to
$(".theImage").children('img').livequery(function(){
But that didnt work.
ajaxComplete seemed to do nothing so i'm guessing the inifinte scroll i'm using is not ajax based. (surely it is though?)
Thanks
Use delegate:
$(".theImage").delegate('img', function() {
$(this).load( function() { // only if images can be loaded dynamically
handleImageLoad(this);
});
handleImageLoad(this);
});
The problem is that your infinite scroll plugin does not provide the callback functionality. Once your pictures are loaded there is no way to affect them.
I have tried to modify your plugin, so that it will serve your needs, please see http://jsfiddle.net/R8yLZ/
Scroll down the JS section till you see a bunch of comments.
This looks really complicated, and I probably don't get it at all, but I'll try anyway :-)
$("img", ".theImage").bind("load", function() {
var winH = $(window).height();
var imgH = $(this).height();
if (winH < imgH) {
$(this).height(winH);
$(this).next().text("Browser " + winH + " image height " + imgH);
}
});

Ajax Broken in Browsers works in Android

I can run this code in Android app (using PhoneGap adn jQuery Mobile) but not on desktop browsers.
It gives me a syntax error in firebug for this line =
var TicketList = eval("(" + ajax.responseText + ")");
Here is the code
// JScript source code
// ran on body load
function doJsStuff()
{
var ajax = AJAX();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
var TicketList = eval("(" + ajax.responseText + ")");
if (TicketList.ListCount > 0) {
document.getElementById("opencount").innerHTML = TicketList.ListCount +" Open Tickets";
for (Ticket in TicketList.Tickets) {
// add stuff to DOM
//AddTicketToList(TicketList.Tickets[Ticket]);
}
}
else {
document.getElementById("opencount").innerHTML = "All Tickets Reviewed";
DisplayNoresults();
}
}
}
ajax.open("GET", "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open", true);
ajax.send(null);
//document.addEventListener("deviceready", onDeviceReady, false);
//event to check for PhoneGap
//$('ul').listview('refresh');
$('#mtickets').page();
//showVars();
}
function AJAX()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
}
return xmlHttp;
}
**TicketList is a variable in the JSon that comes across like this=
{"Tickets" : [{"TicketID": "1054","Category": "N/A","SubmittedUserID": "bob.thebuilder","ShortDescription": "test question QID:16668","CreationDate": "2/16/2011 12:24:19 PM","TicketStatus": "Open","LongDescription": "Something is wrong with this question I know I hve the right answer but it keeps telling me I'm wrong"},{"TicketID": "1053","Category": "Mission Support","SubmittedUserID": "dave","ShortDescription": "Make courseware revisions","CreationDate": "2/16/2011 9:34:48 AM","TicketStatus": "Open","LongDescription": "Find help tickets generated by users for possible courseware update."}], "PageCount": "6", "ListCount": "11"}
Note about PhoneGap If you are trying to include phoengap functions in a place where the code may also be executed on in a browser make sure you only add the phone gap function with on "deviceready" or your browser will not render. Example:
function onload(){
//event to check for PhoneGap
document.addEventListener("deviceready", onDeviceReady, true);
}
...
function onDeviceReady()
{
// Now PhoneGap API ready
vibrate(90); // vib to ack pg ready
$("a").click(function(event){
vibrate(30); // add 30 sec vib to all links
});
}
My immediate response would be to use jQuery's getJSON method, since you're aready using jQuery. jQuery's AJAX provides a much broader base of browser compatibility. Also, every time you use eval(), a small baby somewhere cries.
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(TicketList){
if (TicketList.ListCount > 0) {
$("#opencount").html(TicketList.ListCount +" Open Tickets");
for (Ticket in TicketList.Tickets) {
...
}
} else {
$("#opencount").html("All Tickets Reviewed");
DisplayNoresults();
}
});
If this still doesn't work for you, ensure that the JSON being returned is valid. But please stick to this method, and don't use eval!!
SIMPLIFIED UPDATE
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
UPDATE USING 'DATA'
If your url becomes too long, you might begin to encounter problems. It is suggested to pass the url data via the data argument.
var url = "http://website.com/ListTicketsRequest.ashx";
var data = "PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url, data, function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
Looking at your code, it seems likely to me that the syntax error isn't in the code you posted, but instead is contained in the JSON object you're evaluating in ajax.responseText. Take a look at the data being returned by the AJAX request. Is it valid Javascript? Does the page you're calling return something different to desktop browsers vs mobile? Is there an error message where the JSON code should be?
Another possibility: Is your app running on website.com? If not, Firefox is probably blocking the XMLHttpRequest from functioning properly. Firefox 3 and below block cross-site AJAX requests. Firefox 3.5 seems to allow some exceptions.

Resources