samedi 27 juin 2015

JavaScript OnChange load another JSP page

I have a Jsp page on which there is a form form1 with a dropdownlist and I have included another Jsp page containing another form form2 to this page. I want that the form2 should be visible only when a particular element(say opt2) on the dropdownlist of form1 is selected.

Please see the code structure below:

<div id="somediv1">
    <%@ include file="../form2.jsp"%>
</div>
<form id="form1">
    <select  id="list1">
    <option>opt1</option>
    <option>Opt2</option>
    <option>opt3</option>
    <option>opt4</option>
    </select>

Team Treehouse nav bar animation

I am trying to reproduce the effects of the nav-bar animation when scrolling on their homepage. I understand how they can add classes when scrolling past a certain threshold with Jquery. Any ideas? If i try to animate links in the menu with opacity my content either overlaps, and if I use visibility it gets displaced.

Thank you.

PHP Countdown distribution

I am writing a randomized countdown that show number of products left in promotion alongside a timer. Number of products left is stored in the database, so all users see the same number. I am using simple php/ajax/javascript solution. My problem is with distributing the random sales so all fit within limited timer and are nicely distributed.

Here is code I have so far:

function start() {
    $date= new DateTime();
    $prod_left = getval("SELECT * FROM counter LIMIT 1");
    if ( $prod_left == 20 ) {
        $fp = fopen("../index.html", "r+");
        while($buf = fgets($fp)){
            if(preg_match("/<!--(.|\s)*?-->/", $buf)){
                fputs($fp, '<script type="text/javascript">$(document).ready(function() {$(".countdown").circularCountdown({startDate:"' . $date->format('Y/m/d H:i:s') . '",endDate:"' . $date->modify("+5minutes")->format('Y/m/d H:i:s') . '",timeZone:+2});});</script></body></html>');
            }
        }
        fclose($fp);
        sleep(30);
        while ($prod_left > 0) {
            if (rand(0,4) > 2) {
                $prod_left--;
                sleep(rand(1,13));
                updateval($prod_left);
            }
        }

    } else {
        echo 'Promocja w trakcie lub zakończona, zresetuj zegar, jeżeli chcesz rozpocząć ponownie';
    }
    exit;
}

My assumption here is: 50% of time decrease timer and wait on average 6.5 seconds, which should on average give me 260 seconds for full sale. Unfortunately its very unevenly distributed. My goal is to have the sale completed not later than 270seconds after start. Will you be able to help?

Implementation doesnt need to be in any particular programing language, im just looking for a clue/concept I can follow to achieve this.

What is the strangest, the $prod_left value not always goes to 0, on sime iterations it just sits at 3 or 5.

Please help!

Passing File path to MVC controller from View with Ajax J query return null

I'm trying to upload a image using MVC 5 and Ajax Jquery (asynchronously) but value of image variable always return null,

i already checked some previous stack overflow posts regarding this issue but i could not find my mistake, can anyone help me,

please help,,

Model Class

 public class TravelCategoryCustom
        {
            public int categoryId { get; set; }
            public string categoryName { get; set; }
            public string categoryDescriprion { get; set; }
            public HttpPostedFileBase image { get; set; }
            public int TotalPlaces { get; set; }
        }

View

<form enctype="multipart/form-data">
                <div class="form-group">
                    <label>Category Name</label>
                    @Html.TextBoxFor(model => model.categoryName, new { @class = "form-control" })

                </div>
                <div class="form-group">
                    <label>Category Description</label>
                    @Html.TextAreaFor(model => model.categoryDescriprion, 5, 1, new { @class = "form-control " })
                </div>
                <div class="form-group">
                    <label>Category Image</label>
                     <input type="file" id="dialog" />
                </div>

                <input type="button" value="Create" id="submtt" class="btn btn-primary" onclick="favfunct()" />

            </form>   

Script

<script>
    function favfunct() {
    $.ajax({
  var formData = new FormData($('form')[0]);
        url: "/MVCTravelCategories/Create",
        dataType: "json",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ trvlcategory: { categoryId: '1', categoryName: 'testName', categoryDescriprion: 'TestDec', image: formData , TotalPlaces: '3' } }),
        async: true,
        processData: false,
        cache: false,
        success: function (data) {
            alert(data);
        },
        error: function (xhr) {
            alert('error');
        }
    });
    }
</script>

How to disable JQuery waypoints on click menu item?

I have read all the questions and answers on this topic. This should be a simple task, but I cannot get it to work.

JQuery version of Waypoints is working fine on top menu items, on one page site. I want to disable it upon clicking these menu items, and then restore it. I haven't gotten to the restore part yet. When I call the disable function I get a "TypeError: e.disable not a function". Commented lines show all the ways I have tried to include the disable() function:

var waypoints = $('section.waypoint').waypoint({
    handler:function(){
    var hash = '#'+this.element.id;     
    $('#menu-main-menu li.active').removeClass('active');
    $('#menu-main-menu li a[href='+ hash +']').parent('li').addClass('active');
    window.console.log($(window).scrollTop());
    if($(window).scrollTop() < 500){
    $('#menu-main-menu li.active').removeClass('active');
    }

    //$('#menu-main-menu li a').on('click', function(){
    //this.disableAll();
    //});
},
offset: '30%',
continuous: false

});

//waypoints.disable();

$('.jumbotron a, #menu-main-menu li a').on('click', function(e) {
e.preventDefault();
//waypoints.disable();
//waypoints.disableAll();
$('#menu-main-menu li.active').removeClass('active');

if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name="' + this.hash.slice(1) +'"]');
if ($target.length) {
var targetOffset = $target.offset().top - 45; 
$('html, body').animate({scrollTop: targetOffset}, 1000);
}
}    
});

I realize that waypoints is an array, so have tried disableAll() and iteration. No dice. Thanks in advance for your help!

Calling function inside jQuery returns wrong result

I have the following javascript code that runs fine if called outside the jQuery function on the bottom. I don't know what I am doing wrong.

Bresenham Algorithm:

function bresenham(x0,y0,x1,y1){
        var bresenham = [];
        
  var x=0;
        var dx = x1-x0;
        var dy = y1-y0;
        
        var D = 2*dy - dx;
        bresenham.push(x0 + "," + y0);
        var y=y0;
        
        for (x = x0+1;x<=x1;x++){
                        if (D>0){
                                        y = y+1;
                                        bresenham.push(x + "," + y);
                                        D = D + (2*dy - 2*dx);
                        } else {
                                        bresenham.push(x + "," + y);
                                        D = D + (2*dy);
                        }
        }
  return bresenham;
};

JQuery:

$(document).ready(function(){
        $(".button").click(function(){
                $("div#output p").remove();
                
                var x0 = $('input[name=x0]').val();
                var y0 = $('input[name=y0]').val();
                var x1 = $('input[name=x1]').val();
                var y1 = $('input[name=y1]').val();

                var bres = bresenham(x0,y0,x1,y1);
                console.log(bres);
        });
});

If I input: x0 = 1, y = 0 and x1 = 15, y2 = 9 it outputs: ["1,0", "11,01", "12,01", "13,011", "14,0111", "15,0111"]

Stuck with multi click event

I am stuck with the following. I have a play button. When the user clicks the first time on it, it should play the song and add a pause button to it. The second time you click on the button, it should pause the song.

Came up with this:

$('.play').click(function(event) {
        event.preventDefault();

        var trackID = $(this).closest('li').attr('data-id');
        console.log(trackID);

        $('#playlist li').removeClass('active');
        $(this).parent().addClass('active'); 


        if ( $(this).hasClass('play pause') ) {
            console.log('false');
            $(this).removeClass('pause');
        } else {
            console.log('true');
            $(this).addClass('pause');
            //return false;
        }

        if (nowPlaying) {
            nowPlaying.stop();
        }


        SC.stream('/tracks/' + trackID, function(sound) {
            if ( !$(this).hasClass('play pause') ) {
                console.log('hellooo');
                sound.play();
                nowPlaying = sound;
            } else {
                console.log('byeee');
                sound.pause();
                nowPlaying = sound;
            }
        });

   });

The above part will work correct. Play is the default of the button. When click the console.log send me the trackID: 91298058, true, and the string hellooo inside the stream function and the song is playing. The second time it will give me also the trackID 91298058, false and also the string hellooo. So the bug is here. Whenever you click the string hellooo will be send to the console.log. And the console.log - byeee will never be send and thus never be paused.

So in short, I would like to have one button that switch from play to pause and reverse. At play it should play the song: sound.play(); and at pause it should pause the song: sound.pause();;

Does anyone know how to fix this issue?