jeudi 13 août 2015

TypeError: click called on object that does not implement interface HtmlElement

I've seen the other questions on this topics, but i can't spot the error in my code.

$('#submit_bulk').on('click',function(e){

    var action = $('select[name="bulk_action"]'),
    targets = $('table tr td:first-child :checkbox:checked');
    if(action=='invalid' || targets.length == 0){
        sk.alert('Nothing to do','warning');
        return false;
    }else{
        $(this).html('Working....');

        var fData = {
            action: action,
            mixtapes: '',
            singles: ''
        };

        $.each(targets,function(i,v){
            if($(this).data('type') == 'mixtape'){
                fData.mixtapes += $(this).data('id')+',';
            }else{
                fData.singles += $(this).data('id')+',';
            }
        });

        fData = $.param(fData); 

        console.log(fData); //i get no output here. is fData null?

        $.post(window.location.origin+'/adminAPI/bulk_action',fData,function(data){
            var data = JSON.parse(data);
            if(data.error==0){
                sk.alert('Your changes were saved','success');
                //update view here.
            }else{
                sk.alert(data.message,'error');
            }
        });
        $(this).html('go');
    }

});



via Chebli Mohamed

Javascript/jQuery to tell when YouTube is played

On http://www.pegstar.net/ we are displaying the videos using the old object code (example code is below) and displaying 15 videos per a page. These are all dynamically generated and looking to upgrade to the iFrame API. One thing we are wondering is how many people are clicking on "play" on the videos. Is there a way to be able to tell this using the old object script or does it have to be updated to the iFrame API?

<object width="425" height="350" data="http://www.youtube.com/v/MIqhbyZ5iZg" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/MIqhbyZ5iZg" /></object>



via Chebli Mohamed

Add an "click outside of menu to close" jquary/javascript to a menu drop-up that has .toggle()

I would like to add the function to close the menu if i click outside the menu. And also keep the menu button working to close it too: http://ift.tt/1DNxM2R

$(document).ready(function () { $("li").click(function () { $('li > ul').not($(this).children("ul").toggle()).hide(); }); });

Also can you tell me if this is correct for mobile etc? I hope and think so, because it's using .click, right?

This is referring to this post, that I can't reply to the answer to ask there: How to change drop-down menu to drop-up menu



via Chebli Mohamed

Illegal Invocation while passing data attribute on Ajax

I am trying to get the data attribute of a button with id delete_btn and send it through ajax. As a result, I am getting the following error.

Uncaught TypeError: Illegal invocation

JQuery

var id = $( "#delete_btn").attr('data-identifier');

$.ajax({

    dataType: "json",
    url: apiURL,
    data: { 'req': 'delete', 'id': id},

    success: function(data){
        //   do something

    },
    error: function (textStatus){
        //do something
    }

});

I have even tried getting the attribute value by

 $( "#delete_btn" ).data( "identifier")

But got the same error



via Chebli Mohamed

ng-show, toggle right element on click [Angularjs]

I wana toggle elements but not all elements i need just one on which is clicked.

for example if I have 3 form elements and 3 buttons if I click on button 1. I just wana toggle 1. form element.

This is my current code:

angular:

$scope.formWhat = false;
$scope.formShow = function(item){
                   $scope.formWhat = !$scope.formWhat;
               };

html:

<div ng-repeat="x in comments">
<a href="#" ng-click="formShow(x)">replay</a>
       <form id="<%x.id%>" ng-show="formWhat">
        blbllblblbl
        </form>
</div>

This code will open all forms, but i need just on which is clicked, any idea?



via Chebli Mohamed

jQuery Autocomplete Results Not Highlighted/Underlined

I have a search bar with autocomplete that looks like this:

enter image description here

Attached is my code:

HTML:

<form
    method="GET"
    action="{{ URL('schedulizer/results') }}"
    accept-charset="UTF-8"
    class="form-inline global-search" role="form">
    <div class="form-group">
        <input
            type="search"
            class="form-control floating-label"
            id="q"
            name="q"
            placeholder="i.e. ECE 201, Digital Logic, Kandasamy, or 41045"
        >
    </div>
    <button type="submit" class="btn btn-material-teal shadow-z-1">
        <span class="glyphicon glyphicon-search"></span>
    </button>
</form>

JS:

$.ui.autocomplete.prototype._renderItem = function( ul, item){
        var term = this.term.split(' ').join('|');
        var re = new RegExp("(" + term + ")", "gi") ;
        var t = item.label.replace(re,"<b>$1</b>");
        return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + t + "</a>" )
                .appendTo( ul );
    };

    // once page loads, make AJAX request to get your autocomplete list and apply to HTML
    $.ajax({ url: '{{ URL('autocomplete') }}',
        type: "GET",
        contentType: "application/json",
        success: function(tags) {
            $( "#q" ).autocomplete({
                source: tags,
                minLength: 2,
                delay: 0,
                select: function(event, ui) {
                    $('#q').val(ui.item.value);
                }
            });
        }
    });

CSS:

.ui-autocomplete {

  .ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;

    &.ui-state-hover, &.ui-state-active {
      color: #ffffff;
      text-decoration: none;
      background-color: red;
      border-radius: 0px;
      -webkit-border-radius: 0px;
      -moz-border-radius: 0px;
      background-image: none;
    }
  }
}

The issue I have with this is, when I am scrolling down the results using my ^ and v key, the results within the autocomplete do not get highlighted/underlined. Only when I use my mouse to hover over the results, do my results get underlined.

I have some custom CSS that renders a Boostrap-like theme onto the autocomplete, and what I did was, I changed the parameters and added a background-color of grey, or render an underline on the active text, however, I was unable to fix the issue with using the arrow keys to navigate the autocomplete and underline/highlight the results.

I would love some assistance.



via Chebli Mohamed

jquery validation behaves different on android phone

I have written some jquery validation it works fine on desktop, iphone, but does not android phone.

on android it show validation errors on typing single word, it should not do this. on desktop it works fine and it only show error validation, if user moved to next field, same way it should work on android



via Chebli Mohamed

Javascript changes all image title attributes and not just the selected img

I am writing a Chrome Extension which allows people to report child sexual abuse images they find online. As soon as they report the image it should be replaced with another that is part of the extension. This all works well.

We also change the href of the image, the title and the alt. This is where things go wrong. The code is like this:

var imgs = document.getElementsByTagName("img");
  for(var idx = 0; idx < imgs.length; idx ++)
  {
    // request.greeting = an img src url
    if(imgs[idx].src == request.greeting) 
    {      
      var width = imgs[idx].getAttribute("width");
      var height = imgs[idx].height;
      var st = imgs[idx].style;

          imgs[idx].src = imgURL;  // Change the Image and set it's properties                   
          imgs[idx].href = "http:\\7ASecond.Net";
          imgs[idx].alt = "Removed by 7ASecond.Net";
          imgs[idx].title = "Removed by 7ASecond.Net";
          resizeImg(imgs[idx]);
         // imgs[idx].setAttribute("style", "width=" + width + "; height=" + height + ";");
        }
      }
    }

  });

What actually happens is that all images on the page have their title, and alt changed. Can you see the problem? Do you want to join the team to make this most needed extension? :D



via Chebli Mohamed

Using Select2 in dropdownlist

Can't seem to get select2 working correctly in my view.

@Html.DropDownList(
    "ResourceID"
    , null
    , "--Select--"
    , new {@class="input-control" ,data_role="select" })

If I use select2 outside of the DropDownList then it works so I know it's not a jquery or select2 issue.

http://ift.tt/1TzuvG2



via Chebli Mohamed

How to set an image to change source based off of two different radio buttons?

I'm starting to understand PHP pretty well, however, Javascript is still pretty new to me. I'm trying to change an image with Javascript, based on the selection of two radio buttons.

My radio buttons are as follows (one from the color set of radio buttons and one from the trim level set of radio buttons):

<input name="extcolor" type="radio" id="extcolor2'" value="Obsidian Blue Pearl" />
<input name="trimlevel" data-trim="exl" type="radio" value="2016 Honda Odyssey EX-L" />

I was able to get it to work with only one variable with this code:

<script type='text/javascript'>
$(document).ready(function(){
    $("input:radio[name=extcolor]").click(function() {
        var color = $(this).val();
        var image_name;
            image_name = ("/new-inventory-stock-images/<?=$VehicleYear?>/<?=$VehicleModel?>/configurations/base-cars/"+color+"_exl_34FRONT.png");
         $('#buildyourown').attr('src', image_name);
    });
});

<img src="default-image.png" name="buildyourown" id="buildyourown"> 

However, when I try to add a second variable, as is shown below, this is where the problem occurs. I can't seem to get javascript to read the data-trim data attribute in the trimlevel radio buttons and I don't think my functions are set up properly to work at the same time, but I can't for the life of me figure out how to set it up so both work. Can someone point me in the right direction?

<script type='text/javascript'>
$(document).ready(function(){
    $("input:radio[name=trimlevel]").click(function() {
        var trimlevel =$(this).attr(dataset.trim); 
        }

    $("input:radio[name=extcolor]").click(function() {
        var color = $(this).val();

        var image_name;
            image_name = ("/new-inventory-stock-images/<?=$VehicleYear?>/<?=$VehicleModel?>/configurations/base-cars/"+color+"_"+trimlevel+"_34FRONT.png");
         $('#buildyourown').attr('src', image_name);
    });
});

<img src="default-image.png" name="buildyourown" id="buildyourown"> 



via Chebli Mohamed

JQuery select data from database (mybatis)

Now,I'm running the project on SpringMVC and use mybatis for connecting to database. And now I got problem on JSP, I want to use JQuery to select data from database without setattribute from controller. Can you give me sample to do that.



via Chebli Mohamed

jQuery - Change CSS of one div that shares its class with other divs

I am trying to change the CSS of a single DIV that shares its class with other divs.

I have been trying looking around for a solution but nothing seems to work.

I am trying using the code below without results:

$(".singleOffer").click(function(){
    $(this).parent().find(".offerSocial").css({transform: "translateY(0%)", opacity: "1" });
});

HTML

<div id="pattern" class="pattern">
  <ul class="g">

<li class="singleOffer">
      <img class="offerImg" src="<?php echo $file ?>" alt="Product Name" />
      <div class="offerSocial">
          <a class="previewLink" target="_blank" href="<?php echo $file ?>" >DOWNLOAD</a>
          <label class="shareLabel">Share on</label>
          <div class="share-buttons">
              <button class="fbShare" type="button" onclick="window.open('<?php echo $file ?>', 'newwindow', 'width=500, height=500'); return false;">Facebook</button>
              <button class="twShare" type="button" onclick="window.open('<?php echo $file ?>', 'newwindow', 'width=500, height=500'); return false;">Twitter</button>
          </div>
      <div>
</li>

<li class="singleOffer">
      <img class="offerImg" src="<?php echo $file ?>" alt="Product Name" />
      <div class="offerSocial">
          <a class="previewLink" target="_blank" href="<?php echo $file ?>" >DOWNLOAD</a>
          <label class="shareLabel">Share on</label>
          <div class="share-buttons">
              <button class="fbShare" type="button" onclick="window.open('<?php echo $file ?>', 'newwindow', 'width=500, height=500'); return false;">Facebook</button>
              <button class="twShare" type="button" onclick="window.open('<?php echo $file ?>', 'newwindow', 'width=500, height=500'); return false;">Twitter</button>
          </div>
      <div>
</li>

.....

  </ul>
</div>



via Chebli Mohamed

AJAX request to PHP - Handling response data

Im working on some AJAX login function, making a request via PHP. I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.

I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames

Is the data a JSON Object by itself? Thanks!

The code below was used before and has been verified to work.

function retrieveVersion(){
                                var URL = RSlink + "/updates";
                                $.ajax({
                                        headers : {
                                                "Content-Type" : "application/json; charset=UTF-8",
                                                "sessionid" : result
                                        },
                                        type : "GET",
                                        url : vURL,

                                        statusCode : {
                                                0 : function() {
                                                        hideLoadingMsg();
                                                        showError(networkError, false);
                                                },
                                                200 : function(data) {
                                                        currentVersion = String(data.version);
                                                        updatesArray=data.updates;
                                                        });
                                                        
                                                        }
                                                }
                                        });​


via Chebli Mohamed

How to change window title on a new popup window with custom height and width

Hi below is my code using a onclick with target="popup", how do I change the title of the new popup?

<a href="#" target="popup" 
  onclick="window.open('http://ift.tt/1UGj41N','popup','width=220,height=220,scrollbars=no,resizable=no'); return false;">Open new window</a>



via Chebli Mohamed

Javascript - Why my code is not working?

I have this code:

(The code should send the user to a div with the class "scroll". Every time the user is scrolling, it sends to the next (or previous) div with class "scroll")

(function ($) {
    var targets = $('.scroll'); // List of elements to scroll to
    var index = 0;

    // Modulo function which also works with negative numbers:
    function mod(x, n) {
        return x - (n * Math.floor(x / n));
    }

    $(window).mousewheel(function (ev) {

        if (ev.deltaY < 0) {
            index = index + 1; // Scrolling up, so increase index
        } else {
            index = index - 1; // Scrolling down, so decrease index
        }

        // Make sure the index is between 0 and (targets.length - 1)
        index = mod(index, targets.length);

        // Scroll to the target element:
        $(window).scrollTo(targets.get(index), {
            duration: 500,
            easing: 'swing'
        });
    });
})($);

I have already added ScrollTo (min) 1.4.2, MouseWheel 3.1.13 and jQuery (min) 1.7.2 to the project. I have also added a "scroll" class to all my divs where I want it to scroll.

But it doesn't seem to work.

I took this code from http://ift.tt/1UGjaGo (optimized for my own needs with bla bla for testing). The problem with this code is that it add a "current" class to every next div, what I want, is it so send the user to a specific div (with class named "scroll"). I replaced the JS in jsfiddle with the code I got from a question I asked before. Tried to optimize it but it's still not working.

You may fix the code above to fit the code from jsfiddle or optimize the code in jsfiddle. Maybe jsfiddle code would be even better since it's working well.

If you can help you will save me. Really, I already spent like 13 hours searching.

Thank you



via Chebli Mohamed

How can I paginate the thumbnails of this jQuery image slider?

Link to code below. n.b. this is quite messy as I have dropped it in from the site.

http://ift.tt/1UGjvJb

I have an image slider, with the 'active' image on the left and thumbnails for all images on the right.

The thumbnails are automatically generated based on the images in the #slider div.

You click one of the thumbnails and the active image changes.

What I need to do at request of my client, is paginate these thumbnails to a maximum of 14 items.

After item 14, will be a 'next' link, which changes to show the remaining thumbnails.

There will not be more than 28 thumbnails, if this helps. It is fine to have a 'next' link on both the 1st and 2nd page of thumbnails - no requirement for a 'previous' link.

Thank you! This is for a important project so any help much appreciated.

Important code below but please see js fiddle above for full example.

<div class="lookbook__image">
<div id="slider1">
<img src="xxxx.jpg">
... and more images
</div>
</div>

<div class="lookbook__thumbs">
<ul class="lookbook__thumbs__list">
</ul>
</div>
</div>
<script src="http://ift.tt/1UGj41L"></script>

<script>
$(document).ready(function(){
$('#slider1').cycle({
fx: 'fade', // Here you can change the effect
speed: 'slow', 
timeout: 0,
next: '#next', 
prev: '#prev',
pager: '.lookbook__thumbs__list',
pagerAnchorBuilder: function(idx, slide) { 
return '<li><a href="#"><img src="' + slide.src + '" /></a></li>'; 
} 
});
});
</script>



via Chebli Mohamed

Send While Loop To Next Row If No Change

Because we can't set table-cell's max-height so I am using this loop to limit row height (equal to cell), by increasing the table width until all rows height < max-height I set.

var i = 0,
    row, table = document.getElementsByTagName('table')[0],
    j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 200 && j < 3000) {
        j += 250;
        table.style.width = j + 'px';
    }
}

But there is a problem in this script, if for some reason a specific row height can't be less than 400px, which is greater than max-height I set for rows in script, the table becomes unnecessary 3000px wide because of the condition in loop.

Is there any way to send loop to next row if a row height is same before and after table width increment by loop. I tried web searching but nothing found to handle this, if anyone here knows about this please help me



via Chebli Mohamed

display the song name jquery

hello i have a list of songs i play in my website,i want to be able to display the current song name playing ,i have this code which have play ,pause,next,back,which works fine,but i need to edit it to display the song name,thanks for the help

     <body>
                <a class="btn" href="#" id="play" style="background-color:black">Play </a> 

                <a  class="btn"  href="#"  style="background-color:black" id="pause">Pause</a>
                <br>

                <a  class="btn"  href="#" style="background-color:black" id="skip">Next </a> 

                <a  class="btn"  href="#"  style="background-color:black" id="previous">Back</a>

 <audio    preload="metadata" tabindex="0" controls autoplay type="audio/mpeg"   class="audio-player" src="dz.mp3"></audio>

          <audio  class="audio-player" src="song2.mp3"></audio>

        <audio  class="audio-player" src="song3.mp3"></audio>

            <body>

and this is my script

<script>
var x = $(".audio-player").length;
var z = 0;
var songName = $("audio[name]")

$("#play").click(function(){
    $(".audio-player")[z].play();
    $("#song-name").text(songName);
    $("#song-name").show();
})
$("#pause").click(function(){
    $(".audio-player")[z].pause();
    $("#song-name").hide();
})
$("#skip").click(function(){
    $(".audio-player")[z].pause();
    z++;
    if (z >= x) z = 0;
    $(".audio-player")[z].play();
    $(".audio-player")[z].currentTime = 0;
    $("#song-name").text(songName);
})




$("#previous").click(function(){
    $(".audio-player")[z].pause();
    z=z-1;
    if (z >= x) z = 0;
    $(".audio-player")[z].play();
    $(".audio-player")[z].currentTime = 0;
    $("#song-name").text(songName);
})
</Script>



via Chebli Mohamed

How do I create a list with definitions using javascript and JQuery?

I am familiar with HTML5 & CSS3, and just starting to learn JS. I need help creating a list of string variables, and attach definitions to all of them.

Basically, I need a two column table, where the left column is the list of strings, and when you click the words, it pulls up the definition on the right. I also need to make sure that the page doesn't reload when you click on the different words.

The photo (link below) best illustrates what I'm trying to create.

http://ift.tt/1MqWPLO



via Chebli Mohamed

Better way to change parent div class name when click

How to change the UL class name(menu1) when click each LIs ?

For example,

when click "tab1", change UL's class name to "menu1".

when click "tab2", change UL's class name to "menu2".

when click "tab3", change UL's class name to "menu3".

This code is I tried.

<ul class="tab menu1">
   <li class="tab1">t1</li>
   <li class="tab2">t1</li>
   <li class="tab3">t1</li>
</ul>

<script>
$('.tab1').click(function(){
   $('.tab').addClass('menu1');
   $('.tab').removeClass('menu2');
   $('.tab').removeClass('menu3');
});

$('.tab2').click(function(){
   $('.tab').removeClass('menu1');
   $('.tab').addClass('menu2');
   $('.tab').removeClass('menu3');
});

$('.tab3').click(function(){
   $('.tab').removeClass('menu1');
   $('.tab').removeClass('menu2');
   $('.tab').addClass('menu3');
});
</script>



via Chebli Mohamed

jQuery selector from a variable

JSFIDDLE LINK

var $select = $('select');

$select.on('change', function () {
    var value = $(this).val();
    var modifier = value.split('_')[0];
    var target = modifier + '_target';

    console.log(target);

    $('div').filter(target).addClass('active');

});

If you open console and select any option from the select, you'll see that the text that is thrown to the console is legit (as I want to select modifier1_target depending on the selected option).

However, I can not make a jQuery selector out of this, so as the div is selected and applied an active class.

I tried $(el).attr('class', target) but it didn't work surely.

I am running out of ideas where am I wrong here?



via Chebli Mohamed

How could I customize the datatable with custom text and remove footer

I want to customize the datatable,

here's the current JS code,

  $(document).ready(function() {
      $('#flight_prices').DataTable({"bPaginate": false, "bFilter": true});
  } );

enter image description here



via Chebli Mohamed

DateTimePicker shows ontop of input

I am using the "Timepicker Addon for jQuery UI Datepicker". It is working for what I need and a pretty slick addon, but I am having a problem. I have a page full of inputs and with the ones close the top and it seems to get confused on it's own height. For some reason it seems think it is shorter than it actually is. This causes the datetimepicker to actually sit on top of the input so to speak and cover it so you can't see what it is doing.

I did do some testing and found that when I made the time picking part on the bottom "display: none" it fit on the page and lined up just right. Not really sure what to do. Something as simple as always having it pop up on the bottom would solve it.

enter image description here



via Chebli Mohamed

jQuery: Unable to access array elements using variable and array literal

first Q/ Noob.

I have several arrays set up inside $(document).ready(function(){ --e.g. var caribbean = ["AG", "AI", "AN", "AW", "BB", "BL"];

Each element is a unique inside a Each element bordered with where class = a specific subcontinent

    `<div class="flag">  
        <a class="029" id="aw" href="#"><img class="media-object custom-media" src="flags/Aruba.png" alt="Aruba"> </a> 
        <p> Aruba </p>
    </div>`

--e.g. 029 = carribean

The user-selected subcontinent is verified in an array of all subcontents.

I hide all flags from all subcontinents. No problem to there.

I'm trying to show the appropriate flags, based on the user selection.

Tried so far each(), forEach() --> "TypeError: invalid 'in' operand a":jquery-2.1.4.min.js line 2000+

Found info on AJAX, PHP, and Json.

Now trying to 'for loop' through the array, "caribbean" (in this example).

Using alert I found that the contents of the variable arrayName ("caribbean") is being converted into a char array - arrayName.length === 9

    `for (var i = 0; i < arrayName.length; i++)
    {
        alert( "Name: " + arrayName + "    " + "Index : " + i + "    " +     "Index value: " + arrayName [i]);
    };`

I have changed variables around in case of reserved words and have found quite a bit on creating the char array.

I am trying to reference the array without the contents of arrayName becoming it's own array. At this point, I can't think of anything else to try and haven't found anything more pointing to a potential solution.

The project is HTML, CSS and javascript/ jQuery. It uses the Bootstrap row/ column setup and custom overflow sliders.

Also, in looking around I'm not sure if I should be using hide()/ show() or display: block/ none. I need the resulting display to sequence into the bootstrap column without leaving gaps, top down. Please advise.

I would appreciate any direction you could provide. I am stumped. TIA.

RAd



via Chebli Mohamed

what does jquery focus.bind(domObj) do?

so I encountered this code:

setTimeout(domObj.focus.bind(domObj), 500);

What does that do in plain English?

what does focus.bind do?

and what would passing a domOBj into the bind() function accomplish?



via Chebli Mohamed

Long Polling don't works;

longpolling.js

function getContent( timestamp )
{
    var queryString = {"timestamp" : timestamp};

    $.ajax({
            type: "GET",
            url: '/php-long-polling-master/server/server.php',
            data: queryString, 
            sucess: function ( data ) {
            var obj = jQuery.parseJSON( data )[0];
            $( '#response' ).html( obj.content );       
            // reconnect with other timestamp from **server.php**
            getContent( obj.timestamp );
            }
    });
}


$( document ).ready ( function ()
{
    getContent();
});

server.php

<?php
require 'pdo.php';
set_time_limit(0);
while ( true )
{
    $requestedTimestamp = isset ( $_GET [ 'timestamp' ] ) ? (int)$_GET [ 'timestamp' ] : time();

    clearstatcache();

    $stmt = $pdo->prepare( "SELECT * FROM publication WHERE publication_time >= :requestedTimestamp" );

    $stmt->bindParam( ':requestedTimestamp', $requestedTimestamp );
    $stmt->execute();
    $rows = $stmt->fetchAll( PDO::FETCH_ASSOC );

    if ( count( $rows ) > 0 )
    {
        $json = json_encode( $rows );

        var_dump($rows);

        echo $json;
        break;


} else  {
    sleep( 2 );
    continue;
    }

}
?>

The problems:

  1. longpolling.js don't have a timestamp, the log shows: get /directory/directory/server.php instead server.php?timestamp=TimeInMilisseconds

  2. If don't have a timestamp, the server.php never will show results :|



via Chebli Mohamed

JQuery remove key and its value from an Array

I am trying to figure out how to remove a key called age from an array.

I tried below splice, but didnt help me removing the key and retain other keys and values in an array.

$(data).splice("age",1);

Here is my full code that outputs an array

var data = {'fname': 'John', 'lname': 'Smith', 'age': 29, 'job': 'Agent' };

$(data).splice("age",1);

console.log(data);

Here is JSFiddle link that demonstrates above example.



via Chebli Mohamed

Javascript validate human field for contact form

OK, I have tried getting my contact form to work trying to update the php - with no success. Thank you to those of you who attempted to help with my previous question. I now think I should be able to get this to work by updating the JS, but of course I know about as much JS as I do PHP!

So here we go again...

I have a contact form I am using in a Bootstrap responsive single-page site. The form works just fine and sends the emails just fine. My site does not get a whole lot of traffic and I dislike the Captcha fields, so I wanted to insert a simple field for users to enter to ensure they are human. I added a simple math question. Now, I need to know how to validate that the user entered the correct math answer before the email is processed.

My form uses a contact_me.js file in combination with the jqBootstrapBalidation.js file to validate and send the form to the contact_me.php to process the email. I tried updating the PHP (with some suggestions from here) but I could not get it to work. It will always send the email through even if the math answer was entered incorrectly.

It is important to note that I did not write the code for this, I am very new to js. The form and code was supplied by startbootstrap.com templates.

Looking at the contact_me.js field, I can see that it starts off validating the fields with the jqBootstrapBalidation.js. I see it then moves down to a preventDefault and has a comment stating "prevent spam click and default submit behaviour. Is this code already preventing SPAM emails here?

If it is not, I want to force the user to input the correct answer to the math question. I added this field myself. I added the variable for the human field to the contact_me.js file (I assume I needed to do this) to get the value from the form.

Further down on the .js file it then uses ajax to post to the contact_me.php to process the email. Below this is where it looks like it further validates the fields and displays the success/error messages. Is there someplace here I can verify if the user entered the correct math equation (answer should be =5) and if it is correct, then to process the email via the contact_me.php and if the answer is incorrect then to display an error message without sending to the php and ask to try again? Below is the html, contact_me.js and the contact_me.php. Thank you so much for your help with this!

HTML:

 <form name="sentMessage" id="contactForm" novalidate>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Name</label>
                            <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Email Address</label>
                            <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Phone Number</label>
                            <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Message</label>
                            <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Human</label>
                            <input type="text" class="form-control" placeholder="Two + 3 = ?" id="human" required data-validation-required-message="Please solve math equation to prove you are human">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                     <br>
                    <div id="success"></div>
                    <div class="row">
                        <div class="form-group col-xs-12">
                            <button type="submit" class="btn btn-success btn-lg">Send</button>
                        </div>
                    </div>
                  </form>

contact_me.js:

  $(function() {

$("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function($form, event) {
        // Prevent spam click and default submit behaviour
        $("#btnSubmit").attr("disabled", true);
        event.preventDefault();

        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var phone = $("input#phone").val();
        var message = $("textarea#message").val();
        var human = $("textarea#human").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }
        $.ajax({
            url: "././mail/contact_me.php",
            type: "POST",
            data: {
                name: name,
                phone: phone,
                email: email,
                message: message,
                human: human
            },
            cache: false,
            success: function() {
                // Enable button & show success message
                $("#btnSubmit").attr("disabled", false);
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Your message has been sent. </strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#contactForm').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            },
        })
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

$("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
});
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
$('#success').html('');
});

contact_me.php:

<?php
// Check for empty fields
if(empty($_POST['name'])        ||
empty($_POST['email'])      ||
empty($_POST['phone'])      ||
empty($_POST['message'])    ||
empty($_POST['human'])  ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}

//Check if simple anti-bot test is correct
if ($human !== 5) {
   $errHuman = 'Your anti-spam is incorrect';
}   

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$message = $_POST['human'];

// Create the email and send the message
$to = 'info@mysite.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Portfolio Website Message:  $name";
$email_body = "You have received a new message from your portfolio website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@mysite.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>



via Chebli Mohamed

JQuery search bar to hide table rows

Hopefully someone will be able to help me with this. I have a dynamically created table full of info, and I am trying to use JQuery to only show rows that are matching what is being typed in the search bar. The match is of the first td within each row. I am not sure why this does not work.

JQuery
                        var $foo = $('#table-name tr input[name="someValue"]');
                    $('#search').keyup(function() {
                        var bar = $.trim($(this).val()).toLowerCase();


                        $foo.parent().parent().show().filter(function() {
                            var thud = $(this).val().toLowerCase();
                            return !~thud.indexOf(bar);
                        }).hide();

When entering any character in the search bar all of the rows disappear, whether or not there are any matches. The table is structured as follows:

    table
    <table id="table-name">
            <thead>
                <tr>
                    <th>0</th>
                    <th>1</th>
                </tr>
            </thead>
    <c:forEach>
    <form:form id = “{id}”>
                    <tr id="${id2}">
    <td><input type="text" class= “someClass" name= “someValue"> </input></td>
        <td><select class="someClass" name="otherValue"> </select> </td>
    </tr>
    </form:form>
</c:forEach>
</table>

Why is my JQuery not behaving correctly?



via Chebli Mohamed

How to Completely Remove Element Based on Screen Size

I have two forms that have to use the same IDs, etc. however, one is specifically for mobile viewing and the other for everything else. I am using media queries and display: none to show/hide each, but of course they are both technically still coded ON the page, which means neither of them work. So instead I am trying to think of a way to totally remove the element based on screen size. It has to be actually removed and not simply hidden.

I'm stuck and I need to get the site migrated by tonight. Any suggestions would be most appreciated!!!



via Chebli Mohamed

Can I use a callback with .submit in jquery

I'm trying to prevent a return false or undefined from the submit handler. I only want to return a value after the async results come back from google maps. Is this possible? My objective is to wait for google map results to come back before I go to my controller.

$('form').submit(function (e) {
        
        var geocoder = new google.maps.Geocoder();
        var address = $('#SearchQuery').val();
        
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status != google.maps.GeocoderStatus.OK) {
                
                alert("Geocode was not successful for the following reason: " + status);
                return false;
            } else {
                $("#latitude").val(results[0].geometry.location.G);
                $("#longitude").val(results[0].geometry.location.K);
                
                alert("Geocode successful");
                return true;
            }
        });
        //don't let anything get returned here, is a callback needed?
    });


via Chebli Mohamed

jquery file upload with angular - upload as files are added

I am trying to figure out how to upload files as they are loaded instead of clicking the start upload button in angular, similar to how the basic file uploader is working.

http://ift.tt/1shWksu

I have tried using add() with ng-change on the file input and went through all the event listeners to manually call add() but can't seem to get anything to work.



via Chebli Mohamed

jquery return error msg from php server not showing in div

i have a simple code for js on my side and wanted to return the error msg from my php json server side if there is an error such like custom msg

php

<?php
header('Content-Type: text/html; charset=utf-8');
require_once('class/MysqliDb.php');
$db = new Mysqlidb();
$cols = array("card_id","card_os");

$cards = $db->get("cards",null,$cols);
if($db->count >0){
$cards['status'] = 'success';
} else {
$cards['status'] = 'fail';
$cards['error'] = 'fail to insert';
}
echo json_encode($cards);
?>

as for my js

 $(document).ready(function() {
 $.post('./get_cards.php',$(this).serialize(),function(msg){


 if(msg.status == 'success'){
 $('#cardlist').html(format(msg));                        
 }
 else if(msg.status == 'fail') {
  console.log(msg.error);
 $('#cardlist').html(msg.error);
 }
 },'json');

 } );

i am trying to have my #cardlist div to have this error msg 'fail to insert' from my server side. It is not showing the msg in the div but instead when is there is data is populating correctly.



via Chebli Mohamed

html,head and body tags are being deleted after processing Javascript. So how to avoid such deletion? [on hold]

With the help of the following code, I can add number of colspan according to number of td available within a table.The problem with is that, it is adding properly colgroup, but after processing, it is deleting some tags within that same page(html,head,body tags).

How can I avoid such deletion?

$(document).ready(function() {

    $('#btnApply').on('click', function() {

        var input = '<div>' + $('#input').text() + '</div>';
        var html = $('<div/>').html(input).contents();
        console.log(html.find('table'));
        var output = '';
        html.find('table').each(function() {

            var colCount = 0;
            $(this).find('tr:nth-child(1) td').each(function() { // Get the count of table columns

                if ($(this).attr('colspan')) { // if there is a <td colspan>
                    colCount += +$(this).attr('colspan');
                } else {
                    colCount++;
                }
                console.log($(this));
            });


            var colgroupList = '';
            for (i = 0; i < colCount; i++) { // Add a <colgroup></colgroup> for each <td>
                colgroupList += '<col width="50%"></col>';
                console.log(colgroupList);
            }
            console.log('<colgroup>' + colgroupList + '</colgroup>');

            $(this).find("tbody").prepend('<colgroup>' + colgroupList + '</colgroup>');

            output += '<table>' + $(this).html() + '</table>';

        });

        $('#output').html(output);
        $('#outputHTML').text(output);
        $('#outputArea').fadeIn(1000);

    });

});

So can anyone help me. You can view my fiddle.



via Chebli Mohamed

Adding multiple matchMedia into script

I'm trying to add

var mql = window.matchMedia("(max-width: 480px)"),  window.matchMedia("(max-height: 479px)");

into my existing script right now which only has

var mql = window.matchMedia("(max-width: 480px)"). 

When I add the second .matchMedia the script doesn't fire at all.

I've tried adding two variables

       var mqls = [ 
window.matchMedia("(max-width: 480px)"),
window.matchMedia("(max-height: 479px)")
]

   function mediaqueryresponse(mql){
document.getElementById("match1").innerHTML = mqls[0].matches // width: 480px media match?
document.getElementById("match2").innerHTML = mqls[1].matches // width: 479px media match?
}

Here is the script working before adding max-height:

  • Please note that the script is at the bottom of js panel. The top script is for TweenMax to animate the lines

JSFIDDLE

Here is the script with the added variables.

JSFIDDLE



via Chebli Mohamed

Use AJAX to load content to a jQuery UI dialog

On my site, I have a bunch of profile previews that are being generated by running JSON data through a mustache.js template.

Here's the template:

<script id="profile-preview-template" type="text/template"> 
    <div class="col-sm-3">
        <a style="display:block">
            <div class="profile-preview">
                <img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
                <h1>{{first_name}} {{last_name}}</h1>
                <h2 class="text-muted">{{major}}</h2>
                <h3 class="text-muted">Cohort {{cohort}}</h3>
            </div>
        </a>
    </div>
</script> 

The profile preview shows select info from the JSON info like first_name, last_name, etc.

Here's the format of the JSON data:

{
"profiles": [
{
  "first_name": "Robert",
  "last_name": "Hosking",
  "img_url": "img/about/hackbert.jpg",
  "major": "Computer Science",
  "cohort": 12,
  "bio": "some info",
  "linkedin": "some url",
  "home_town": "some place",
  "status": "Student"
},
{
  "first_name": "Jimmy",
  "last_name": "Harval",
  "img_url": "img/about/hackbert.jpg",
  "major": "Chemistry",
  "cohort": 13,
  "bio": "some info",
  "linkedin": "some url",
  "home_town": "some place",
  "status": "Student"
}
]
}

However, when one of the previews is clicked, I'd like to make a jQuery UI dialog modal popup containing all of the info in the JSON data (not just the data displayed in the preview).

My question is how do I get a reference as to which profile preview was clicked so I know where in the JSON file to look to get the rest of the information.



via Chebli Mohamed

Jquery. Convert String to number and add 1

This is what I tried to convert a string to a number and add 1:

<script>
var title = $("div.example");
var parts = title.split(' - ');
var parts2 = +parts[0];
var convert = parts2 + 1;
$("div.example").replace(parts2 , convert);
</script>



via Chebli Mohamed

Query Inside Parse Cloud For Loop

I have been trying to run my Parse Cloud Code for some time and can not seem to get around this problem:

I have an array of Parse objectId's called IDArray. I then am sending the array as a parameter of a PFCloud call. Once the array has been sent to the Cloud Code, I can not seem to successfully create a for loop that goes through and updates a number value stored as "points" on Parse for each objectId.

In a nutshell, this is all I am trying to accomplish:

  • I just need to be able to have the for loop go through each objectId and perform an action for each ID.

I have been trying to get this to work for some time but have had no luck. Here is the code that I have been trying to manipulate - hopefully it will give someone a starting point to answer my question.

Parse.Cloud.define('updateAllUsers', function(request, response) {
    var UserData = Parse.Object.extend('UserData');
    var query = new Parse.Query(UserData);
    var list = request.params.listID;
    var currentuser = request.params.user;

                   
    for (var i = 0; i < list.length; i++) {
                   
        var userdata = list[i];
                   
        query.get(list[i], {
                                       
            success: function(userdata) {
                                       
                response.success('Should add up');
                userdata.increment('Done', +1);
                userdata.save();
            },
            error: function() {
                response.error('something went wrong ' );
            }
        });
    }
});

If someone could please help me with this I would be very grateful. Thank you



via Chebli Mohamed

My img div is floating in the other div

I'm trying to get my bootstrap img-responsive to get to the bottom of the div, but it no matter what I do, it won't move. I've tried altering the img-resposive CSS file setting height:to 0and bottom:to 0 but it doesn't fix the problem. I'm new to this and probably missing something out, so please be tolerant.

<!--this is the bootstrap.css file -->
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
  display: block;
  max-width: 100%;
  height: 0;
  bottom:0;

}
<!--and this is the html -->
<div class="col-md-9 hidden-sm">
                    <img src="img/valencia.png" class="img-responsive animated fadeInRight" alt="mockup">
                </div>


via Chebli Mohamed

Fadeout page after animation finishes

I want an animation (function handleScreen(mql)) to run and after it is completed, for the page (#splash,#name) to fade out. I tried adding a .done function but that doesn't seem to work. Any help would be very much appreciated.

$(document).ready(function() {

    $("#splash,#name").show()

    var mql = window.matchMedia("(max-width: 480px)");

    function smallBlock() {
        //STUFF
    };

    function largeBlock() {
        //STUFF
    };

    function handleScreen(mql) {
        if (mql.matches) {
            smallBlock();
        } else {
            largeBlock();
        }

        mql.addListener(handleScreen);
        handleScreen(mql);
    };

    $.when(handleScreen(mql).done(function() {
            setTimeout(function() {
                $("#name,#splash").fadeOut("slow")
            }, 1000)
        });
    });
});



via Chebli Mohamed

Angular-Slick and dynamic data not initializing correctly

I'm using the angular-slick directive because I have found this to work best for me in most instances. However, I'm still having a problem with getting the slides to initialize properly with dynamic data.

I have a dropdown that updates the relatedResorts json object in a factory. My controller watches for this update and updates scope.relatedResorts accordingly. That all works fine.

Before the slider updates, the slides/content+images are there and it looks like its working. The slick-initialized class has been applied and the excess slides are hidden. But they won't drag or auto advance and the arrows don't even show up.

I then make the images clickable so you can update the json object by clicking on one of the cards as well. The slider actually works better after an image is clicked and the object is refreshed, oddly enough, but the arrows still won't work. You can even drag the slider and see the other slides.

I have tried slick and unslick (which works only after the dom is loaded even with a $timeout applied and seems like a bit of a hack), creating my own directive, and $timeout. I've racked my brains trying to figure this one out.

help please...

HTML:

<slick class="row slider" arrows="true" responsive="breakpoints" slides-to-show=3 slides-to-scroll=1 dots="false" infinite="true" speed="300" touch-move="false" ng-if="relatedResorts.length" init-onload=true data="relatedResorts">
    <div class="card col-md-4 col-sm-6 col-xs-12" ng-repeat="option in relatedResorts" ng-click="resetResort(option.id)">
        <div class="img-container"> 
                <div class="banner">
                <p>{{option.resort_name}}</p>
            </div>
            <img ng-src="assets/images/resorts/{{option.id}}/{{option.resort_img}}" alt="Luxury Resort: {{option.resort_name}}"/>
        </div>
    </div>
</slick>

CONTROLLER:

resortModule.controller('relatedResortsController', ['$scope', 'locaService', '$timeout', function($scope, locaService, $timeout) {
    $scope.relatedResorts;
    $scope.resort;
    $scope.getRelated = function (resort) {
        //Resorts in location/destination on location change
        locaService.fetchRelatedResorts(resort).then(function(result) {
            $scope.relatedResorts= result;
        });
    }
    $scope.resetResort= function(resort){
        //reset resort for app when related resort image is clicked on. 
        $scope.resort= resort;
        locaService.updateResort(resort);
        /*$(".slider").slick('unslick');
        $(".slider").slick();*/
    }

    //watches factory for updates to objects
     $scope.$on('resortUpdated', function() {
        $scope.resort = locaService.resort;
        $scope.getRelated($scope.resort);
    });
}]);



via Chebli Mohamed

Access elements in collapsible section

I am trying to access the fields that are presented after clicking the "sections" button on each class. What would be the best way to approach this using Javascript?

Link: http://ift.tt/1NtIV8R



via Chebli Mohamed

ria services + jquery

i have used ria.js or upshot but same error in jquery: object is undefined

THis error is inside the jquery at 630 lines, inside each:function
--> length = object.length

my javascript can call the domainservice and have the json response, and in the debugger i have this response :

{"GetTodoItemsResult":{"TotalCount":4,"RootResults":[{"IsDone":false,"Title":"Todo item 1","TodoItemId":1},{"IsDone":false,"Title":"Todo item 2","TodoItemId":2},{"IsDone":false,"Title":"Todo item 3","TodoItemId":3},{"IsDone":false,"Title":"Todo item 4","TodoItemId":4}]}}



via Chebli Mohamed

Pre-loading site layer and Jquery

Anyone can tell me WHAT is wrong with this code. Doesn´t work for me. I put big images (size) to test, but still not working.

Pre loading site with DIV, image pre-loading and JQUERY

On the

<script src="http://ift.tt/1rfghyb"></script>
<style>
.modal {
    display:    none;
    position:   fixed;
    z-index:    10000000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('http://ift.tt/V4kkSr') 
                50% 50% 
                no-repeat;
}


body.loading {
    overflow: hidden;   
}


body.loading .modal {
    display: block;
}
</style>

<script>
$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");   },
     ajaxStop: function() { $body.removeClass("loading");  }    
});


</script>

And before

<div class="modal"><!-- Place at bottom of page --></div>
</body>



via Chebli Mohamed

Infinite scroll within Ajax

So, I have Ajax enabled on my Wordpress site as the following:

id within any anchor within the chosen div will be saved and used to find an appropriate php file then loaded at an appropriate content div.

PHP

<!--Menu part -->
 <div class="royal_front_menu">
      <a href="#rcp_front_front_id" class="mdl-tabs__tab is-active" id="front_id">All</a>       
      <a href="#rcp_front_electronic_id" class="mdl-tabs__tab" id="electronic_id">Electronics</a>         
</div>

<!--Content Part-->
<div class="active" id="rcp_front_front_id">  
     <div class="spinner"></div>
</div>
<div class="not_active" style="display:none;" id="rcp_front_electronic_id"> 
     <div class="spinner"></div> 
</div>      


<script>
//Ajax loading
jQuery(document).ready(function() {
    jQuery('.royal_front_menu a').click(function(e) {
        e.preventDefault();

        var tab_id = jQuery(this).attr('id'); 

        jQuery.ajax({
            type: "GET",
            url: "<?php echo admin_url('admin-ajax.php'); ?>", 
            dataType: 'html',
            data: ({ action: 'royal_front_tab', id: tab_id}),
            success: function(data){
                  jQuery('#rcp_front_' + tab_id).html(data);


        },
        error: function(data)  
        {  
        alert("Error!");
        return false;
        }  

        }); 

 }); 
 });
</script>

FUNCTION.PHP

//Ajax call for front page for Mobile
function royal_front_tab_rhm_callback() {  
     $template_part_path = 'page-parts/rhm/front/01_front_menu_' .  $_GET['id'];
get_template_part($template_part_path);
exit;
}
 add_action('wp_ajax_royal_front_tab_rhm', 'royal_front_tab_rhm_callback');
 add_action('wp_ajax_nopriv_royal_front_tab_rhm', 'royal_front_tab_rhm_callback');

01_front_menu_front_id.php

<div class="content">
    <?php echo do_shortcode('[Post_Shortcode]'); ?> 
</div>

So far so good...

So, with the following setup, everything is working fine. All the contents are called only when clicked etc. GREAT!

However, I am trying to add one more feature: Infinite scroll

What I have done so far:

I followed the following instruction: http://ift.tt/L0bQWp

So, I tried this on a separate dummy site to see how it works before messing things up.

SET UP

Add the following to the function.php:

// To add infinitescroll js
function custom_theme_js(){
    wp_register_script( 'infinite_scroll',  get_template_directory_uri() . '/custom_js/jquery.infinitescroll.min.js', array('jquery'),null,false );
    wp_enqueue_script('infinite_scroll');

}
add_action('wp_enqueue_scripts', 'custom_theme_js');

//To add selectors
function custom_infinite_scroll_js() {
    { ?>
    <script>
    jQuery('.royal_card.site-row-fluid.site-grid-list').infinitescroll({
        navSelector  : jQuery('.site-pagination'),
        nextSelector : jQuery('.site-pagination > a.next'),
        itemSelector :  '.royal_card.site-row-fluid.site-grid-list > .royal_card_outer.royal_card_content_grid',
        contentSelector: jQuery('.royal_card.site-row-fluid.site-grid-list'),
    msgText: "Yay"  
    },function(newElements){
        jQuery('.site-separator').remove();
        jQuery('.royal_card.site-row-fluid.site-grid-list > .royal_card_outer.royal_card_content_grid').after('');
     });
    </script>
    <?php
     }
 }
add_action( 'wp_footer', 'custom_infinite_scroll_js',100 );

When I tried this on a dummy site (without Ajax), it works fine. I can get the next page content as infinite scroll.

The "Normal" URL from the dummy site is this:

 <a class="page-numbers" href="http://ift.tt/1zVzOFL">2</a>

Problem

So, with the Ajax page, I found something peculiar. The page URL became somewhat odd:

 <a class="page-numbers" href="http://ift.tt/1ILDSQ4">2</a>

Because it is not a normal URL, it leads to a "404" page as it does not exist.

Here is my guess

I thought that jQuery('.royal_front_menu a').click(function(e) { which any anchor within royal_front_menu div will be affected. But the content is loaded outside of the div.

Okay, I am confused to why it is happening.

Any suggestions?



via Chebli Mohamed

Jquery DataTable filtering without using a global object

I have a datatable that is sometimes shown and sometimes hidden. I also have several other tables on the same page.

The datatables example (located here) uses a global object to store your custom function $.fn.dataTable.ext.search. This is great, it affects all tables.

I can't find a way to provide a search function per table and not add it to a global variable.



via Chebli Mohamed

Select2 dynamic dropdowns with templating

Trying to work out how to use the select2 templating function with a dynamic select2 dropdown to also show the extra data in a JSON response

Example data

{"id":"12","value":"DASGDSA67","otherData":"Brunswick","extraData":"Heads"}

View (Javascript)

<script type="text/javascript">
$(document).ready(function() {
    $(".company2").select2();
    $(".location2").select2({
        templateResult: formatState
    });
});

$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
    url:"../api/locations/" + $company2.val(),
    type:'GET',
    success:function(data) {
        var $location2 = $(".location2");
        $location2.empty();
        $.each(data, function(value, key) {
            $location2.append($("<option></option>").attr("value", value).text(key));
        }); 
        $location2.select2();
    }
});
}).trigger('change');

function formatState (state) {
  if (!state.id) { return state.text; }
      var $state = $(
         '<h1>' + state.element.value() + '</h1>' + '<p>' + state.element.otherData() + '</p>'
      );
  return $state;
};
</script>



via Chebli Mohamed

Wrap links found in content editable div on user keypress.

How would I go about wrapping text in a content editable div that is a URL right when the user enters it and without changing the position of the cursor? I had this same issue with handling #hashtags and @mentions, but I was able to get passed that by using At.js .



via Chebli Mohamed

highcharts legend-item text to align below legend item

I am trying to place the Highcharts legend item text below the legend. i tried to display block for the legend inside highcharts function nothing works to move the text exactly below the highcharts Legend. Any help is appreciated. legend: { enabled: true, symbolWidth: 85, symbolHeight: 15, align: 'left',

            // itemStyle:{
            //  float: 'left',
            //  display: 'block',
            //  position: 'relative'
            // }
            //useHTML: true

}



via Chebli Mohamed

Modify JavaScript Filter to allow dates and multiple selection options combined on each filter rule

I have a JavaScript Filter which allows me to filter out rows (make hidden) from my Task List.

Demo of what I have right now: http://ift.tt/1NtGe72

It currently works with dropdown selection fields and allows multiple filters to be combined.

For example you can filter out every task that doesn't have a Status of Completed and doesn't have a Milestone set to Milestone 3.

It works great thanks to the help creating it from SO user Lucio Paiva on my other question here How to combine multiple FIlters together to filter Task Rows using jQuery?

It looks like this...

enter image description here


I now need to improve upon the features of this code to add some different types of filters besides a simple true/false based on a dropdown selection.

  1. Date Range - I need to add in the ability to filter out rows that dont match a date range. FOr example be able to use a fancy date range selector... enter image description here
  2. Multi-select/checkbox - I also need to be able to select more than 1 item for some of the filter columns. For example on the Milestone column. Be able to select Milestone 2 and Milestone 3 and it would filter out all rows that don't match one of the 2. Image below shows example of GitHub issue which has a filter that allows more than 1 selection on a Label filter. IMage has 3 labels filters selected... enter image description here
  3. With both these new types of filters it needs to still work with the existing dropdown selection filters and still allow multi-filter so that many filters can be set and work together like it currently works.

Below is my code for the filter JS and HTML


JavaScript which filters the Task list rows...

(function () {
  var
    filters = {
      user: null,
      status: null,
      milestone: null,
      priority: null,
      tags: null,
      title: null
    };

  function updateFilters() {
    $('.task-list-row').hide().filter(function () {
      var
        self = $(this),
        result = true; // not guilty until proven guilty

      Object.keys(filters).forEach(function (filter) {
        if (filters[filter] && (filters[filter] != 'None') && (filters[filter] != 'Any')) {
          result = result && filters[filter] === self.data(filter);
        }
      });

      return result;
    }).show();
  }

  function bindDropdownFilters() {
    Object.keys(filters).forEach(function (filterName) {
      $('#' + filterName + '-filter').on('change', function () {
        filters[filterName] = this.value;
        updateFilters();
      });
    });
  }

  bindDropdownFilters();
})();

HTML table of Filters and Tasks which the Filters apply to...

<br><h2>Testing Task List Filters</h2><hr><br>

<div class="container">
  <div class="row">

      <table class="table">
        <thead>
          <tr class="filters">
            <th>
              <input type="text" id="title-filter" value="" class="form-control">
            </th>
            <th>Assigned User
              <select id="user-filter" class="form-control">
                <option>None</option>
                <option>John</option>
                <option>Rob</option>
                <option>Larry</option>
                <option>Donald</option>
                <option>Roger</option>
              </select>
            </th>
            <th>Status
              <select id="status-filter" class="form-control">
                <option>Any</option>
                <option>Not Started</option>
                <option>In Progress</option>
                <option>Completed</option>
              </select>
            </th>
            <th>Milestone
              <select id="milestone-filter" class="form-control">
                <option>None</option>
                <option>Milestone 1</option>
                <option>Milestone 2</option>
                <option>Milestone 3</option>
              </select>
            </th>
            <th>Priority
              <select id="priority-filter" class="form-control">
                <option>Any</option>
                <option>Low</option>
                <option>Medium</option>
                <option>High</option>
                <option>Urgent</option>
              </select>
            </th>
            <th>Tags
              <select id="tags-filter" class="form-control">
                <option>None</option>
                <option>Tag 1</option>
                <option>Tag 2</option>
                <option>Tag 3</option>
              </select>
            </th>
          </tr>
        </thead>
      </table>


    <div class="panel panel-primary filterable">
      <div class="panel-heading">
        <h3 class="panel-title">Tasks</h3>
        <div class="pull-right"></div>
      </div>





      <table id="task-list-tbl" class="table">
        <thead>
          <tr>
            <th>Title</th>
            <th>Created</th>
            <th>Due Date</th>
            <th>Priority</th>
            <th>Milestone</th>
            <th>Assigned User</th>
            <th>Tags</th>
          </tr>
        </thead>

        <tbody>

          <tr id="task-1"
              class="task-list-row" 
              data-task-id="1"
              data-title="Task title 1"
              data-user="Larry"
              data-status="In Progress"
              data-milestone="Milestone 2"
              data-priority="Urgent"
              data-tags="Tag 2">
            <td>Task title 1</td>
            <td>01/24/2015</td>
            <td>09/24/2015</td>
            <td>Urgent</td>
            <td>Milestone 2</td>
            <td>Larry</td>
            <td>Tag 2</td>
          </tr>

          <tr id="task-2"
              class="task-list-row" 
              data-task-id="2"
              data-title="Task title 2"
              data-user="Larry"
              data-status="Not Started"
              data-milestone="Milestone 2"
              data-priority="Low"
              data-tags="Tag 1">
            <td>Task title 2</td>
            <td>03/14/2015</td>
            <td>09/18/2015</td>
            <td>Low</td>
            <td>Milestone 2</td>
            <td>Larry</td>
            <td>Tag 1</td>
          </tr>

          <tr id="task-3"
              class="task-list-row" 
              data-task-id="3"
              data-title="Task title 3"
              data-user="Donald"
              data-status="Not Started"
              data-milestone="Milestone 1"
              data-priority="Low"
              data-tags="Tag 3">
            <td>Task title 3</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>Low</td>
            <td>Milestone 1</td>
            <td>Donald</td>
            <td>Tag 3</td>
          </tr>


          <tr id="task-4"
              class="task-list-row" 
              data-task-id="4"
              data-title="Task title 4"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 1"
              data-priority="High"
              data-tags="Tag 1">
            <td>Task title 4</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 1</td>
            <td>Donald</td>
            <td>Tag 1</td>
          </tr>

          <tr id="task-5"
              class="task-list-row" 
              data-task-id="5"
              data-title="Task title 5"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 3"
              data-priority="High"
              data-tags="Tag 1">
            <td>Task title 5</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 3</td>
            <td>Donald</td>
            <td>Tag 1</td>
          </tr> 

          <tr id="task-6"
              class="task-list-row" 
              data-task-id="6"
              data-title="Task title 6"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 2"
              data-priority="High"
              data-tags="Tag 3">
            <td>Task title 6</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 2</td>
            <td>Donald</td>
            <td>Tag 3</td>
          </tr>


          <tr id="task-7"
              class="task-list-row" 
              data-task-id="7"
              data-title="Task title 7"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 1"
              data-priority="High"
              data-tags="Tag 1">
            <td>Task title 7</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 1</td>
            <td>Donald</td>
            <td>Tag 1</td>
          </tr>

        </tbody>
      </table>
    </div>
  </div>
</div>



via Chebli Mohamed

samedi 1 août 2015

Design Pattern for Custom Fields in Reporting System

I have assigned a task to create (relatively) simple reporting system. In these system, user will be shown a table result of report. A table has some fields and each field give some part of information to user in each record. My problem however is that each report field will not be declared by developer. It must be declared by user of system. So my reports table are dynamic.

I saw example in 'Data Driven Custom View Engine in ASP.NET MVC' for creaing dynamic forms using Asp.net MVC Framework but I don't know that is appropriate for my system or not.

Update1:

Currently I ended with followind Entity Relationship Diagram: enter image description here

In above diagram, I store every record for report in Report table. Also I store type of report in ReportType. For each field that will be used in report record I will use a ReportFieldValue. Type of fields will be stored in ReportField.

So If I want to add a record to my db first I add a row to Report Table. Then for each added record fields I will add a row to ReportFieldValue table.

However as you may notice, in these approach I must store every field value in char(255). The problem is for fields type like datetime that should not be stored as string. Is there any design pattern or architecture for this type of systems?

Get SQL query from user and run it against SQL Server

I want to develop very small application by C# which get some SQL query from user and execute it against specified SQL Server.

SQL Server and database must specified by user thus every things can change. My problem is user can enter various type of SQL queries, and every king of it should run in its own way.

For example

SELECT * FROM mytable

and

UPDATE mytable 
SET city = "NY" 
WHERE name = "tom"

can not execute in the same way.

I think I need to recognize user query type in my code, Is there any way to recognize it or any better way to run any possible query?

distinct in mssql server

I am trying a SQL query MSSQL server 2005.

select  distinct emp_code , SSN, name
from dbo.employee
where 
    (City = 'Abc') 
    or
    (Country = 'India') 
and Joining_date between getdate()-60 and getdate()

which is returning 76 queries

But if instead I use

select  distinct emp_code
    from dbo.employee
    where 
        (City = 'Abc') 
        or
        (Country = 'India') 
    and Joining_date between getdate()-60 and getdate()

which is returning 73 records.

I understand that in first query Server is returning where all 3 columns are distinct. How should I write the query if I want only distinct emp_code ?

I have tried using group by emp_code but it is throwing an error Please help!

How can I retrieve second last row?

I have a table with many records and I want to know only the record which I have created at second last.

For ex: I have a table customer in which customerID are random numbers.

Now I want to select second last row.

customerID      customer_name   cont_no
---------------------------------------
 7              david sam       5284
 1              shinthol        1
11              lava            12548
 2              thomas          1
 3              peeter          1
 4              magge           1
 5              revas           1
 6              leela           123975

Output row :

customerID      customer_name   cont_no
5               revas           1

I don't want second highest...

I want second last row.

(Could not open a connection to SQL Server) Error when connecting to remote database from asp.net web application hosted on GoDaddy

I'm getting the following error, while trying to connect to a remote database (on other web hosting server) from my asp.net web app hosted on GoDaddy:

[Win32Exception (0x80004005): The network path was not found]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5347119

While working locally and running the asp.net through visual studio, connection to the remote database worked fine. But when I published the application to the GoDaddy server, I received the above error.

Connection String:

<add name="Connection2" connectionString="Server=103.21.58.192;Database=databaseName;Uid=user;Password=password;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>

SQL table limitation on update command

Is it possible to restrict more than [n] rows of some tables to get effected when running UPDATE command in SQL? Is it fine if instead of table I can put this limit to entire database?

Or any alternate way you can suggest?

Please help.

Thanks,

Variable not passed by reference | ms-sql and php

When I insert a row into my ms-sql server database, I have the following error:

Warning: Variable parameter 3 not passed by reference (prefaced with an &). Variable parameters passed to sqlsrv_prepare or sqlsrv_query should be passed by reference, not by value. For more information, see sqlsrv_prepare or sqlsrv_query in the API Reference section of the product documentation. in C:\...\ImmoToevoegen.php on line 6

The same warning for parameter 1 and 2.

This is my php code:

<?php
if (!empty($_POST['omschrijving']) && !empty($_POST['woningtype']) && !empty($_POST['data'])){
    $oms = $_POST['omschrijving'];
    $type = $_POST['woningtype'];
    $data = json_encode($_POST['data']);

    $prep = sqlsrv_prepare($conn, "insert into Woning(omschrijving, data, typeid) values (?, ?,  ?);", array($oms, $data, $type));
    sqlsrv_execute($prep);

    print "Woning is toegevoegd";
}
?>

<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="POST">
    <!--param 1 "omschrijving"-->
    Omschrijving:
    <textarea name="omschrijving" id="omschrijving" cols="30" rows="10></textarea>

    <!--param 2 "data"-->
    <div>
        wc: <input type="checkbox" name="data[]" value="wc"/><br/>
        cv: <input type="checkbox" name="data[]" value="cv"/><br/>
        boiler: <input type="checkbox" name="data[]" value="boiler"/><br/>
    </div>

    <!--param 3 "woningtype"-->
    <select name="woningtype" id="woningtype">
        <?php
        //code for load data from database
        print "<option value='" . $rij["ID"] . "'>" . $rij["naam"] . "</option>";
        ?>
    </select>
</form>

<?php
sqlsrv_close($conn);
?>

I use like I said php with a ms-sql server database.

What is wrong with my code?
Thanks

500 internal server error in asp.net website

I have two ASP.NET websites hosted on a server and connecting to the SQL database on on different server.

One of the website throwing 500 internal server errors (as custom error mode on in production). I am not sure what is causing these errors. And these errors are random, so I am not able replicate on dev environment. Both website having almost similar functionality but I am facing these errors only in one website. Recently there so many time out errors. So I asked the system admins to check the event log then they said lot of windows updates are pending, so they ran patch and rebooted both application and database servers.

After that I am getting 500 internal errors while going from login to default page in the website but I am sure there nothing wrong with code and these errors not caught in the application_error event in the global ascx file.

Any insights on how to troubleshoot this issue further?

Why I can't reference to WITH expression more than one time?

In MSSQL I can't reference to WITH expression more than one time?

DECLARE @total FLOAT;
WITH cte AS (
  SELECT s.plate, SUM(s.net) AS tonnage
    FROM scale s
    GROUP BY s.plate
)

SELECT @total = SUM(tonnage) / 100 FROM cte;
SELECT t.*, t.tonnage / @total AS percentage FROM cte t;

Table Indexing consideration for SaaS Project

Would be good to hear you guys out about how best to consider the indexing strategy, because the data in these tables may grow tremendously in the time to come. Decided to proceed by storing multi-tenant data in a single table approach. For an example, I have only couple of tables for this discussion.

CREATE TABLE [dbo].[TenantID](
    [TenantID] [smallint] IDENTITY(1,1) NOT NULL,
    [TenantName] [varchar](128) NOT NULL
) 
CREATE TABLE [dbo].[MenuType](
    [MenuTypeID] [int] IDENTITY(1,1) NOT NULL,
    [TenantID] [smallint] NOT NULL,
    [MenuTypeName] [varchar](128) NOT NULL
) 

  • MenuTypeName should be unique for each Tenant. Therefore, I will have a Unique Index on TenantID and MenuTypeName
  • TenantID should be referenced to Tenant table. So, Foreign Key on TenantID.
  • Am still thinking whether I should have Primary Key or just a Clustered Index on MenuTypeID which is an auto-increment column.
  • In future, when the table size grows I should be able to Partition out the data based on TenantID easily to a new database server.

Questions:

  1. Do I really need to define the Primary Key on MenuTypeID because we know SQL Server guarantees incremental seeds. Can I just define a Clustered Index on MenuTypeID.
  2. Define Unique Key on TenantID and MenuTypeName.

Using this approach, I will not have primary key concept in the table design. But, I would like to hear whether am I inviting trouble in future by not having primary key in the tables?

Optimizing LINQ routines

I run a build system. Datawise the simplified description would be that I have Configurations and each config has 0..n Builds. Now builds produce artifacts and some of these are stored on server. What I am doing is writing kind of a rule, that sums all the bytes produced per configuration builds and checks if these are too much.

The code for the routine at the moment is following:

private void CalculateExtendedDiskUsage(IEnumerable<Configuration> allConfigurations)
{
    var sw = new Stopwatch();
    sw.Start();
    // Lets take only confs that have been updated within last 7 days
    var items = allConfigurations.AsParallel().Where(x =>
        x.artifact_cleanup_type != null && x.build_cleanup_type != null &&
        x.updated_date > DateTime.UtcNow.AddDays(-7)
        ).ToList();

    using (var ctx = new LocalEntities())
    {
        Debug.WriteLine("Context: " + sw.Elapsed);
        var allBuilds = ctx.Builds;
        var ruleResult = new List<Notification>();
        foreach (var configuration in items)
        {
            // all builds for current configuration
            var configurationBuilds = allBuilds.Where(x => x.configuration_id == configuration.configuration_id)
                .OrderByDescending(z => z.build_date);
            Debug.WriteLine("Filter conf builds: " + sw.Elapsed);

            // Since I don't know which builds/artifacts have been cleaned up, calculate it manually
            if (configuration.build_cleanup_count != null)
            {
                var buildCleanupCount = "30"; // default
                if (configuration.build_cleanup_type.Equals("ReserveBuildsByDays"))
                {
                    var buildLastCleanupDate = DateTime.UtcNow.AddDays(-int.Parse(buildCleanupCount));
                    configurationBuilds = configurationBuilds.Where(x => x.build_date > buildLastCleanupDate)
                            .OrderByDescending(z => z.build_date);
                }
                if (configuration.build_cleanup_type.Equals("ReserveBuildsByCount"))
                {
                    var buildLastCleanupCount = int.Parse(buildCleanupCount);
                    configurationBuilds =
                        configurationBuilds.Take(buildLastCleanupCount).OrderByDescending(z => z.build_date);
                }
            }

            if (configuration.artifact_cleanup_count != null)
            {
                // skipped, similar to previous block
            }

            Debug.WriteLine("Done cleanup: " + sw.Elapsed);
            const int maxDiscAllocationPerConfiguration = 1000000000; // 1GB
            // Sum all disc usage per configuration
            var confDiscSizePerConfiguration = configurationBuilds
                .GroupBy(c => new {c.configuration_id})
                .Where(c => (c.Sum(z => z.artifact_dir_size) > maxDiscAllocationPerConfiguration))
                .Select(groupedBuilds =>
                    new
                    {
                        configurationId = groupedBuilds.FirstOrDefault().configuration_id,
                        configurationPath = groupedBuilds.FirstOrDefault().configuration_path,
                        Total = groupedBuilds.Sum(c => c.artifact_dir_size),
                        Average = groupedBuilds.Average(c => c.artifact_dir_size)
                    }).ToList();
            Debug.WriteLine("Done db query: " + sw.Elapsed);

            ruleResult.AddRange(confDiscSizePerConfiguration.Select(iter => new Notification
            {
                ConfigurationId = iter.configurationId,
                CreatedDate = DateTime.UtcNow,
                RuleType = (int) RulesEnum.TooMuchDisc,
                ConfigrationPath = iter.configurationPath
            }));
            Debug.WriteLine("Finished loop: " + sw.Elapsed);
        }
        // find owners and insert...
    }
}

This does exactly what I want, but I am thinking if I could make it any faster. Currenly I see:

Context: 00:00:00.0609067
// first round
Filter conf builds: 00:00:00.0636291
Done cleanup: 00:00:00.0644505
Done db query: 00:00:00.3050122
Finished loop: 00:00:00.3062711
// avg round
Filter conf builds: 00:00:00.0001707
Done cleanup: 00:00:00.0006343
Done db query: 00:00:00.0760567
Finished loop: 00:00:00.0773370

The SQL generated by .ToList() looks very messy. (Everything that is used in WHERE is covered with an index in DB)

I am testing with 200 configurations, so this adds up to 00:00:18.6326722. I have a total of ~8k items that need to get processed daily (so the whole routine takes more than 10 minutes to complete).

I have been randomly googling around this internet and it seems to me that Entitiy Framework is not very good with parallel processing. Knowing that I still decided to give this async/await approch a try (First time a tried it, so sorry for any nonsense).

Basically if I move all the processing out of scope like:

        foreach (var configuration in items)
        {

            var confDiscSizePerConfiguration = await GetData(configuration, allBuilds);

            ruleResult.AddRange(confDiscSizePerConfiguration.Select(iter => new Notification
            {
               ... skiped
        } 

And:

private async Task<List<Tmp>> GetData(Configuration configuration, IQueryable<Build> allBuilds)
        {
                var configurationBuilds = allBuilds.Where(x => x.configuration_id == configuration.configuration_id)
                    .OrderByDescending(z => z.build_date);
                //..skipped
                var confDiscSizePerConfiguration = configurationBuilds
                    .GroupBy(c => new {c.configuration_id})
                    .Where(c => (c.Sum(z => z.artifact_dir_size) > maxDiscAllocationPerConfiguration))
                    .Select(groupedBuilds =>
                        new Tmp
                        {
                            ConfigurationId = groupedBuilds.FirstOrDefault().configuration_id,
                            ConfigurationPath = groupedBuilds.FirstOrDefault().configuration_path,
                            Total = groupedBuilds.Sum(c => c.artifact_dir_size),
                            Average = groupedBuilds.Average(c => c.artifact_dir_size)
                        }).ToListAsync();
            return await confDiscSizePerConfiguration;
    }

This, for some reason, drops the execution time for 200 items from 18 -> 13 sec. Anyway, from what I understand, since I am awaiting each .ToListAsync(), it is still processed in sequence, is that correct?

So the "can't process in parallel" claim starts coming out when I replace the foreach (var configuration in items) with Parallel.ForEach(items, async configuration =>. Doing this change results in:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

It was a bit confusing to me at first as I await practically in every place where the compiler allows it, but possibly the data gets seeded to fast.

I tried to overcome this by being less greedy and added the new ParallelOptions {MaxDegreeOfParallelism = 4} to that parallel loop, peasant assumption was that default connection pool size is 100, all I want to use is 4, should be plenty. But it still fails.

I have also tried to create new DbContexts inside the GetData method, but it still fails. If I remember correctly (can't test now), I got

Underlying connection failed to open

What possibilities there are to make this routine go faster?