Affichage des articles dont le libellé est Active questions tagged jquery - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged jquery - Stack Overflow. Afficher tous les articles

vendredi 29 mai 2015

How to hide Boostrap Dropdown submenu when other menu of dropdown is clicked?

I am displaying bootstrap dropdownmenu and on click of any parent dropdown value i am displaying other child dropdown. when i click on a value in dropdown ,the childmenu opens and when i click on next dropdown value ,the previous chidmenu dropdown is not closed.I want to close the previous childdropdown menu if any other value of parent menu is clicked.How to achieve this?Please help! Thanks in advance

Here is my code:

<div class="dropdown">
    <ul id="ddlTest" class="ddltestdd dropdown-menu" role="menu">
        @foreach (var item in (IEnumerable<SelectListItem>)ViewBag.testresults)
        {
            <li class="dropdown-submenu">
                <span class="dropdown-toggle" data-toggle="dropdown">@item.Text</span>
                <span class="testCaret" aria-hidden="true" style="float:right;margin-top:5px;">
                </span>
                <ul class="ddltestdd dropdown-menu dropup" role="menu" id="testorder_@item.Text">
                    <li>
                        <span class="TestBySubmenu">T1</span>
                    </li>
                    <li>
                        <span class="TestBySubmenu">T2</span>
                    </li>
                </ul>
            </li>
        }
    </ul>
</div>

Jquery:

var testText;
                    $(".dropdown-submenu").click(function () {
                            $(this).find(".dropdown-submenu").removeClass('open');
                    $(".dropdown-submenu:hover > .dropdown-menu").css('display', 'block');
                    testText;= $(this).text();
                    return false;
                });



        $('.dropdown-menu li span').click(function () {

        var Allowpageload = testText;
        if ((Allowpageload == "T1") || (Allowpageload == "T2")) {
          //load page
            $(".dropdown-submenu:hover > .dropdown-menu").css('display', 'none');
            $('[id^="testorder_]').dropdown('toggle');
            $('[data-toggle="dropdown"]').parent().removeClass('open');
            }

Geojson (GetJSON) and remove higlight (mouse out) on Leaflet

I don't manage to remove the highlight on a map since I call the data with $.getJSON. When I use the basic map (http://ift.tt/1Kt8lC1) all works, but when I call a geojson file with Jquery (not a leaflet json template with var = {json}), the highlight doesn't remove.

Example of what doesn't work (you can see it at : http://ift.tt/1G6JiXs) I think it comes from the function resetHighlight(e) but I don't manage to resolve it.

    function styleeurope(feature) {
        return {
            weight: 1.5,
            color: '#222',
            opacity:0.5,
            fillOpacity: 0.7,
            fillColor: getColor(feature.properties.statTOTAL)
        };
    }
    function highlightFeature(e) {
        var layer = e.target;

        layer.setStyle({
            weight: 3,
            color: 'black',
            opacity: 0.7,
            dashArray: '0',
            fillOpacity: 0.5,
            fillColor: '#fff200',
        });


        info.update(layer.feature.properties);
    }

// reset highlight //

function resetHighlight(e) {
        geojson.resetStyle(e.target);
        info.update();
    }

// OnEachFeature

function onEachFeature(feature, layer) {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight,       
        });
    }

// GeoJSON call data //

$.getJSON("data/europe_fao.json",function(dataeurope){ var geojson = L.geoJson(dataeurope,{
        style: styleeurope,
        onEachFeature: onEachFeature} ).addTo(map);  });

Thank you so much if you manage to help me !

Json response to ajax

The data is inserted and i receive in console the json response but the page move for the insert php and gives the json response So i start in page A (form) and after submit moves to page B (insert)giving me the json response. I'm having a problem getting the response of the following php into ajax

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {

$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
    trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
if (!$stmt->execute()) {
    echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
} else {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));

This is my ajax

$.ajax({
            url: 'nova_formacaoBD.php',
            dataType: 'json',
            data: data,
            success: function(data) {
                $('#ajaxDivOk').html('Informação: Esta formação foi registada na base de dados');
                if(data.status == "success"){ 
                   $('#ajaxDivOk').append(data.message);
                }
             }
          });

And this is my form

 <form action="nova_formacaoBD.php" method="post" id="formacao" name="formacao" enctype="multipart/form-data">

Place the scrollbar at the bottom of viewport

I'm working on a rather complex layout. There are two regions, red and blue, that must scroll vertically simultaneously but the right region (blue) must be able to scroll horizontally independently of the other region.

I managed to do that, but the scrollbar is always at the bottom of the div and I need the scrollbar always visible at the bottom of the viewport.

Is it possible to achieve this with HTML/CSS? What plain JS or jQuery plugins could help with this?

JSFiddle Demo

Ajax fails to pass html page as parameter to code behind

I am working on a task to convert a webpage to pdf file using SelectPdf. SelectPdf does not support dynamic pages. So I want to use Ajax to pass the webpage as html.

For some reason when I passed ordinary string it works but when I change to use a variable (with html as value) it doesn't. I don't know whether the html content is too large, however I tried with less content and still the same issue. Any help will be appreciated.

The project is language is VB.Net, the page is vbhtml and code behind is a controller.

Please see below the code I have implemented:

VIEW

           var btn = $('#BtnCreateHtmlToPdf');

           btn.click(function () {

            var theHtml = document.documentElement.innerHTML;

            //Just to see there is a value
            alert(theHtml)  

            $(function () {
                $.ajax({
                    type: 'post',
                    url: "/CreatHtmlToPdf/CreatePdf",
                    dataType: "html",
                    data: { HTML: theHtml }
                })
                .done(function (results) {
                    alert("Html data: " + results);
                });
            });
           });

CODE BEHIND

Public Class CreatHtmlToPdfController
    Inherits Controller

    ' GET: CreatHtmlToPdf
    Function Index() As ActionResult

        Return View()
    End Function

    <HttpPost()>
    Function CreatePdf(ByVal HTML As String) As ActionResult

        Dim doc As PdfDocument

        ' read parameters from the webpage
        Dim htmlString As String = HTML

        ' instantiate a html to pdf converter object
        Dim converter As New HtmlToPdf()

        ' create a new pdf document converting an url
        If (HTML <> String.Empty) Then

            doc = converter.ConvertHtmlString(htmlString)


        End If


        ' save pdf document
        Dim pdf As Byte() = doc.Save()

        ' close pdf document
        doc.Close()

        ' return resulted pdf document
        Dim fileResult As FileResult = New FileContentResult(pdf, "application/pdf")
        fileResult.FileDownloadName = "Results_page.pdf"
        Return fileResult

    End Function

    'Declaration
    'Public Property EnablePageMethods As Boolean

End Class

WAI ARIA screenreader not reading dynamically added rows

I've scenario where I am trying to add rows dynamically to a table using Ajax. I've following table structure:

<table class="user-table table" id="usersTable">
    <thead>
      <tr>
        <th class="user-col user-name">Name</th>
        <th class="user-col user-email">Email</th>
        <th class="user-col user-status">Admin</th>
        <th class="user-col user-i-col">Active</th>
        <th class="user-col user-i-col">Actions</th>
      </tr>
    </thead>
</table>

Now I am trying to dynamically add/remove rows to/from table using JavaScript/jQuery. There are basically 2 different ways I am doing this:

  1. looping through JSON data, creating tbody, rows and cell and appending the tbody to target table using JavaScript OR
  2. using $(element).append(HTML) to append the HTML returned by Ajax call.

if I use JavaScript to create tbody, rows and data cells, NVDA correctly reads the added rows Ref: updateTableAsync . So if I add 3 rows to table this way, NVDA will read table with 4 rows and 5 columns, which is correct.

However, if I try to append the returned html directory into table using $.append or $.html, it does not identify the rows that were added dynamically. Ref: updateTableContentAsync

Here is the JSON that is returned:

{"users":[
    {"name":"ABC","email":"ABC@mailcatch.com","admin":true, "active":true,"action":"Remove" },
    {"name":"XYZ","email":"XYZ@mailcatch.com","admin":false, "active":false,"action":"Remove"},
    {"name":"ASDF","email":"ASDF@mailcatch.com","admin":false, "active":true,"action":"Remove"}
    ]
}

(function(global, window, $) {
      'use strict';
      //Accessible Ajax Loading Test
      var AALoadingTest = AALoadingTest || {};
      AALoadingTest.AjaxUtil = (function() {          
          
          
          var makeDataCell = function(row, index, data ) {
            var cell = row.insertCell(index);
            var cellText  = document.createTextNode(data)
            cell.appendChild(cellText);
          };

          var setFocus = function(element, fallbackElement) {
            var focusElement = document.getElementById(element); 
            if(typeof focusElement == 'undefined') {
              focusElement = document.getElementById(fallbackElement);
            }                
            window.setTimeout(function(){
              window.console.log(focusElement);
              focusElement.focus();
            }, 100);
          };

          //Method : 1 Update table content by looping through json data using native Javascript   
          var updateTableAsync = function(url, targetTable, targetContainer, focusContainer, announce) {
            
            //TODO: remove timeout when in prod, need while testing because locally changes are loading too fast
            window.setTimeout( function() {
              $.get(url, function(data){              
                
                var tempTargetTBody = document.getElementById(targetContainer);
                var target = document.getElementById(targetTable);
                var targetTBody = document.createElement('tbody');
                targetTBody.innerHTML = '';
                targetTBody.setAttribute('aria-live', tempTargetTBody.getAttribute('aria-live'));
                // targetTBody.setAttribute('aria-atomic', tempTargetTBody.getAttribute('aria-live'));
                tempTargetTBody.remove();
                targetTBody.setAttribute('id',targetContainer);
                
                $.each(data.users, function(key, value){
                  var row = targetTBody.insertRow(targetTBody.rows.length);
                  makeDataCell(row, 0, value.name);
                  makeDataCell(row, 1, value.email);
                  makeDataCell(row, 2, value.admin ? 'Yes': 'No');
                  makeDataCell(row, 3, value.active ? 'Yes': 'No');
                  makeDataCell(row, 4, value.action);
                });
                target.appendChild(targetTBody);           
              })
            },5000);
          };

          //Method : 2 Update table content by inserting HTML element by looping through JSON returned into table  
          var updateTableHTMLAsync = function(url, targetTable,  targetContainer, focusContainer, announce) {                         
            

            //TODO: remove timeout when in prod, need while testing because locally changes are loading too fast
            window.setTimeout( function() {
              $.get(url, function(data){              
                
                var targetElement = $('#'+targetContainer);
                targetElement.remove();
                targetElement = $('<tbody></tbody>').attr({'aria-live': 'polite', 'id': targetContainer});
                
                $.each(data.users, function(key, value) {
                  window.setTimeout(function() {
                    var row = $("<tr> </tr>");
                      targetElement.append(row);
                      row.append($("<td></td>").text(value.name));
                      row.append($("<td></td>").text(value.email));
                      row.append($("<td></td>").text((value.admin ? 'Yes': 'No')));
                      row.append($("<td></td>").text((value.active ? 'Yes': 'No')));
                      row.append($("<td></td>").text(value.action));
                  },100);
                });      
                $("#"+targetTable).append(targetElement);         
                
              })
            },5000);
          };

          //Method : 3 Update table content by inserting HTML returned into table  
          var updateTableContentAsync = function(url, targetTable,  targetContainer, focusContainer, announce) {                         
            

            //TODO: remove timeout when in prod, need while testing because locally changes are loading too fast
            window.setTimeout( function() {
              $.get(url, function(data){              
                
                var targetElement = $('#'+targetContainer);
                targetElement.remove();
                targetElement = $('<tbody></tbody>').attr({/*'aria-live': 'polite',*/ 'id': targetContainer});
                $("#"+targetTable).append(targetElement);                
                
                targetElement.append($(data));                
              })
            },5000);
          };

          return {
            updateTableAsync: updateTableAsync,
            updateTableHTMLAsync: updateTableHTMLAsync,
            updateTableContentAsync: updateTableContentAsync,
            removeLoader: removeLoader,
            loader: loader
          };
      })();
      
      $("#asyncHTML").on("click", function(e){ 
        e.stopPropagation();
        AALoadingTest.AjaxUtil.updateTableHTMLAsync(
          $(this).attr('data-resource'),
          $(this).attr('data-target-table'),
          $(this).attr('data-target-element'),
          $(this).attr('data-focus-element'),
          true
        );       
        return false;
      });

      $("#asyncJSON").on("click", function(e){ 
        e.stopPropagation();
        AALoadingTest.AjaxUtil.updateTableAsync(
          $(this).attr('data-resource'),
          $(this).attr('data-target-table'),
          $(this).attr('data-target-element'),
          $(this).attr('data-focus-element'),
          true
        );       
        return false;
      });

      $("#asyncHTMLContent").on("click", function(e){ 
          e.stopPropagation();
          AALoadingTest.AjaxUtil.updateTableContentAsync(
            $(this).attr('href'),
            $(this).attr('data-target-table'),
            $(this).attr('data-target-element'),
            $(this).attr('data-focus-element'),
            true
          );       
          return false;
      });


      })(this, window,jQuery);
<link href="http://ift.tt/1mDOveJ" rel="stylesheet"/>
<script src="http://ift.tt/1qRgvOJ"></script>
<script src="http://ift.tt/1h4yM0u"></script>
<main>
      <div class="container">     
        <div class="container-fluid">         
          
          <h1>Dynamic Tables</h1>        
          <p> Load JSON using Ajax get, use JavaScript to create tbody, rows and data cell and append the tbody to table using appendChild</p>
          <br>
            <a class="btn btn-primary async" id="asyncJSON" data-target-table="usersTableJSON"
                role="button" data-target-element="userTableBodyJSON" data-focus-element="asyncContentJSON" 
                href="javascript:;" data-resource="data/users.json">
                Load Users <span class="sr-only">Load json Data</span>
            </a>
          <br>
          <br>
          <div class="panel" id="asyncContentJSON">
            <table class="user-table table" id="usersTableJSON">
            <thead>
              <tr>
                <th class="user-col user-name">Name</th>
                <th class="user-col user-email">Email</th>
                <th class="user-col user-status">Admin</th>
                <th class="user-col user-i-col">Active</th>
                <th class="user-col user-i-col">Actions</th>
              </tr>
            </thead>
            <tbody id="userTableBodyJSON" aria-live="polite"></tbody>            
          </table>
          </div>

          <br>
          <p> Load JSON using Ajax get, use jQuery to create tbody, rows and data cell and append the tbody to table using $.append</p>
          <br>
            <a class="btn btn-primary async2" id="asyncHTML"
                role="button" data-target-element="userTableBodyHTML" data-target-table="usersTableHTML" data-focus-element="asyncContentHTML" 
                href="data/rows.html" data-resource="data/users.json">
                Load Users<span class="sr-only">Load HTML Data</span>
            </a>
          <br>

          <br>
          <div class="panel" id="asyncContentHTML">
            <table class="user-table table" id="usersTableHTML">
            <thead>
              <tr>
                <th class="user-col user-name">Name</th>
                <th class="user-col user-email">Email</th>
                <th class="user-col user-status">Admin</th>
                <th class="user-col user-i-col">Active</th>
                <th class="user-col user-i-col">Actions</th>
              </tr>
            </thead>
            <tbody id="userTableBodyHTML" aria-live="polite"></tbody>
          </table>
          </div>

          <br>
          <p> Load JSON using Ajax get, use JavaScript to create tbody, rows and data cell and append the tbody to table using $.html</p>
          <br>
            <a class="btn btn-primary async2" id="asyncHTMLContent"
                role="button" data-target-element="userTableBodyHTMLContent" data-target-table="usersTableHTMLContent" data-focus-element="asyncContentHTMLContent" 
                href="data/rows.html" data-resource="">
                Load Users<span class="sr-only">Load HTML View</span>
            </a>
          <br>
          <br>
          <div class="panel" id="asyncContentHTMLContent">
            <table class="user-table table" id="usersTableHTMLContent">
            <thead>
              <tr>
                <th class="user-col user-name">Name</th>
                <th class="user-col user-email">Email</th>
                <th class="user-col user-status">Admin</th>
                <th class="user-col user-i-col">Active</th>
                <th class="user-col user-i-col">Actions</th>
              </tr>
            </thead>
            <tbody id="userTableBodyHTMLContent" aria-live="polite"></tbody>
          </table>
          </div>
        </div>        
      </div>
      <div id="overlay" class="hidden">          
        <span class="visuallyHidden" id="loadingMessage" role="status" aria-hidden="true"></span>
      </div>        
    </main>

One thing that I suspect here is: when I manually add rows one by one, NVDA is aware of individual DOM change, however, when I update the innerHTML all it know is "one update in DOM". Please let me know if someone has faced similar issue and how you fixed that.

Thanks

Using ':hidden' selector to find hidden elements in jquery

In jQuery, I can use $(':hidden') to find hidden elements, but I don't want to include the 0 size elements (width=0 and height=0).

How to achieve this?

I can't just judge if it is 0 size, because if one of its parents is hidden, I also want to select it.

For example:

<img id="e1" width="0" height="0" />
<div style="display:none;">
    <img id="e2" width="0" height="0" />
</div>

I want to select "e2",but not "e1".

AngularJS/jQuery - Update Scope

I am working on a legacy system that uses jQuery and had to add AngularJS for a particular feature, however im having issues updating the scope.

Basically, we have a dropdown and when you select an option, we're firing an Ajax call to get an array or objects. This array of objects is then being stored in a global variable, say var myObjs. Basically using the ng-repeat service from Angular, I need to loop through these and render a list.

I am new to Angular, so i'm not sure if this is the way to be done. What I am doing is setting the scope in this way:

$scope.myObjs= myObjs;

However, by doing so, the scope is not changing at all.

Can someone tell me how this can be done? I tried to look around but am finding it a bit hacky having a hybrid of AngularJS & jQuery on the same page.

EDIT: adding sample snippet. Basically on change of the dropdown im firing an ajax call, and store the response (which is an array of objects) in myObjs variable. Then I am trying to set the scope to the value of this variable. Regarding the way I am bootstrapping Angular, this is due to a limitation of the legacy system, which is over 8 years old.

var myObjs = null;


$(function() {
  $("#myHeader").on("change", "#mySelect", function() {
    // perform Ajax Call
  });

});

function ajaxCallback(data) {
  myObjs = data;
}

var myModule = angular.module("GetObjsModule", []);
myModule.controller("MyController", function($scope) {
  $scope.objs = myObjs;
});

angular.element(document).ready(function() {
  var myDiv = $("#myDiv");
  angular.bootstrap(myDiv, ["GetObjsModule"]);
});
<script src="http://ift.tt/1mQ03rn"></script>
<script src="http://ift.tt/Sw98cH">
</script>

<div id="myHeader">
  <select id="mySelect">
    <option value="1">Value 1</option>
    <option value="2">Value 2</option>
    <option value="3">Value 3</option>
  </select>
</div>

<div id="myDiv">
  <ul ng-controller="MyController">
    <li ng-repeat="x in objs">
      <div>
        {{x.name}} {{x.surname}}: {{x.tel}}
      </div>
      <div>
        <p>
          Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut odio. Curabitur malesuada. Vestibulum
          a velit eu ante scelerisque vulputate.
        </p>
      </div>
    </li>
  </ul>
</div>

trigger is not working in angular js

trigger is not working in angular js

 $http({
     method: 'POST',
     url: partial_path + '/test.php',
     data: 'action=create&d=' + localStorage.getItem('lastid'),
     headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
     }
 }).success(function(data) {
     if (data != "error") {
         var url = partial_path + '/' + data;
         //alert(url);
         $("#hreflink").attr("href", url);
         $('#hreflink').trigger('click');
     }
 });

Hi i am new to angular js

Trigger event is not working in angular js ajax loaded template

Please help to fix this issue

Updated

window.open(url, '_blank');

window.open is working but its ask popup browser alert

Codebehind function not being called by Ajax POST

My Ajax post is not running my code behind method and thus not returning any data.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="AspTest.Test" %>

Test.aspx (Ajax script)

    <script>
                $(".avatarThumb").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "Test.aspx/MyMethod",
                        //data: {"s": "Some data passed through" },
                        //contentType: 'application/json; charset=utf-8',
                        //dataType: 'json',
                        success: function (response) {
                            alert(response.d); //Returns "undefined"
                        },
                        failure: function(response) {
                            alert(response);
                        }
                    });
                });
            </script>

Removing contentType and dataType does reach success but does not run the codeBehind method. With contentType and/or dataType active it will not reach success nor failure. FF firebug does not display any errors.

*Test.aspx.cs CodeBehind method

        [System.Web.Services.WebMethod]
        public static string MyMethod()
        {
(*)         Debug.WriteLine("MyMethod called!"); // (*) Breakpoint never reached

            return "Method called!";
        }

extract vimeo video id from the url

Though this question is available on SO, I am facing a little problem.I failed to extract the vimeo id using vimeo regex used here: Vimeo Regex

My codes I,m using now:

function vimeoProcess(url){
   var vimeoReg = /https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/;
   var match = url.match(vimeoReg);
   if (match){
      console.log(match[3]);
   }else{
      return "<span class='error'>error</span>";
   }
}

It does not consoles any thing. Can any one help?

change img size inside iframe with jquery

I'm using an adserver on my website. All adds are using iframe, and I'm trying to target the img (the first one with width = 728 & height = 90) inside the iframe to change its size (width & height). I've been able to target the body (changing its background color to test), but I can't target the image to change its size. here is the iframe code, I need to target the iframe object, and not the iframe class, because the class changes every time.

<div class="insert_pub">
<iframe id="a0811af3" width="" height="90" frameborder="0" scrolling="no" src="/www/delivery/afr.php?zoneid=3&cb=INSERT_RANDOM_NUMBER_HERE" name="a0811af3">
#document
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html lang="en" xml:lang="en" xmlns="http://ift.tt/lH0Osb">
<head></head>
<body>
<a href="/www/delivery/ck.php?oaparams=2__bannerid=212__zoneid=3__cb=9b2dbdb22f__oadest=http%3A%2F%2Fthebayfestival.fr%2F" target="_blank">
    <img src="/www/images/c34d3222b19118f97aa99e76310c70fe.jpg" alt="" title="" height="90" border="0" width="728">
</a>
<div id="beacon_9b2dbdb22f" style="position: absolute; left: 0px; top: 0px; visibility: hidden;">
    <img src="/www/delivery/lg.php?bannerid=212&amp;campaignid=176&amp;zoneid=3&amp;loc=http%3A%2F%2Fwww.mmdwc.com%2Fmagazine%2F&amp;cb=9b2dbdb22f" alt="" style="width: 0px; height: 0px;" height="0" width="0">
</div>
</body>
</html>
</html>
</iframe>
</div>

here is what I've tried, but it's not working :

function iframe_insert_size() {
  $(".insert_pub iframe").contents().find("img").css({"width":624, "height" : 77});
}

can anybody help me with this ?

thanks a lot,

Submitting post between ajax and php

I'm a newbie in the world of php and I was trying to learn it with a simple page. I've created an html form and I want to send data using ajax but it still POST http://localhost/Home.php 500 (Internal Server Error)

In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)

This is my form (Home.php)

<div id="displayForm">

<form method="post" id="selectForm">
        <?php
        include ("Database.php");

        $Database = new Database( "localhost", "root", "1234");
        $Database->connectToServer();
        $Database->connectToDatabase("test");
        $Tables = $Database->countTable();
        foreach($Tables as $column) {
            echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " .  $column;
        }
        ?>
    <input type="submit" class="submit" name="createSelect">
</form> </div>

The php in the form is only for create the button with the name of the tables.

In the same file (Home.php)

<?php
 include 'ChromePhp.php';
 ChromePhp::log("corretto");
echo "ok";
?>

In the file Home.php, in the head section I've included all jquery library and the js file

<script src='jquery-1.10.2.min.js'></script>
<script src='Script.js'></script>

And this is my ajax file

$(document).ready(
    function() {
        $("#createTable").click(goCreate);
        $("#displayTable").click(goDisplay);
        $('#selectForm').submit(goSelect);
        $("#createForm").hide();
        $("#displayForm").hide();
    }
);

function goCreate(data) {
    $("#createForm").show();
    $("#functions").hide();
}

function goDisplay(data) {
    $("#displayForm").show();
    $("#functions").hide();
}

function goSelect() {
    var selectedTable = $("#selectQuery:checked").val();
    console.log($("#selectQuery:checked").val());


    $.ajax({
        url: "Home.php",
        type: "POST",
        dataType: "html",
        data: {
            'select': 'display',
            'table': selectedTable
        },
        success: function(msg) {
            console.log(msg);
        },
        error: function(xhr, desc, err) {
            console.log("error");
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }

    }); // end ajax call
    return false;
};

How do I update the location field when I chnge the latitude, longitude coordinates manually?

I am using jquery location picker plugin to take the entry of user's location through a map.

The problem that I 'm facing is that when I change the lat, long coodinates manually, the location field does not shift accordingly to the correct position however the marker does.

What is the solution?

Here is the map that I'm using http://ift.tt/1HAeglQ

JQgrid file upload with form edit

I have JQgrid with form edit.

 jQuery("#tblPriceListUpload").jqGrid({
        url: $('#tblPriceListUpload').attr("RequestUrl"),
        postData: { PriceListType: SelectedPriceListType },
        datatype: "json",
        mtype: "Get",
        hoverrows: false,
        ajaxGridOptions: { timeout: 30000 },
        colNames: PriceListColName,
        colModel: PriceListColModel,
        cmTemplate: { editable: true },
        rowNum: 10,
        hidegrid: false,
        rownumbers: true,
        pager: '#PriceListGridPager',
        viewrecords: true,
        caption: "Price List ",
        height: 'auto',
        scrollOffset: 0,
        gridview: true,
        shrinkToFit: true,
        autoencode: true,
        loadonce: true,
        ignoreCase: true,
        enableClear: true,
        width: '1000',
        beforeRequest: function () {

            //responsive_jqgrid($(".jqGrid"));
        }
    });

    $('#tblPriceListUpload').jqGrid('filterToolbar', { searchOnEnter: false, enableClear: false, defaultSearch: "cn", stringResult: true });

For Form Add

  $("#tblPriceListUpload").jqGrid('navGrid', '#PriceListGridPager',
           { edit: true, add: true, del: true, refresh: true, view: false, search: false },
           { //Edit Code here
               }, {

               caption: "",
               title: "Add Attachment",
               id: "add_Attachment",
               buttonicon: "ui-icon-plus",
               position: "first",
               url: 'AddPriceList',
               recreateForm: true,
               onclickSubmit: function (response, postdata) {
                   debugger;
                   if (jqXHRData) {
                       //jqXHRData.submit();
                       $("#Form").submit();
                       $("#FormError").remove();

                   }
               },
               beforeShowForm: function (form) {
                   $("#PriceListType").val(SelectedPriceListType);
                   $("#tr_PriceListType").hide();
                   $('#FileName').fileupload({
                       replaceFileInput: false,
                       dataType: 'json',
                       url: 'AddPriceList',
                       change: function (e, data) { },
                       add: function (e, data) {
                           jqXHRData = data
                       },
                       done: function (event, data) {

                           alert(data.result.message)
                           $("#cData").trigger('click');
                           $("#tblPriceListUpload").setGridParam({ datatype: 'json', page: 1 }).trigger("reloadGrid");
                           jqXHRData = null;
                       },
                       fail: function (event, data) {

                           if (data.files[0].error) {
                               alert(data.files[0].error);
                           }
                       }
                   });
               }

           }, {});

And Col Model Below

     var PriceListColModel = [{ name: 'DisplayDescription', index: 'DisplayDescription', align: 'center', editable: true, },
           {
               name: 'Header', index: 'Header', width: 95, align: 'center', formatter: 'select', editable: true,
               edittype: 'select', editoptions: { value: HeaderList, defaultValue: 'HP Oct 12 - GOs' },
               stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + HeaderList }
           },

    {
        name: 'OneSeriesPerPage', index: 'OneSeriesPerPage', align: 'center', formatter: 'checkbox', edittype: 'checkbox',
        editoptions: { value: "true:false", defaultValue: "true" }, editable: true
    },
{
    name: 'EnvironmentCode', index: 'EnvironmentCode', search: true, editable: true,
    edittype: 'select', editoptions: { value: EnvList, defaultValue: 'AFI' },
    stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + EnvList }
},
{
    name: 'FileName', index: 'FileName', edittype: 'file', editable: true,
    edittype: 'file',
    editoptions: {
        enctype: "multipart/form-data"
    }, search: true
},
    {
        name: 'PriceListType', index: 'PriceListType', align: 'center', hidden: true, editrules: {
            required: true,
            edithidden: true
        }
    }];

In "OnclickSubmit" event of "AddPriceList" if i am posting jqXHRData.submit(); If Check Box column is false it is not sending the data to controller. If true, it is sending the data to controller.

If i am posting the form $("#Form").submit(); I am not getting the file in Controller.

Please help on this issue.

Chomsky Normal Form using JavaScript : Stuck

I have been trying to implement a web application that converts the given context free grammar into its Chomsky Normal Form (CNF). The CodePen link to the same is http://ift.tt/1HAeeud

The only region where I am stuck is breaking down the rules of form S -> aAb into further nonterminals and terminals. Can anyone help me with an implementation algorithm regarding the same?

jquery function for getting div inside row Table

I have a Datalist with three columns or fields: Column1: Some data Column2: Linkbutton Update Column3: div "divCheck", by default it's hide.

<asp:DataList ID="MyDataList" runat="server" EnableViewState="True">
      <HeaderTemplate>
      </HeaderTemplate>
      <ItemTemplate>
          <table width="100%">
              <tr id="ItemRow" runat="server">
                  <td >
                      <%# DataBinder.Eval(Container.DataItem, "some_data")%>
                  </td>
                  <td >
                      <asp:LinkButton Text="Update" class="lnk_showCheck" CommandName="update" Runat="server" ID="update"   />
                  </td>
                  <td >
                      <div id="divCheck" style="display: none">Check</div>

                  </td>
              </tr>
          </table>
      </ItemTemplate>

</asp:DataList>

The idea is that when clicking linkbutton on any row, it has to trigger a server side function and call jquery function ShowCheck.

Protected Sub MyDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles MyDataList.ItemCommand

        If e.CommandName = "update" Then
            Dim script As String = "<script language='javascript'> ShowCheck();</script>"
            Page.ClientScript.RegisterStartupScript(Me.[GetType](), "ShowCheck", script, False)

        End If

    End Sub

Jquery ShowCheck() has to show divCheck in that row.

<script type="text/javascript">

        function ShowCheck() {

            //alert($(this).get(0).tagName);
            $('div', $(this).closest("td").next()).show();
            };

    </script>

Problem is that $(this) is passed as an undefined object. It should be passed as a LinkButton object inside DataList.

Is that possible? How could jquery find divCheck in Table row when is triggered from server side function?

Track JS CSS Asset Errors on page load

Is it possible to track the number of errors and warning thrown by a browser on page load using javascript?

For example CSS Assets missing or images missing or js script errors? I don't need a detailed log but maybe a count of each type of error.

Like a count of CSS, Assets missing and JS Errors?

This needs to be tracked using JS.

How to fix Foundation.js moving reveal modal html from backbone view

I'm developing a website with backbone.js, and foundation.js. I create a backbone parent view, and append a backbone child view to it.

    this.myProfileModalView = new MyApp.Views.MyProfileModalView();
    this.$el.append(this.myProfileModalView.render().el);

This child view contains the html for foundation reveal modal.

<div id="profileModal" class="reveal-modal medium" data-options="close_on_background_click:false;" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog" >

When the site loads the modal is correctly appended in the html as a child. However, when I click on the open modal button, the modal html suddenly gets placed just before the tag. This is making backbone events to not function, and also this.$el comes up null.

How can I fix this issue so that the appended view stays at the same location?

Fade in and Fade Out Text in DIV - Remove Loop

I have created a DIV with 3 different quotes fade in and fade out. I am using below JQuery code for the same.

(function() {
var quotes = $(".changetxt");
var quoteIndex = -1;
function showNextQuote() {
    ++quoteIndex;
    quotes.eq(quoteIndex % quotes.length)
        .fadeIn(1000)
        .delay(4000)
        .fadeOut(500, showNextQuote);
}
showNextQuote();
})();

HTML CODE

<div class="toptext">
    <div class="changetxt">
        ”The simple act of paying positive attention to<br> 
        people has a great deal to do with productivity”
        <p>- Tom Peters</p>
    </div>

    <div class="changetxt">
        ”If you deprive yourself of outsourcing and your competitors<br> do not, you are putting yourself out of business”
        <p>- Lee Kuan Yew</p>
    </div>

    <div class="changetxt">
        ”Focus on being  PRODUCTIVE<br>
        instead of busy”
        <p>- Tim Ferris</p>
    </div>
</div>

It is working perfect but I don't want to loop, There are 3 quotes, so as soon as it shows last (third) quote it should stop animation and no loop.

How can I achieve this?