mercredi 6 mai 2015

Pass the triggered element to the bootbox callback jquery

I want to pass the 'a.delete' triggered element to my bootbox callback, is there a way to do that?

var confirm = false;
$('body').on('click', 'a.delete', function(e) {
    if( confirm == false){ e.preventDefault(); }
    bootbox.confirm("Confirm?", function(result) {
        if(result == true){
            confirm = true;
            $(this).trigger('click');
        }
    });
});

EDIT Well, Taplar I did what you said, but isn't triggering the action, even if the "trigger click" is working...

var confirm = false;
$('body').on('click', 'a.delete', function(e) {
    var element = $(this);
    if( confirm == false){
        e.preventDefault();
        bootbox.confirm("Confirm?", function(result) {
            if(result == true){
                confirm = true;
                console.log(confirm);
                element.trigger('click');
            }
        });
    } else {
        console.log('triggered again');
    }
});

EXIT: What I get after clicking the confirm button

true

triggered again

My Solution

var confirm = false;
$('body').on('click', 'a.delete', function(e) {
    var element = $(this);
    if( confirm == false){
        e.preventDefault();
        bootbox.confirm("Confirm?", function(result) {
            if(result == true){
                confirm = true;
                $(element)[0].click();
            }
        });
    } else {confirm = false;}
});

JQuery validation message appearing weirdly between two radio buttons

I am using JQuery Validation plugin to validate my form. The validation messages for all the fields except radio button are showing properly below the respective field.But for radio button the messages are showing between first two radio buttons.

gender : {
    required : true
    }


<html:radio property="gender" value="1"
        name="formBean" styleId="gender">&nbsp;Male&nbsp;</html:radio>
    <html:radio property="gender" value="0"
        name="formBean" styleId="gender">&nbsp;Female&nbsp;</html:radio>

enter image description here

Is there any way the error message shown after or below the radio buttons?

Thanks in advance.

Why Can't I get my google maps to update lat/lng on button click?

I am trying to get my center location to change on my google map based on a button click. I have more functionality to add later, but I can't get this basic update to work. I have a default value that loads on page load. The button should set a new location, but I see that it does update but then is quickly overridden by the default value because the page loads again.

I am new to google maps, and I am just trying to figure out how to load and interact with the map correctly.

Here is my code:

         <script src="http://ift.tt/13qgtmt"></script>                                                        
<script>

    var deanLat = 43.0843816;
    var deanLong = -89.5302394;
    var deanAddress = '1277 deming way, madison wi';

    var stmaryLat = 43.0592730;
    var stmaryLong = -89.4015130;
    var stmaryAddress = '700 S Park St, Madison, WI 53715';

    $("#FindDean").click(function() {
       refreshMap(deanLat, deanLong);
       });

    function alertme(message) {
          alert (message);
      }


    function refreshMap(ilat,ilong) {
       ilat = typeof ilat !== 'undefined' ? ilat : stmaryLat;
       ilong = typeof ilong !== 'undefined' ? ilong : stmaryLong;
        alertme(ilat);
        var mapOptions = {  
                zoom: 16,
                center: new google.maps.LatLng(ilat, ilong)
            };

        gmap = new google.maps.Map(document.getElementById('mapholder'),
          mapOptions);
    }


    function loadScript() {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'http://ift.tt/1lrRXYd' +
          '&signed_in=true&callback=refreshMap';
      document.body.appendChild(script);
    }
   window.onload = loadScript;

Submitting Values From a Jquery Slider

Hey guys I have this code here for a jquery slider. I want to take the value of the slider out and use an http post method to submit the value to a database. I have a processing form which I used successfully for textboxes and radio buttons. I was hoping to save the value of the slider in a hidden field and just post it. I know this gets the value from the slider.

    var selection = $( ".selector" ).slider( "value" );

Now how can I add this into the value in this submit form?

    <input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value=selection>

This is my whole code.

    <<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Slider - Slider bound to select</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="style.css">
  <script>
  $(function() {
    var select = $( "#minbeds" );
    var slider = $( "<div id='slider'></div>" ).insertAfter( select ).slider({
      min: 1,
      max: 10,
      range: "min",
      value: select[ 0 ].selectedIndex + 1,
      slide: function( event, ui ) {
        select[ 0 ].selectedIndex = ui.value - 1;
      }
    });
    $( "#minbeds" ).change(function() {
      slider.slider( "value", this.selectedIndex + 1 );
    });
  });
  var selection = $( ".selector" ).slider( "value" );
  </script>
</head>
<body>

<form id="mainForm_1" class="MainForm" method=post enctype=multipart/form-data action=processorss.php onSubmit="return validatePage1();">



  <label for="minbeds" class="mainForm">Rate Your Prefence for Fish 1-10</label>
 <select name="minbeds" id="minbeds">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
  </select>
  <li class="mainForm">



  <input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value=selection>

                    <input id="saveForm" class="mainForm" type="submit" value="Submit" />
                </li>
</form>


</body>
</html>

FullCalendar Horizontal Time Range Selection

Can someone tell me how to achieve something like below image. How can I select particular time range in selected days.

Notice that the selection spans multiple days. It's a horizontal selection across multiple days (as opposed to a continuous one).

I am using fullCalendar jquery library.

intended result

jQuery - Ask for width or height in percent % and returns me in 0 pixels

I've set styles in % like:

<style>
#somediv {width:70%}
</style>
<div id="#somediv"></div>

And it returns me the result in pixels with jQuerys css() function

$(document).ready(function(){
var css = $("#somediv").css('width');
console.log(css);
})

Argument is null in call to .NET Web API GET method

I have two similar Web API controllers, one working and one not. Can't find why the broken one is not working. What happens is all the fields of the input argument are null. Here's the controller method signature:

public IEnumerable<Product> GetProducts([FromUri] StateQuery query)

Parameter type:

public class StateQuery
{
    public State state;
    public string username;
    public string password;
}

Routing:

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/{action}"
);

Calling the endpoint:

var uri = 'api/product/';
var query = {
                username: $("#user").val(),
                password: $("#password").val(),
                state: { "name": $("#state").val(), "Counties": [{ "Name": $("#county").val() }] }
            };


$.getJSON(uri + 'getProducts', query)
              .done(function (data) {
                  $('#product').text(data);
                  console.log(data);
              })
              .fail(function (jqXHR, textStatus, err) {
                  $('#product').text('Error: ' + err);
              });

I've tried attribute routing, tried calling from the browser address bar, tried simplifying the input to just username and password, no change. All the fields of query are always null. I also tried changing it to return a IHttpActionResult, which is the main difference between this and the working controller (other than what it does of course) but that had no effect. The method is getting called, so the routing is working, but there is something wrong with the argument binding that I'm just not seeing.

Does anybody see the problem or just a direction to look? I've spent all morning reading tutorials and SO questions and everything I'm seeing indicates that I'm on the right track. Maybe there's some little thing I'm missing because I've been staring at it too long.

jQuery Ajax POST request being sent as GET with Laravel

I'm having a little trouble with Ajax. My project is in Laravel 5 and it's running on Apache and rewrite is enabled and the VerifyCsrfToken middleware is in place. I'm trying to send a POST request to another route inside my project. Here's what my Ajax looks like:

$.ajax({
    url: '/add-device/',
    type: 'POST',
    data: form_data,
    success: function(data)
    {
        console.log(data);
    },
        error: function(data)
    {
        console.log(data);
    }
});

When I click the button that triggers this Ajax, I get a 405: MethodNotAllowed response. So I went into routes.php and I added a GET route. I've also included my POST route:

Route::get('add-device', function()
{
    return 'hello';
});

Route::post('add-device', [
    'middleware' => 'auth',
    'uses' => 'FormController@add_device'
]);

I get the 'hello' message, so this is being sent as GET instead of POST. I tried to use $.post instead of $.ajax to force the POST but I still get the same behavior. For good measure, here is my .htaccess file:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

I also tried the Ajax without the trailing slash because of the rewrite rule (/add-device) but I get the same 'hello' message.

I tested all of my Ajax requests (half GET, half POST) during development and they worked fine while being served with artisan. I've only had this problem come up after switching to Apache. I've moved into the QA phase of my project and so I moved the project onto our development server, which is running Apache 2.4.10 on Debian 8.

Anyone have any ideas on what is going on and how to resolve it?

Pan zoom with bxSlider not zooming in centralized

I have used Panzoom jquery with bxSlider. The problem is this while zooming with scroll it doesn't zoom on center. Zoom goes either left side or right Because of slider otherwise it works proper.

find fiddle demo here.

<div class="slider">    
        <ul class="bxSlider">
            <li>
                <section class="focal">
                    <div class="parent">
                        <div class="panzoom">
                            <img src="http://ift.tt/1zN00c6" width="1000" height="450" />
                        </div>
                    </div>
                    <div class="buttons">
                        <button class="zoom-in">Zoom In</button>
                        <button class="zoom-out">Zoom Out</button>
                        <input type="range" class="zoom-range" />
                        <button class="reset">Reset</button>
                    </div>
                </section>
            </li>
            <li>
                <section class="focal">
                    <div class="parent">
                        <div class="panzoom">
                            <img src="http://ift.tt/1Jrnof0" width="1000" height="450" />
                        </div>
                    </div>
                    <div class="buttons">
                        <button class="zoom-in">Zoom In</button>
                        <button class="zoom-out">Zoom Out</button>
                        <input type="range" class="zoom-range" />
                        <button class="reset">Reset</button>
                    </div>
                </section>
            </li>
            <li>
                <section class="focal">
                    <div class="parent">
                        <div class="panzoom">
                            <img src="http://ift.tt/1zMZYRg" width="1000" height="450" />
                        </div>
                    </div>
                    <div class="buttons">
                        <button class="zoom-in">Zoom In</button>
                        <button class="zoom-out">Zoom Out</button>
                        <input type="range" class="zoom-range" />
                        <button class="reset">Reset</button>
                    </div>
                </section>
            </li>
        </ul>
</div>

js

 (function() {
    var $section = $('.focal');
    var $panzoom = $section.find('.panzoom').panzoom({
        $zoomIn: $section.find(".zoom-in"),
        $zoomOut: $section.find(".zoom-out"),
        $zoomRange: $section.find(".zoom-range"),
        $reset: $section.find(".reset"),
        $set: $section.find('.parent > div')
    });
    $panzoom.parent().on('mousewheel.focal', function( e ) {
      e.preventDefault();
      var delta = e.delta || e.originalEvent.wheelDelta;
      var zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;
      $panzoom.panzoom('zoom', zoomOut, {
        increment: 0.1,
        animate: false,
        focal: e
      });
    });

  })();

  $('.bxSlider').bxSlider({
        auto:true,
        autoHover: true,
        speed:1800,
        controls: true,
        pager: false,
        pause: 10000
    });

Product share virtual store for Facebook

I'm having trouble to make the share of a product from a virtual store for facebook. I'm putting the meta tags on the product page:

<meta property='og:title'...
<meta property='og:url' ...
<meta property='og:site_name' ...
<meta property='og:type' content='website'/>
<meta property='og:image' ...    
<meta property='og:description' ...

And the script I use to open the share window is as follows:

$("#btn_facebook").bind('click', function (event) {
      var twtTitle = document.title;
      var twtUrl = location.href;
      var imagem = 'http://ift.tt/1f2izrE' + $("#Share_Image").val();
      var twtLink = 'http://ift.tt/ML4eCW' + twtUrl;
      window.open(twtLink,'', '_blank', 'location=no, menubar=no, resizable=yes, width=575, height=520, fullscreen=yes, status=no, titlebar=no, toolbar=no');                                    
});

To open the share window properly with the photo and description of the product, but when I click share, in posting on facebook, go all descriptions and text, But the image does not load and does not appear.

It appears only a whiteboard without the photo that appeared before.

Can anyone help me identify this problem or have any solutions?

Thanks, Alex

Why is trigger('click') the same as $('#test').trigger({ type : 'click' });?

I am new to JS and basically I am trying to delve more into JS events and understand events and objects better. I came across a small difficulty that I would like to ask you kind people.

I wanted to know weather trigger('click') is the same as trigger({type : 'click'})

Now I wrote the below function to understand the difference and confirm if they are both the same:

<script>
    $(document).ready(function(){

        var call_it = function() {          
            setTimeout(function() {
                $('#test').trigger({
                    type : 'click' 
                });
            } , 1500 );
        }

        call_it();

        $('#test').on('click' , function(){
                console.log('button clicked');
        });
    });
</script>

Fiddle HERE

now when you replace :

$('#test').trigger({
        type : 'click' 
    });

with:

$('#test').trigger('click' );

the click is still triggered, but I am still confused, HOW and WHY are they the same ?? HOW are they internally the same?

I know its a trick question , but I hope somebody can answer it.

Thank you.

Tenali.

DOM element not displaying when position:absolute

I'm using jQuery Mobile 1.4.5. I have an element that is not displaying, under the following conditions: 1. Its CSS position is "absolute" 2. It is in the DOM under a JQM "grid":

<div class="ui-grid-a">
  <div class="ui-block-a">
    <div class="tt_autocomplete_wrap">
       <ul class="jqm_autocomplete ui-listview ...bla >
          <li class="ui-first-child" >
            <a class="ui-btn ui-btn-icon-right ui-icon-carat-r" href="#">Not Seen If Absolute</a>

See the details here: http://ift.tt/1JrmrDj

If the CSS position of the .jqm_autocomplete element is set to "absolute", the first element in the demo does not display. I've left it displaying in the fiddle, but uncommenting the line shows the problem:

.jqm_autocomplete {
  /* uncomment the next line to see the problem */
  /*    position: absolute; */

However: it is positioned correctly - it can be seen using the developer tools in outline form, exactly where it should be. And its z-axis position is also in front of everything.

I can't see any difference in the computed styles of the working and non-working elements, but am I missing something?

Highcharts stacked bar chart comes empty

I'm trying to put a chart similar to this one here: http://ift.tt/1HM2ZAB

When the page loads, the chart comes empty. I tried the solution here:
http://ift.tt/1zN00bX
by adding the code part to plotOptions:

column: {
    borderWidth: 0
}

I also tried:

barChart = new Highcharts.Chart(barOptions);
barChart.series[0].hide();
barChart.series[0].show();

None of these solved it. I set chart type to column, everything is ok, then I change it to bar and it stops working. Any workarounds?

Prevent Moving to Next Tab If Input Field Is Empty

I have a page with multiple tabs and input fields within the tabs. When a user clicks the continue button and the input field is blank I want to prevent them from moving to the next tab. I have tried preventDefault(); and return false; and neither seemed to be working for me.

Here is my code, any help with what I am doing wrong is appreciated!

$('.btn-next').click(function (event) {
        var businessNameInput = $.trim($('#businessName').val());

        if (businessNameInput === '') {
            event.preventDefault();
            console.log('Oops, looks like something is missing!');
        } else {
            console.log("Yay, we're good to go!");
        }
    });

The console logs work for each option (input blank or not) but it still moves to the next tab.

I am using Fuel UX Wizard for the tabs and Next and previous button. I took a look at their code and pulled this out, I think it is their next button function...

var Wizard = function( element, options ) {
            var kids;

            this.$element = $( element );
            this.options = $.extend( {}, $.fn.wizard.defaults, options );
            this.options.disablePreviousStep = ( this.$element.attr( 'data-restrict' ) === "previous" ) ? true : this.options.disablePreviousStep;
            this.currentStep = this.options.selectedItem.step;
            this.numSteps = this.$element.find( '.steps li' ).length;
            this.$prevBtn = this.$element.find( 'button.btn-prev' );
            this.$nextBtn = this.$element.find( 'button.btn-next' );

            kids = this.$nextBtn.children().detach();
            this.nextText = $.trim( this.$nextBtn.text() );
            this.$nextBtn.append( kids );

            // handle events
            this.$prevBtn.on( 'click.fu.wizard', $.proxy( this.previous, this ) );
            this.$nextBtn.on( 'click.fu.wizard', $.proxy( this.next, this ) );
            this.$element.on( 'click.fu.wizard', 'li.complete', $.proxy( this.stepclicked, this ) );

            this.selectedItem( this.options.selectedItem );

            if ( this.options.disablePreviousStep ) {
                this.$prevBtn.attr( 'disabled', true );
                this.$element.find( '.steps' ).addClass( 'previous-disabled' );
            }
        };

Traversing HTML DOM Elements in foreach loop

I have this segment of code here

<table>
    <thead>
        <th>Title One</th>
        <th>Title Two</th>
        <th>Title Three</th>
    </thead>
    <tbody>
        <?php foreach ($foos as $foo): ?>
            <tr>
                <td id="x"><?php echo $foo->bar1; ?></td>
                <td id="y"><?php echo $foo->bar2; ?></td>
                <td id="z"><?php echo $foo->bar3; ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<script type="text/javascript">
    $('#x').on('click', function(){
        console.log($(this).html());
    });
</script>

Suppose I have 10 rows of data there, how will I be able to reference the exact element I have clicked? For example row number 5, how will jQuery know that I have clicked row 5? I can't go writing <td id="x1">,<td id="x2">,<td id="x3">,<td id="x4"> because I can be having a thousand records.

Any help will be appreciated.

jQuery on scroll listener after click event

What is the proper way to activate an on scroll listener after a click event?

I'm currently using:

$('.button').click(function (event) {
   $(window).on("scroll", someFunction);
}

someFunction = function() {
   //do stuff 
   $(window).off("scroll"); //disable scroll listener
}

On a click event I enable the scroll listener which runs someFunction. The function does stuff and disables the scroll listener when finished. The scroll listener is enabled again on click.

My concern is that I'm not doing it right. Please advise!

Note: The scroll listener cannot run indefinitely. It starts on click and must finish at the end of myFunction.

Note: I'm not trying to detect when user stops scrolling..

Google Chrome is stupid to understand an easy code

I have a textarea with id="myarea" and a div with id="preview"

I want: if I type like: [B][U][I]Hello World![/B][/U][/I] in textarea and click button, it will automatic convert to: <b><u><i>Hello World!</b></u></i>

This code will work correctly:

function PreView()
{
  var temp = document.getElementById("myarea");
  temp.value = temp.value.replace("[B]", "<b>").replace("[/B]", "</b>");
  temp.value = temp.value.replace("[U]", "<u>").replace("[/U]", "</u>");
  temp.value = temp.value.replace("[I]", "<i>").replace("[/I]", "</i>");
  $("#preview").html(temp.value);
}

But when I try this, it doesn't work:

function PreView()
{
  var temp = document.getElementById("myarea").value;
  temp = temp.replace("[B]", "<b>").replace("[/B]", "</b>");
  temp = temp.replace("[U]", "<u>").replace("[/U]", "</u>");
  temp = temp.replace("[I]", "<i>").replace("[/I]", "</i>");
  $("#preview").html(temp);
}

I think that Google Chrome is stupid enough to make my code error.

But, if I wrong. Can you tell me why?

Thanks!

Add and delete records with ember.js

I am using emberjs for mvc in client side, I'm facing a problem when I would like to delete a record et create another with the same Id of the deleted one.

It shows me this error

Uncaught Error: Assertion Failed: Error: Assertion Failed: The id 2 has already been used with another record of type Client.Componant.

I tried destroyRecord() and store.unloadRecord(...) but it seems like the store still have the record which supposed deleted in his cache or some thing like that.

Any HELP please !! Thanks

IndexedDb: Autocomplete data extraction.

I am using an web application and the application has an autocomplete feature. I am sure the data for autocomplete is cached as the autocomplete works even when I am not connected to internet. I checked the "Resources" tab in developer tools and I see some of the cached data there. The thing is when I try to print the data I am only able to print part of the data.

When i check the path where indexedDB stores the cached data there are multiple Idb files and I have a feeling only one of them is getting printed when I try to print the data. Files in the path

Please advice on the same.

Best

Ankit Solanki

Symfony2 updating the values and displaying them without refresh with ajax

first of all I want to say that im not an expert in front-end, and this is my first time digging in to ajax. So this is what I want to do:

I want to change and show the updated value without the full pages refresh.. The only thing I want to update is the input field with its values and thats it. How can I update only that portion of the code?

This is my twig(when i press the + button i increase the quantity of the product and i want the twig to update it without refreshing the whole page. Like in any standard shopping cart):

{% for key, item in cart %}

                {% if key == info.id %}

                    <div class="input-append">

                    <input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
                    <a href="javascript:void(0)" class="remove btn"><i class="icon-minus"></i></a>
                    <a href="javascript:void(0)" class="add btn"><i class="icon-plus"></i></a>

                    {% endif %}

                    {% endfor %}

And this is the script:

$(document).ready(function () {
    $(document).on('click', '.add', function (e) {
    $this = $(this);   
    $.ajax({
        type: 'POST',
        url: 'add/quantity',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {      
          if(data.success == false){
           alert('error')
          }else{
            document.location.reload(true);
           }
        }
    });
});   
});

currently I only have the document.location.reload(true); which reloads the full page, how can I change that code?

adding and remove classes on click events

I am working on a click event, which intially is pretty standard.

on.click: Remove the active class from all list items, then add active to the clicked list item.

ie

var li = $('.child-item');
li.click(function(){
  li.removeClass('active');
  li.addClass('active');
});  

Works as expected. However, I also need a condition that if the active class is clicked again, it will remove the active class from the clicked item.

I tried this:

$('.child-item').toggle(function(e){

   $('.child-item').removeClass('active');
   var filterValue = $(this).attr('data-filter');
   $(this).addClass('active');

}, function() {
   $('.child-item').removeClass('active');
   $(this).removeClass('active');           
});    

but often the toggle is in the off state, so it requires a double click to get the toggle back on track. This seems like it would be a pretty straightforward solution, but I cannot seem to get it to work.

Added a jsFiddle here with another option. This is fine for when the same element is clicked, but it doesn't clear all active classes on each click.

jQuery tablesorter - IE8 issue with adding style to table row

Using jQuery tablesorter to sort and give style to each odd row in the table.

Issue: IE8 ignores the table row background or wouldn't apply the style for odd rows. Any idea how to make this work for IE < 9?

Here is the http://ift.tt/1Jrlqv7 - this works fine in all browsers except IE < 10

Thanks!

JSP:

<html>
<head>
<style type="text/css">
.tablesorter tbody tr:nth-child(odd) {
    background-color: #faf4e2;
}
</style>

<script type="text/javascript" src="http://ift.tt/1Jna9vQ"></script>
<script type="text/javascript" src="http://ift.tt/1OYEx6u"></script>
<script type="text/javascript">
    $(document).ready(function() {          
            $("#myTable").tablesorter();            
        } 
    ); 
</script>
</head>

<body>
<table id="myTable" class="tablesorter"> 
<thead> 
<tr> 
    <th>Last Name</th> 
    <th>First Name</th> 
    <th>Email</th>     
</tr> 
</thead> 
<tbody> 
<tr> 
    <td>Saul</td> 
    <td>Tarsus</td> 
    <td>st@mail.com</td> 
   </tr> 
<tr> 
    <td>Paul</td> 
    <td>Rock</td> 
    <td>pr@mail.com</td>     
</tr> 
</tbody> 
</table> 
</body>
</html>

Can't return the response data using jQuery AJAX [duplicate]

This question already has an answer here:

I'm loading cross domain html page with jQuery AJAX.

My problem is to return or equal the response data (target's html code) .

var html = "";

get("http://google.com");

function get( url ){

    $.ajaxPrefilter( function (options) {
        if (options.crossDomain && jQuery.support.cors) {
            var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
            options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
        }
    });

    $.get(url,function (response) {

         // Here is the problem

     });    
}

In the $.get() method I tried to :

html = result ;

return result ;

Both tries didn't work.

Is there any similar way to 'export' the response data to a global scope var ?

P.S - I've tried to use a function with a parameter to return the response . It worked perfectly but that is not what I want at all.

Side effects from Chartjs for only *some* clients

I was working on a couple of Chart.js charts and have found some strange behavior.

In this fiddle: http://ift.tt/1GXDooM people have been getting a variety of side effects when pressing the buttons "Day", "Week", or "Month".

What it should do: Simply refresh the chart with potentially new information displayed(the pie and doughnut actually don't have anything new)

What it should not do: As a side effect for some, it is growing the size of the <canvas> on each click. It does it for me. But it doesn't do it for a lot of other people accessing this fiddle. Here is a screen shot:

enter image description here

Why is it doing this for some people and not others? How can I remedy this problem? If you are curious, I initially asked a question about something else about these charts, but this could be somewhat related.

Any clue what could be causing this in my browser and other browsers/computers?

How to pass 3 parameters to the controller

This my controller,which takes date:

public ActionResult ViewLevel(string datepicker)
        {
            @ViewBag.DatePicker = datepicker;
            return View();
        }

I have View:

@model Car

@{
    var datepicker = Convert.ToString(ViewBag.DatePicker);
}
<div class = "Conteiner"
@foreach (Car car in Model)
        {
<p data-carnumber="@car.Number"> @car.Number<p>
<button class="buyCar">Buy</button>
}
</div>

<script type="text/javascript">
    $('.Conteiner').on("click", ".buyCar", function () {
        var number = $(this).data("carnumber");
        window.location.href = '@Html.Raw(Url.Action("Form", "Buy", new {datepicker,number}))';
    });
</script>

datepicker I need to pass too. Why not see number in new {datepicker,number} .number is red

How to implement jQuery inputmask to @Html.TextBoxFor()

I have an @Html.TextBoxFor(m => m.Expiration, new {@placeholder="MM/YY"}) that I'm trying to apply RobinHerbots jquery.inputmask (http://ift.tt/1yHWP3N) to so as the user types they would see something similar to

Starting: MM/YY

After First Character: 0M/YY

Second Character: 04/YY

and so on.

I've applied

$("#Expiration").inputmask({mask:"MM/YY",greedy:false});

However I get MM/YY in my text input without being able to click on it. Any assistance would be great.

Space and special characters problems on post

I got a problem with blank space and special characters during a POST action using this AJAX function:

function comments(id,postId,user_id) {
        var user_comments = encodeURIComponent($("#commentsId_"+id).val());
        if(user_comments!=''){
            var img = $("#img_"+id).val();
            var username = "<?php echo $this->session->userdata('username'); ?>"
            $.ajax({
                    type: "POST",
                    url: "<?php echo base_url() ?>social/userscomment/" +user_id+"/"+postId+"/"+user_comments,
                    data:{ user_comments : user_comments},
                    success: function(data) { 
                        $("#commentsId_"+id).val('');
                        var $sparkLines = $('.comments_body_'+id);
                        $("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+user_comments+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
                    }
            });
        }
    }

The PHP controller:

public function userscomment($comment_id,$post_id,$user_comments){

    $this->load->model('comments');

    $user_comments = utf8_decode(trim(mysql_real_escape_string($user_comments)));

    if(!empty($user_comments)){

        $data = array("user_id"         => $this->session->userdata('user_id'),
                      "comment_user_id" => $comment_id,
                      "comments"        => $user_comments,
                      "post_id"         => $post_id,
                      "username"        => $this->session->userdata('username')
                );
        $this->comments->insertComments($data);

        //logged user
       $userRow = $this->register->get_login($this->session->userdata('user_id'));
       redirect('social/userprofile/'.$userRow[0]['username']);
    }
}    

When an user post a comment like: "a b c d" the results showed in the view is: a%20b%20c%20d, if an user try to wrote a special characters like € i got this results %E2%82%AC

How can i prevent this problem?

Display uploaded images on button click

On click of button preview i need the uploaded images to be shown ,the scripts it's working fine for changing event but not for the click one.

HTML

 <form action="test.php" enctype="multipart/form-data" id="mainform" method="post" name="mainform">
Imagine 1:<br>
 <input type="file" name="img1" id="img1"><br>
     <br><br>     
Imagine 2 :<br>
 <input type="file" name="img2" id="img2"><br>
     <br>
 Imagine 3 :<br>
 <input type="file" name="img3" id="img3"><br> 
     <br>
 Imagine 4 :<br>
 <input type="file" name="img4" id="img4"><br>    
     <br>
 Imagine 5 :<br>
 <input type="file" name="img5" id="img5"><br>   
     <br>
 Imagine 6 :<br>
 <input type="file" name="img6" id="img6"><br>   
     <br>
 Imagine 7 :<br>
 <input type="file" name="img7" id="img7"><br>    
     <br>
 Imagine 8 :<br>
 <input type="file" name="img8" id="img8"><br>    
     <br>
 Imagine 9 :<br>
 <input type="file" name="img9" id="img9"><br>   
     <br>
 Imagine 10 :<br>
 <input type="file" name="img10" id="img10"><br>    
     <br>
 Imagine 11 :<br>
 <input type="file" name="img11" id="img11"><br> 
     <br>
 Imagine 12 :<br>
 <input type="file" name="img12" id="img12"><br>    
     <br>
 Imagine 13 :<br>
 <input type="file" name="img13" id="img13"><br>    
     <br>
 Imagine 14 :<br>
 <input type="file" name="img14" id="img14"><br>     
     <br>
 Imagine 15 :<br>
 <input type="file" name="img15" id="img15"><br>    
     <br />
     Preview:
     <br />
     <input type="checkbox" id="previz" />Preview
</form>
<div id="#previzdiv">
<img src="" id="preview-img1">
<img src="" id="preview-img2">
<img src="" id="preview-img3">
<img src="" id="preview-img9">
<img src="" id="preview-img5">
</div>

Jquery:

$("#center2 #forme #previz").change(function(){
if(this.checked){
for(i=1;i<15;i++){
j = $("form#mainform #img"+i);
console.log(j);
readURL(j);
}
}

});
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                imgId = '#preview-'+$(input).attr('id');
                $(imgId).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
      }


      $("form#mainform input[type='file']").change(function(){
        readURL(this);
        console.log(this);
      });

The console log from "j" should look like <input type="file" name="img1" id="img1"> yet it different from what change event is console logging.Is the approach correct? JSFIDDLE:http://ift.tt/1JrktCS

Limiting the jQuery search scope correctly?

I've stumbled up this code and I'm wondering if its just limiting the scope or selecting both of the elements at the same time.

container = jQuery("#test", parent.document);

jQuery("param[name=scale]", another.object)

Can anyone shed some light on this?

jQuery Flip front to 2 different backsides

I am having trouble getting a certain feature to work.

As you can see here: http://ift.tt/1F5JkhP

<div> CHECK CODE AT JSFIDDLE</div>

I am using the flip jquery plugin which made a flip, where you choose a category, and then gets sent to a certain login screen. My issue is, that I want the bottom one to flip to another backside. I have tried altering the jquery plugin, but without luck. Is there anyone who knows how I could make this work?

So the pink one goes to the pink login, and the blue one goes to the blue login.

Thank you in advance!

Jquery Sortable retrieve hidden Id on change

i am using the jquery sortable arrange images in a certain order, all i want to do is on change get the hidden id of the image and the new current position number so i can run an ajax request to update the new position in my database, however when i change the image position the alert is not triggered(in below code) so i am wondering what i am doing wrong.

Jquery code

<script>
        $(function() {
            $("#sortable").sortable({
                stop: function(event, ui) {

                    $('input.imageHiddenImageId').each(function(idx) {

                        var imageId = (this).val();
                        alert("New position: " + ui.item.index() + "id:" + imageId);
                        //Run some AJAX code to server
                    });

                }
            });
            $( "#sortable" ).disableSelection();
        });
    </script>

HTML code

<ul id="sortable">
   <li class="ui-state-default">
      <img src="http://localhost/site/gallery/3.png" style="max-width: 100%; height: auto;">
      <input type="hidden" class="imageHiddenImageId" id="imageHiddenImageId" name="imageHiddenImageId" value="45">
      <input type="hidden" id="imageHiddenNo" name="imageHiddenNo" value="2">
    </li>
 </ul>

Thanks for the help

CSS Filter Blur: Prevent Undefined Image Edges on a Blurred Image during CSS Transition

Preventing an image from having undefined blurry edges can be achieved by adding negative margin, but during a CSS transition this fails. How can you keep the edges of an image defined during a CSS transition while adding or removing a filter blur class?

Check out my example: Codepen

HTML:

<link href='http://ift.tt/1etXiq2' rel='stylesheet' type='text/css'>
<link href='http://ift.tt/1H1oAIk' rel='stylesheet' type='text/css'>
<div class="container">
  <img class="blur" src="http://ift.tt/1c6fyfO"/>
</div>
<div class="col">
<h2 class="montserrat">Hover Over Image</h2>
<hr>
  <p class="hind">Preventing an image from having undefined blurry edges can be achieved by adding negative margin, but during a CSS transition this fails.  As you can see, on-hover, the edges of the image become undefined/blurred.  How can you keep the edges of an image defined during a CSS transition while applying or removing filter blur?<br><br>Hover over the image!</p>
</div>

CSS:

html,body{
  margin:0;
  text-align:center;
  background:#F8F8F8;
  height:100%;
}

h2{
  margin:1em 0;
  padding:0;
  line-height:1;
  color:#111;
}
p{
  margin:1em 0;
  padding:0;
  line-height:1;
  text-align:justify;
  color:#999;
}

.montserrat{
    font-family: 'Montserrat', sans-serif;
}
.hind{
    font-family: 'Hind', sans-serif;
}
hr { 
  width:100%;
  display: block; 
  height: 1px;
  border: 0; 
  border-top: 1px solid #222;
  margin: 1em 0; 
  padding: 0; 
  line-height:0;
}

.col{
  max-width:400px;
  display:inline-block;
  height:100%;
  float:left;
  background:#333;
  padding-left:20px;
  padding-right:20px;
}

.container{
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width:10%;
  display:inline-block;
  padding-top:10%;
  position:absolute;
  overflow:hidden !important;
  border-radius:50%;
  -webkit-filter: blur(0px); -moz-filter: blur(0px); -o-filter: blur(0px); -ms-filter: blur(0px); filter: blur(0px);/*prevents image from overflowing*/
}

.container img{
  position:absolute;
  min-width:calc(100% + 30px);
  height:calc(100% + 30px);
  left:-15px;
  right:-15px;
  top:-15px;
  bottom:-15px;
  -webkit-transition: .5s ease-in-out;
}

.blur{
        -webkit-filter: blur(5px); -moz-filter: blur(5px); -o-filter: blur(5px); -ms-filter: blur(5px); filter: blur(5px);
}

Just a smidge of jQuery:

$(document).ready(function(){
    $('img').hover(function(){
        $(this).toggleClass('blur');
    }); 
});

difference between window and document in jQuery

i wanna know whats the difference between document && window in jQuery ??

These two are used quite often, but i hv never got the difference between them.

jQuery Caching & traversing Objects

I'm trying to get my head around jQuery caching and how it improves performance and how it should be used?

As I understand it, when you use a jQuery selector you are searching the DOM and creating a jQuery object which you can traverse. Does that mean if you create a jQuery object of the html body tag you can avoid the need to traverse the DOM when creating new jQuery objects? Would there be any point to doing that?

Considering ...

var htmlBody = $('body');
$('header',htmlBody).css('background','green');
$('footer',htmlBody).css('background','yellow');

Would the above piece of code be cheaper/use less resources by creating new objects and traversing the DOM than...

$('header').css('background','green');
$('footer').css('background','yellow');

Escape/Special Characters from user input to HTML5 data-attributes using URL Encode/Decode

This is my first question on stackoverflow - needing help from all you experts. Our web app allows the user to input escape/special characters. We are doing some testing for extreme cases. I'm able to pass the escape characters through ajax/json.

var test = JSON.stringify({
  typeName: $("#typeName").val(),
  invoiceType: 'NewTypeArea'
});
$.ajax({
  type: "POST",
  url: "BackEnd/WebService.php",
  data: {
    newInvoice: test
  },
  dataType: 'json'
});
<script src="http://ift.tt/1g1yFpr"></script>

My backend developer does their thing with escape/special characters. When I make another call I get the following JSON data

[{"propName":"Special '\"'\\","typeName":"type'\"\\"}]

This data returned is correct. For simplicity - I have only one object for this example - I take this data and put it into a dropdown list.

$.each(data, function(i, val) {
var output = '<option class="type" id="' + this.qfInvoiceNum + '" value="' + this.typeName + '">' + this.typeName +'</option>';
$('select#typeList').append(output);

});

It displays all the escape/special characters correctly. For instance: "type'\"\" displays as type'\"\

The user then selects one of the list items. I've tried capturing the typeName numerous ways with data-attributes, value, etc. Here is one example:

$( '.selectChange1').change(function() {
typeGrab = $('select option.type:selected').val();
pullArea();
});

But this is where the problem comes in. If they select a list item with special/escape characters the value from the console returns

"type'"

not

"type'\"\\"

So of course when I pass in the var typeGrab for the JSON/AJAX call it is wrong.

Is there a good solution on on how to get escape/special characters from a dropdown? Or maybe I'm going wrong with $.each when I loop through the data? Or, quite possibly, I'm missing something very simple. Any help or insight would be great.

Thank you.

Additional Info. The first solution does work. However, I didn't use this initially due to the fact that there are a couple of times where the displayed text is not what I want to grab - which is why I was trying data*-attributes.

For example:

$.each(data, function(i, val) {
var output = '<option id="' + this.qfInvoiceNum + '" class="type" data-index="' + this.typeName + '" >' + this.typeName +' | #' + this.qfInvoiceNum +'</option>';
$('select#typeList').append(output);
}); 

If I want the value of this.typeName with escape/special characters the provided solution does not work. I can't use data-attributes or the html option value.

However, after much research, I found a great solution for this problem if you are looking to pass in values to data-attributes that have escape/special characters. Please my answer below.

Leaflet popup closing immediately after function fires to open popup dynamically

I have a feature that allows the user to look up a marker and zoom to its location, at which point I want the popup to open. Everything is working fine, except that the popup closes after the function fires. I can't figure out what's making the popup close. Here's my relevant code:

var geoJsonDataFeatures = {
"type": "FeatureCollection",
"features":[]
};

//create popup content
var htmlString = "<div>popup html goes here....</div>";
var popupContent = L.popup().setContent(htmlString);

//create geoJson object for each marker
var geoJsonData = {
"type": "Feature",
"id": siteNo, //a string saved as a variable 
"properties": {
    "popupContent": popupContent,
    "icon": icon //an L.icon object
    },
"geometry": {
    "type": "Point",
    "coordinates": [longitude, latitude] //strings saved as variables
    }
}

//push the geoJson feature into the features object
geoJsonDataFeatures.features.push(geoJsonData);

//create the map layer that holds the markers
var geoJsonDataLayer = L.geoJson(geoJsonDataFeatures, {
    onEachFeature: function (feature, layer) {
    layer.bindPopup(feature.properties.popupContent);
    layer.setIcon(feature.properties.icon);
    }
}).addTo(map);

....

//when the user has selected a site from a dropdown select menu,
//we pass the site number (siteNo) to a function to zoom and open the
//marker popup:

zoomOpenPopup(siteNo);

function zoomOpenPopup(siteNo){
var marker = {};
var popup = {};
var layerObj = {};

    if(map.hasLayer(geoJsonDataLayer))
    {
    layerObj = geoJsonDataLayer;
    }

    jQuery.each(layerObj._layers, function(k){

        if(siteNo == layerObj._layers[k].feature.id)
        {
        marker = layerObj._layers[k];
        popup = layerObj._layers[k].feature.properties.popupContent;
        }  
    });

marker.openPopup();
//popup._isOpen = true; //doesn't work
//popup.openOn(map); //doesn't work
//map.openPopup(popup); //doesn't work
 alert("done!"); 
}

When the alert fires, you can see the popup open on the map, but once it closes the popup disappears. I do have a function that updates the position of the popup anchor on open if the content is too wide, but I have the same issue even if I comment out that function and reload the page. Has anyone run into something similar?

pass specific element of array to ajax in joomla 3 module

I'm sure this is really simple but I have been trying to get this for ages. I have a foreach loop which iterates over an array of objects and displays them in an html table with a submit button which when clicked makes an ajax call to display some data in the same page.

This all works fine except it only passes the value of the last object from the array in the foreach loop instead of the value as displayed in that table row. I have tried to use a counter or to set and id for the but unsure how to get that specific value and pass it through.

Here is what is in my code:

<?php 
// No direct access
defined('_JEXEC') or die; ?>

<div class="status shelterbuddydog" >
<table class="profile_table">
   <?php foreach ($animalDetails as $profile):?>
    <tr>
        <td><?php echo $profile->photo;?></td>
        <td><span class="profile">Name:<?php echo $profile->name;?></span><br/>
            <span class="profile">Sex: <?php echo $profile->sex;?></span></<br/>
            <span class="profile">Age: <?php echo $profile->age;?></span><br/>
            <span class="profile">Breed: <?php echo $profile->breed;?></span><br/>
            <span class="profile">Animal Id: <?php echo$profile->animalId;?></span><br/>
            <span class="profile">Location: <?php echo $profile->shelter;?></span><br/>
            <?php $profile->summary;?>
            <input type="submit" id="summary" name="summary" value="VIEW MY PROFILE">
            </input></td>
    </tr>
    <?php endforeach;

</table>
<?php 
// Instantiate global document object

$doc = JFactory::getDocument();

$js = <<<JS

(function ($) {
 $(document).on('click', '#summary', function () {

    var profileSummary = {};
        profileSummary['photo'] = '$profile->photo';
        profileSummary['name'] =  "$profile->name";
        profileSummary['sex']  = "$profile->sex";
        profileSummary['age']  =  "$profile->age";
        profileSummary['breed']  = "$profile->breed";
        profileSummary['shelter']  = "$profile->shelter";
        profileSummary['animalId']  =  "$profile->animalId";
        profileSummary['summary'] =  "$profile->summary";

        request = {
                'option' : 'com_ajax',
                'module' : 'shelterbuddydog',
                'data'   : profileSummary,
                'format' : 'raw'
            };
    $.ajax({
        type   : 'GET',
        data   : request,
        success: function (response) {
            $('.status').html(response);
        }
    });
    return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);    
?>
</div>

Thanks for any help with this.

meteor template content fully loaded callback

I've a template like below

<template name="mainEvents">
    <section class="main-events-list events-list js-content-slider">
        {{#each events}}
            <div class="events-list-item">
                <figcaption>
                    <dl class="clearfix">
                        <dt>
                        <h3>{{name}}</h3></dt>
                    </dl>
                </figcaption>
                <figure class="ratioBox">
                    <div class="js-backstretch content"><img src="{{image}}"/></div>
                </figure>
                <a href="" class="full-link"></a>
            </div>
        {{/each}}
    </section>
</template>

a simple helper like below

Template.mainEvents.helpers({
   "events": function () {
       return Events.find({is_deleted:false})
   }
})

and lastly a simple iron-route like below:

Router.route('/slider', {
name: 'mainEn',
path: '/slider',
template: 'slider',
layoutTemplate: 'mainLayout',
yieldRegions: {
    'indexHeader': {to: 'header'},
    'footer': {to: 'footer'}
},
onBeforeAction: function () {
    //TAPi18n.setLanguage('en'); // set to english
    this.next();
},
action: function () {
    // render all templates and regions for this route
    this.render();
}
});

As you can guess i'm trying to generate a slider with the data came from the collection and trying to do it with Slick package.

Template.mainEvents.rendered .. function works well when roaming between routes. Suppose my slider is in /slider route and i load the meteor app by entering localhost:3000 and then click /slider button. everything works as it's should.

But when try to load the page with localhost:3000/slider route. rendered function triggers before the content fully loaded and slick fails. I manage to work it only by setTimeout function.

How can i get the all content in a template fully loaded and rendered callback in meteor ?

I need $('.selector').load(function () {}) like function.

or any other that can solve this issue.

Thanks in advance.

getting values from php dynamically created checkboxes with jquery

H Im trying to get the value of a check box to send in a ajax request to a php page, the checkboxes are dynamically created using php. So far my code allows me to show an instruction to the user telling the user to choose an admin to delete from the list dynamically created. Then when a checkbox is checked the instrcution hides and the delete admin button is shown. Next on clicking the delete button I'm trying to confirm the user wants to delete the admin chosen and click to confirm or cancel. The real problem I'having is getting the value of the chosen checked checkbox to pass to the php processing page, so far I have managed to get the value of the first checkbox to pass no matter which checkbox is checked

Jquery

<script type="text/javascript">

$(document).ready(function() {

    var checkboxes = $("input[type='checkbox']");

checkboxes.click(function() {
    $('.delete_admin_but').show();
    $('#adminDeleteNotice').hide();
    var deleteAdminName=$(this).attr('id');
});

    $(".delete_admin_but").click(function() {



//  if(confirm("Are you sure you want to delete the Admin")) {

    $("#deleteAdminError").html('<img src="image/ajax-loader.gif" width="16" height="16" alt=""/>');




$.post("includes/delete_admin.inc.php",{deleteAdminname:deleteAdminName},function(json)   {
    if(json.result === "success") {
        $("#deleteAdminError").html(json.message);
//  $('.add_intern').get(0).reset();
    }else{
        $("#deleteAdminError").html(json.message);
    }
});



});//submit click
});//doc ready
</script>

html form

<div id="deleteAdmin" style="display:none">

<form id="adminDelete">

          <div class="delete_admin_list">

            <?php while($row = mysqli_fetch_array($result1)) { ?>

              <input type="checkbox" id="<?php echo $row['name']; ?>" value="<?php echo $row['id']; ?>" name="delete[]" class="checkboxAdmin" />

              <div id="admin_db_detail"><?php echo $row['name']; ?> - <?php echo $row['email']; ?></div>

              <?php } ?>

      </div>        


<div id="adminDeleteNotice" style="display:block">Please Choose an Admin to Delete</div>

<input name="delete_admin_but" id="delete_admin_but" type="button" class="delete_admin_but" value="Delete Admin" style="display:none"/>

</form>

<div id="deleteAdminError"></div>

</div>

If anyone could help me figure this out I would be greatful

jQuery Attribute Equals Selector [name=”value”] issues passing a variable that ends with backslash

Humour me on this one.

In my code I am attempting to find all the divs that match a data-attribute value. Now this value is created by a user so the string could contain anything.

During my testing I ran into an error when the value contained a quote and ended with a backslash "\" (The javascript escape character).

Error: Syntax error, unrecognized expression: className[data-attributename="Mac"Mac\"]

Here is an example (please note in this example the double backslash escapes itself and the first backslash escapes the quote):

var value= "Mac\"Mac\\";
$('.className[data-attributename="'+value+'"]');

This error only occurs if the string contains a quote (") and has a backslash (\) at the end of the string. If there is a space after the backslash or if the backslash is in beginning or middle of the string there is no issue.

Is it possible to pass a variable that includes a quote or apostrophe ( " ' ) and ends with a backslash (\) into the jQuery Attribute Equals Selector?

One obvious solution would be just to prevent my users from using the backslash "\" character. If I do this is there any other characters that could be harmful using this jQuery selector?

Another solution would be:

var value= "Mac\"Mac\\";
$('.className').each(function(){
    if($(this).attr('data-attributename') === value){
      //perform action
    }
});

With this solution would it be less efficient because it would have to iterate through each element or does the Attribute Equals Selector essentially work the same way? If so, for safety should I always use this solution over the attribute equals selector?

Here is an example of the div I would be trying to select:

$('body').append("<div class='className' data-attributename='Mac\"Mac\\' ></div>")

Bootstrap button alignment small screen width

okay I'm styling some buttons for a mini survey site I am building and I am happy with how it looks on a desktop, but when i resize the browser window to a size that resembles a phone I cant get the buttons to just align under eachother. the desktop sized version has 2 rows, one with 3 buttons and one with 2 buttons.

full size desktop it looks ok : enter image description here

reduced width: enter image description here

my button code :

<div class="panel-body" style="padding-bottom:0px;">
    <div class="row"> 
        <div class="btn-group btn-group-justified mg0 pd0"role="group" aria-label="...">
        <div class="col-xs-6 col-sm-4 mg0 pd0">
        <button type="button" class="btn btn-default btn-lg btn-block" id="btnChoice1" value="<?php echo $aId[0];?>"><?php echo $aTitle[0];?></button>
        </div><div class="col-xs-6 col-sm-4 mg0 pd0">
        <button type="button" class="btn btn-default btn-lg btn-block" id="btnChoice2" value="<?php echo $aId[1];?>"><?php echo $aTitle[1];?></button>
        </div><div class="col-xs-6 col-sm-4 mg0 pd0">
        <button type="button" class="btn btn-default btn-lg btn-block" id="btnChoice3" value="<?php echo $aId[2];?>"><?php echo $aTitle[2];?></button>
        </div>
    </div>
    </div><div class="row">
      <div class="btn-group btn-group-justified mg0"role="group" aria-label="...">
          <div class="col-xs-6 mg0 pd0">
        <button type="button" class="btn btn-default btn-lg btn-block" id="btnChoice4" value="<?php echo $aId[3];?>"><?php echo $aTitle[3];?></button>
          </div><div class="col-xs-6 mg0 pd0">
         <button type="button" class="btn btn-default btn-lg btn-block" id="btnChoice5" value="<?php echo $aId[4];?>"><?php echo $aTitle[4];?></button>
          </div>
      </div>
    </div>
</div>

I am trying to get the buttons to align themselves one per one under eachother instead of 2 buttons then one then 2 again and text getting outside the buttons in the second picture...

any help?

thanks

Improving full ajax website

I would like to try to improve a script that I use to make my ajax site. But after several attempts, no results. I need some help! ^^

This script was found on GitHub, and the author left a simple demo page. The author uses history.js. HERE

Here's the problem: 1- The back button works normally, but do not work when you have to return to the "index.php".

2- I would change the name of the created pages, but I can not win without breaking the script.

3- Finally I would like to add a function to load the div and use jqueryscrollto to make a transition effect.

I originally wanted to use this script (http://ift.tt/1lrQjVG) but I have not managed to implement. Having no single demo page using this script.

Thank you in advance if you look at the problem.

(function(window, jQuery){

    if(!Modernizr.history){
        alert("No HTML5 pushState support!");
    }

    var directory = 'content/'; //directory of the content we want to ajax in
    var state = History.getState();

    //for when they click on an ajax link
    $('.ajaxify').on('click', function(e){
        var $this = $(this);
        var href = $this.attr('href'); // use the href value to determine what content to ajax in
        $.ajax({
            url: directory + href + '.html', // create the necessary path for our ajax request
            dataType: 'html',
            success: function(data) {
                $('p').css('display', 'block');
                $('#content').html(data); // place our ajaxed content into our content area
                History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
            }
        });
        e.preventDefault(); // we don't want the anchor tag to perform its native function
    });

    //for when they hit the back button
    $(window).on('statechange', function(){
        state = History.getState(); // find out what we previously ajaxed in
        $.ajax({
            url: directory + state.title + '.html', //create our path
            dataType: 'html',
            success: function(data) {
                $('#content').html(data);
            }
        });
    });

/********************************************************************/
/*******************************NOTE*********************************/
/********************************************************************/

// This is just an example to help demonstrate how to ajaxify a website
// Ideally this would be used in combination with a server side language to reduce the redundant html files at the root level
}(window, $));

JQuery autocomplete combobox line items breaking in IE (all versions) Not for trolls, this will take a looksie

 function BindUsers(){
            $.ajax({ url: '<%=Page.ResolveClientUrl("~/Chat_getCurrentTickets.aspx")%>',
                data: { fetch: "GetUserList"}, 
                async: false,
                type: 'GET',
                dataType: "json",
                success: onBindUserSuccess, 
                error: function(){(alert('Error getting list of recipients'))}});      
        }

        function onBindUserSuccess(data){           
            
            //opt.value = '-1';
            //opt.text = 'Enter an email';
            //$('#combobox').append(opt);
            //$('#combobox').selectedIndex = -1;

            for(var i=0;i< data.length;i++){
                var opt = document.createElement('option');
                if(data[i].OperatorName.trim() != ''){
                    opt.value = data[i].Email;
                    opt.text = data[i].OperatorName;
                    $('#combobox').append(opt);
                }
            }
        }

        (function( $ ) {
            $.widget( "custom.combobox", {
                _create: function() {
                    this.wrapper = $( "<span>" )
                      .addClass( "custom-combobox" )
                      .insertAfter( this.element );
 
                    this.element.hide();
                    this._createAutocomplete();
                    this._createShowAllButton();
                },
 
                _createAutocomplete: function() {
                    var selected = this.element.children( ":selected" ),
                      value = selected.val() ? selected.text() : "";
 
                    this.input = $( "<input>" )
                      .appendTo( this.wrapper )
                      .val( value )
                      .attr( "title", "" )
                      .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
                      .autocomplete({
                          delay: 0,
                          minLength: 0,
                          source: $.proxy( this, "_source" )
                      })
                      .tooltip({
                          tooltipClass: "ui-state-highlight"
                      });
 
                    this._on( this.input, {
                        autocompleteselect: function( event, ui ) {
                            ui.item.option.selected = true;
                            this._trigger( "select", event, {
                                item: ui.item.option
                            });
                        },
 
                        autocompletechange: "_removeIfInvalid"
                    });
                },
 
                _createShowAllButton: function() {
                    var input = this.input,
                      wasOpen = false;
 
                    $( "<a>" )
                      .attr( "tabIndex", -1 )
                      .attr( "title", "Show All Items" )
                      .tooltip()
                      .appendTo( this.wrapper )
                      .button({
                          icons: {
                              primary: "ui-icon-triangle-1-s"
                          },
                          text: false
                      })
                      .removeClass( "ui-corner-all" )
                      .addClass( "custom-combobox-toggle ui-corner-right" )
                      .mousedown(function() {
                          wasOpen = input.autocomplete( "widget" ).is( ":visible" );
                      })
                      .click(function() {
                          input.focus();
 
                          // Close if already visible
                          if ( wasOpen ) {
                              return;
                          }
 
                          // Pass empty string as value to search for, displaying all results
                          input.autocomplete( "search", "" );
                      });
                },
 
                _source: function( request, response ) {
                    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                    response( this.element.children( "option" ).map(function() {
                        var text = $( this ).text();
                        if ( this.value && ( !request.term || matcher.test(text) ) )
                            return {
                                label: text,
                                value: text,
                                option: this
                            };
                    }) );
                },
 
                
 
                _destroy: function() {
                    this.wrapper.remove();
                    this.element.show();
                }
            });
        })( jQuery );

        //$( ".combobox" ).autocomplete({
        //    appendTo: "#dialog"
        //});
 
        $(function() {
            $( "#combobox" ).combobox();
            $("#combobox").change(function() {
                alert($(this).val());  //To fetch the value                 
            });
            $( "#toggle" ).click(function() {
                $( "#combobox" ).toggle();
            });
        });
<div id="dialog" title="Help Desk Email" style="display:none;" class="ui-front">                  
                    <div style="width:100%;"> 
                        <div>
                            <div style="width:100%;display:inline-block">
                                <input type="button" id="btnSend" value="Send" onclick="btnSendClickEvent()" style="margin:25px 25px 5px 5px" />
                                <label title="Select a recipient" id="RadCBTo" style="height:25px;margin-right:36px">To: </label>                            
                                <select id="combobox" >
                                    <option value="" selected="selected">Insert or select and email address</option>
                                </select>            
                            </div>
                            <div>
                                <label id="label2" style="height:20px;width:300px; margin:25px 5px 5px 80px">Subject: </label>
                                <input type="text" id="txtSubject" style="height:20px;width:550px;" />
                                <input type="hidden" id="tbTo" />                            
                            </div>
                            <div>
                                <textarea id="tdBody" aria-multiline="true" style="margin:25px 5px 5px 138px; width:inherit;" cols="90" rows="25"></textarea> 
                                <label id="label1" style="background-color:red;"></label>  
                                <input type="hidden" id="resolve"/>                            
                            </div>               
                        </div>                                                  
                    </div>              
                </div>

This is what I get in chrome and not what I get in IE... That is the problem.enter image description here

This is what I get in IE, not what I want

I have an autocomplete combo-box inside a div which opens up into a dialog box. In IE the line items are crammed together and text is not a all visible. You can get the source code, such as I have, directly from JQuery and experience the error such as I have.

For an explanation of use (in case you think it is necessary): This is a pop-up holding a combobox for email addresses. I'm after the dialog loads I use BindUsers to retrieve the list and use the success to build. I've experienced another issue here where I would add a null or "Enter an email" value and when I append the rest of the options the element I previously added is overwritten.

Also the alert which should fire, never fires....

If this isn't enough, you might shoot some ducks and not down vote every post you don't understand. Not every question needs code, its pretty obvious you don't know what the problem is and I'm looking for a relatively quick response instead of wasting half an hour formulating a question so people who had no idea what I was experience could try and get few up-votes.

If element's descendent has class x, add class to element's sibling that has a descendent with class y

I want to check to see if an element has a descendent with a certain class X. If so, I want to check that element's siblings to see if they have a descendent with a class Y. If so, I would like to add class to that sibling with the descendent with a class Y.
HTML:

<div class="x">
    <div>
        <p class="y">Y</p>
    </div>
</div>
<div class="x">
    <div>
        <p class="z">Z</p>
    </div>
</div>


jQuery:

$('div').each(function(){
    if($(this).find('.y')){
      $(this).siblings('div').find('.z').closest('div').addClass(abc);    
    }
});

Here's a fiddle:
http://ift.tt/1JrgAhg


Thanks for any help!

Symfony2 using two different ajax scripts(failed to load response data)

So I have two ajax scripts. One that increases the value and one that decreases. The first scripts, that increases the value works, however the second script which is almost identical does not work and I am getting Failed to load response data in devTools. I dont know why, but maybe you cant use two ajax scripts like that? Maybe I need to create a new file for each script? I really dont know...

Well this is my script file :

$(document).ready(function () {
    $(document).on('click', '.plus', function (e) {
    $this = $(this);

    $.ajax({
        type: 'POST',
        url: 'add/quantity',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {      
          if(data.success == false){
           alert('error')
          }else{

           }
        }
    });
});

    $(document).on('click', '.minus', function (e) {
    $this = $(this);

    $.ajax({
        type: 'POST',
        url: 'remove/quantity',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {
          if(data.success == false){
           alert('error')
          }
        }
    });
});
});

And my controller for both scripts:

public function addQuantityAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];
    $quantity = $requestData['quantity'];
    /** logic*/
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $qtyAvailable > $cart[ $productid ] ) {
        $cart[ $productid ] = $cart[ $productid ] + 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity increased'));
         $session->set('cart', $cart);
    } else {
        $response->setData(array('success'=>false,'message'=>'Out of stock'));
    }
    return $response;
}

public function removeQuantityAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];
    $quantity = $requestData['quantity'];
    /** logic*/
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $cart[ $productid] > 1 ) {
        $cart[ $productid ] = $cart[ $productid ] - 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity decreased'));
         $session->set('cart', $cart);
    } else {
        $response->setData(array('success'=>false,'message'=>'Cant be lower than 1'));
    }
    return $response;
}

Routing.yml:

add_quantity:
  pattern:  /add/quantity
  defaults: { _controller: MpShopBundle:Homepage:addQuantity }

remove_quantity:
  pattern:  /remove/quantity
  defaults: { _controller: MpShopBundle:Homepage:removeQuantity }

As you can see the code is practically identical. It should work, but im not getting any response for the second script.. why?

When im trying to get the response i get status:302 and it redirects me back to the same page... Anyone know why?

Iterate json data in javascript

Following JSON data comes from php,

Json format

I have tried following code. But console displays undefined error.

jQuery.each(result.address, function(obj) {
  console.log(obj.city);
});

how to remove the list of values from json object to another json object using jquery

for example I have two JSON Object. One of them is var A={'Header','Quotes','Returns','indent','Basic'.....,'Placing'.} another Object having Var B={Header','Quotes','Returns','indent'....}

in B having some Header,Quotes,Returns and Indent. So if A having same elements need to remove in jquery.

A's Final Output should be A={'Basic','Placing'.....}

Adding search button and text box in ui-dialog-buttonpane

I am writing a greasemonkey script to manipulates the DOM, queries a server and displays the result on a separate jquery dialog. I want to add following two functionalities to it:

  1. Provide a search box which acts like a simple search on a browser (i.e. searches through the content of the jquery dialog only and highlights the text).
  2. Provide a text-box, the content of which should be stored permanently for all future use of the userscript unless the user changes it specifically.

The problem I am facing is that I want to include both of these in the ui-dialog-buttonpane area of the dialog, to the left of the close button, but I am not able to figure out how to do that.

What I do know is that I can use window.find() (as used here http://ift.tt/1snM0Ap) to enable the browser find functionality.

Can someone help me with this ? Following is the code for my existing greasemonkey script:

// ==UserScript==
// @name        Query for each URL Asynchronously
// @namespace   SupportScript
// @include     *
// @require     http://ift.tt/1yCEpkO
// @require     http://ift.tt/1zMTD8C
// @resource    jqUI_CSS  http://ift.tt/1JrgA0S
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getResourceURL
// @run-at      document-end
// allow pasting
// ==/UserScript==

var snapshotResults = document.evaluate('//a[contains(@href,"http")]/@href', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var windowWidth = $(window).width()-800;
var windowHeight = $(window).height();

var zNode = document.createElement ('input');
zNode.setAttribute ('id', 'SSButton');
zNode.setAttribute( 'type', 'image' );
zNode.setAttribute( 'src', 'http://ift.tt/1zMTB0q');
//zNode.setAttribute( 'src', 'http://ift.tt/1JrgA0U');
//zNode.setAttribute( 'src','http://ift.tt/1zMTB0s');
document.body.appendChild (zNode);

var batchSize = 10;
var urlsToUpsert = [];
var uniqueHostnameSet = new Set();
var uniqueURLArray = [];
uniqueHostnameSet.add(window.location.hostname);
var finalUrl = window.location.protocol + '//' + window.location.hostname;
uniqueURLArray.push(finalUrl);
for (var iterate = 0; iterate < snapshotResults.snapshotLength; iterate++)
{
    var hrefContent = snapshotResults.snapshotItem(iterate).textContent;
    var regex = /http.*/;
    var href = regex.exec(hrefContent);
    var a = document.createElement('a');
    a.href = href;
    if (!uniqueHostnameSet.has(a.hostname))
    {
        uniqueHostnameSet.add(a.hostname);
        finalUrl = a.protocol + '//' + a.hostname;
        uniqueURLArray.push(finalUrl);
    }
}

var divMain = '<div id="SSOverlayDialog"></div>';
$('body').append(divMain);

$.Coral = function (options) {
    $.extend(options, {
        url: "my URL",
        data: JSON.stringify(options.data),
        dataType: 'json',
        crossDomain: true,
        type: 'POST',
        contentType: 'application/json',
        processData: false,
        headers: {
            'Content-Encoding': 'abc',
            'X-Target': options.operation
        },

        dataFilter: function(data, type) {
            return data || "{}";
        }
    });
    return $.ajax(options);
};

$.GetOperation = function (options) {
    $.extend(options, {
        async: true,
        success: function(data) {
            handleData(data);
        },
        operation: 'opeartion1'
    });
    return $.Coral(options);
};

$.UpsertOperation = function (options) {
    $.extend(options, {
        async: true,
        operation: 'Operation2'
    });
    return $.Coral(options);
};


for (var iterateUniqueURLArray=0; iterateUniqueURLArray<uniqueURLArray.length; iterateUniqueURLArray+=batchSize) {
    var urlList = uniqueURLArray.slice(iterateUniqueURLArray,iterateUniqueURLArray+batchSize);
    try {
        var listOfURLs = {
            storeUrlList: urlList
        };
        var dataGetAttributes = {data: listOfURLs};
        $.GetOperation(dataGetAttributes);
    } catch(e) {
        console.log(e);
    }

}

function handleData (data) {
    var div = '<div id="SSOverlayDialog">';
    var response = JSON.stringify(data);
    var subString = "";
    var startIndex = response.indexOf('{',1);
    var endIndex = response.lastIndexOf('}');
    var responseText = response.substring(startIndex,endIndex);
    var subString = JSON.parse(responseText);
    $.each( subString, function( key, value ) {
        key = JSON.stringify(key);
        div+='<b><i><a style="color:#0645AD" href="'+key.substring(1,key.length-1)+'"><u>' + key.substring(1,key.length-1) + '</u></a></i></b><br><br>';
        if(JSON.stringify(value)==='{}') {
            console.log("Value for URL "+key+" is null.");
            div+='<p>This URL does not exist with Mobius.<span style="color:red" class="urlNotPresent" id ="'+key.substring(1,key.length-1)+'"><u>Click Here</u></span> to submit to Mobius.</p>';
        }
        $.each( value, function( ky, val ) {
            ky = JSON.stringify(ky);
            if (val==null) {
                div += '<p><b>'+ky.substring(1,ky.length-1)+': </b><i>'+val+'</i></p>';
            }
            else{
                val = JSON.stringify(val);
                div += '<p><b>'+ky.substring(1,ky.length-1)+': </b><i>'+val.substring(1,val.length-1)+'</i></p>';
            };
        });
        div+='<br>';
    });
    div += '</div>';
    $('#SSOverlayDialog').append(div);
    $(".urlNotPresent").off('click');
    $(".urlNotPresent").one('click', urlNotPresentFn);
    $(".urlNotPresent").hover(pointerToClick, pointerToDefault);
}

var urlNotPresentFn = function() {
    var url = jQuery(this).attr("id");
    if (urlsToUpsert.length == batchSize-1) {
        urlsToUpsert.push(url);
        var listOfURLs = {
            storeUrlList: urlsToUpsert
        };
        var myOptions = {data: listOfURLs};
        $.UpsertOperation(myOptions);
        urlsToUpsert.length = 0;
    } else {
        urlsToUpsert.push(url);
    };
    console.log(urlsToUpsert);
}

var pointerToClick = function() {
    $(".urlNotPresent").css("cursor", "pointer");
}

var pointerToDefault = function(){
    $(".urlNotPresent").css("cursor", "default");
}

$(window).bind('beforeunload', function() {
    if(urlsToUpsert.length>0) {
        var listOfURLs = {
            storeUrlList: urlsToUpsert
        };
        var myOptions = {data: listOfURLs};
        $.UpsertOperation(myOptions);
        urlsToUpsert.length = 0;
    };
    return ;
});

$('#SSOverlayDialog').dialog({

    autoOpen: false,
    modal: false,
    title: 'Discovered URLs (press "Esc" button to close)',
    position: {
        at: 'right top'
    },
    resizable: false,
    width: windowWidth,
    height: windowHeight,
    open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
    zIndex: 11111111,
    buttons: [
    {
        text: 'Close',
        click: function () {
            $(this).dialog('close');
        }
    }
    ]
});

$("#SSButton").click(function() {
    ($("#SSOverlayDialog").dialog("isOpen") == false) ? $("#SSOverlayDialog").dialog("open") : $("#SSOverlayDialog").dialog("close") ;
/*  if ($("#SSOverlayDialog").dialog("isOpen") == false) {
            $("#SSOverlayDialog").dialog("open"),
            $('#SSButton').css({
                'transform': 'rotate(180deg)',
                'transform': 'translate(-windowWidth)'
            });
    } else{
        $("#SSOverlayDialog").dialog("close"),
        $('#SSButton').css({
            'transform': 'initial'
        });
    };*/
});

var jqUI_CssSrc = GM_getResourceText('jqUI_CSS');
jqUI_CssSrc = jqUI_CssSrc.replace(/\.ui-front \{[\s]*z-index:\s100\;[\s]*\}/g,".ui-front \{\n z-index: 20000000 \; \n\}");
GM_addStyle(jqUI_CssSrc);

GM_addStyle ( multilineStr ( function () {/*!
  #SSButton {
    background: none repeat scroll 0% 0% ;
    background-image: none;
    background-repeat: repeat;
    background-attachment: scroll;
    background-position: 0% 0%;
    background-size: auto auto;
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 22222222;
    width: 40px;
    height: 40px;
}
*/} ) );

function multilineStr (multiLineStringFn) {
    var str = multiLineStringFn.toString ();
    str     = str.replace (/^[^\/]+\/\*!?/, '') // Strip function () { /*!
            .replace (/\s*\*\/\s*\}\s*$/, '')   // Strip */ }
            .replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
            ;
            return str;
        }

jsTree plugin Inside Ember

I have used jsTree plugin to render large number of tree node in my product.

Now I am in the process of moving to Ember, and need to implement jsTree plugin within Ember.

I wrote a Ember component to render my folder structure using jsTree.

<script type="text/x-handlebars" data-template-name="components/temp-tree">
    <div id="treediv">Tree Data</div>
</script>

App.TempTreeComponent = Ember.Component.extend({
    didInsertElement: function(){
        var self = this;
        self.$().jstree({
        'plugins':["contextmenu", "dnd"],
        'core' : {
        'data' : [
            'Simple root node',
            { 
                'text' : 'Root node 2',
                'state' : {
                    'opened' : true,
                    'selected' : true
                 },
        'children' : [
         { 'text' : 'Child 1' },
         'Child 2'
        ]
    } 
], 
'check_callback': true
}
})
.on('rename_node.jstree', function(e, data) {
    alert('rename');
})
.on('delete_node.jstree', function(e, data) {
    alert('delete');
}); 
}, 
actions:{

} 
});

In my component for each action done on the tree, jsTree triggers an event respective to the event.

I used to listen to the events and do necessary action if required.

Basically jsTree updates the DOM and triggers the event.

But in Ember we will not update the DOM ,instead we need to update the underlying MODEL and by two way data-binding the DOM is updated by Ember.

Here I am going against the Ember Conventions.

Am I going in the right direction ?

Is there any other way to use jsTree with Ember.

Or is there any jsTree like component available in Ember to render large number of tree nodes with all features like context menu, drag & drop, search, unique plugin, checkbox, lazy loading, updating nodes ?

Doughnut chart updates with twice the data

Working with chart js and got it to do what I needed which is pull data from a webservice and use $interval to update it. When I update the chart using the built in update function it displays again as expected but with the old data in it as well. I thought I was clearing the data out of the array, I am newer to angular so maybe I overlooked something.

Here is the js for what is going on.

angular.module('myapp', [])
  .controller('MainCtrl', function($scope, $http, $interval) {
    $scope.doughnutData = [];
    var myDoughnut = '';
    onload = function() {
      $http.get('http://ift.tt/1JOZRb4').success(function(returnedData) {

        $scope.username = returnedData.name;
        $scope.totalscore = returnedData.totalScore.toFixed(3);

        returnedData.models.forEach(function(x) {
          var score = x.score.toFixed(3);
          console.debug(score);
          if (score >= 75) {
            $scope.doughnutData.push({
              'value': x.score,
              'color': '#F7464A',
              'highlight': '#FF5A5E',
              'label': x.name
            });
          } else if (score >= 50) {
            $scope.doughnutData.push({
              'value': x.score,
              'color': '#FDB45C',
              'highlight': '#FFC870',
              'label': x.name
            });
          } else {
            $scope.doughnutData.push({
              'value': x.score,
              'color': '#424242',
              'highlight': '#686868',
              'label': x.name
            });
          }
        });
        $scope.doughnutData = sortByKey($scope.doughnutData, 'value');
        var ctx = document.getElementById("chart-area").getContext("2d");
        myDoughnut = new Chart(ctx).Doughnut($scope.doughnutData, {
          responsive: true
        });
      });
      mainInterval = $interval(function() {
         doughnutData = '';
        $http.get('http://ift.tt/1JOZRb4').success(function(returnedData) {
          $scope.username = returnedData.name;
          $scope.totalscore = returnedData.totalScore.toFixed(3);

          returnedData.models.forEach(function(x) {
            var score = x.score.toFixed(3);
            console.debug(score);
            if (score >= 75) {
              $scope.doughnutData.push({
                'value': x.score,
                'color': '#F7464A',
                'highlight': '#FF5A5E',
                'label': x.name
              });
            } else if (score >= 50) {
              $scope.doughnutData.push({
                'value': x.score,
                'color': '#FDB45C',
                'highlight': '#FFC870',
                'label': x.name
              });
            } else {
              $scope.doughnutData.push({
                'value': x.score,
                'color': '#424242',
                'highlight': '#686868',
                'label': x.name
              });
            }
          });
          $scope.doughnutData = sortByKey($scope.doughnutData, 'value');
          myDoughnut.segments = doughnutData;
          myDoughnut.update();
        });
      }, 5000);
      $scope.$apply();
    };

    function sortByKey(array, key) {
      return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
      });
    }
  });

So it starts out with 9 values, and when it updates it has 18, etc.. There is nothing currently that will update (I just have it in there now for when I move it to my production webservice). I was thinking the doughnutData = ''; in the $interval section would clear it out?

Wanted to include the html as well to give a better idea of what is going on:

<html>

  <head>
    <script src="http://ift.tt/1Gufy1b"></script>
    <script src="../Chart.js"></script>
    <script src="../src/Chart.Doughnut.js"></script>
    <script src="http://ift.tt/198QQJG"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="../script.js"></script>
  </head>

  <body ng-app="myapp" ng-controller="MainCtrl">
    <div id="canvas-holder">
      <canvas id="chart-area" width="50" height="50"></canvas>
    </div>
  </body>

</html>