javascript

javascript – Database row is not deleting, AJAX, PHP error


I want to remove DB row data from HTML table. I have an HTML table where I have called all the database table values. I want to give a delete order option to the user. I have used a delete button for that. To do this, I am trying to use ajax and jquery with php delete query. But the issue is When I click on delete it just deletes the HTML row data. It should delete that particular id row from DB as well. I need your help. Please let me know what I have done wrong? I am very much new to ajax and jquery.

remove.php

<?php 
include "config.php";

$id = $_REQUEST['id'];

// Delete record
$query = "DELETE FROM mi_home_tv WHERE id='$id'";
mysqli_query($link,$query);

echo 1;

jquery+ajax
<script src="http://stackoverflow.com/jquery-3.0.0.js" type='text/javascript'></script>
<script type="text/javascript">
    $(document).ready(function(){

    // Delete 
    $('.delete').click(function(){
        var el = this;
        var id = this.id;
        var splitid = id.split("_");

        // Delete id
        var deleteid = splitid[1];

        // AJAX Request
        $.ajax({
            url: 'remove.php',
            type: 'POST',
            data: { id:deleteid },
            success: function(response){

                // Removing row from HTML Table
                $(el).closest('tr').css('background','tomato');
                $(el).closest('tr').fadeOut(800, function(){      
                    $(this).remove();
                });
            }
        });
    });
});
</script>

Button Code:

echo "<td> <span  id='del_<?php echo $id; ?>'  type='submit' class=' delete btn c-theme-btn c-btn-uppercase btn-xs  c-btn-square c-font-sm'>Delete</span> </td>";



لینک منبع

Javascript callback execute after user input on modal


I am writing a game, and I have a javascript function that calls a modal to get a dice roll so I need to stop execution of that function until the result of the dice roll. I looked into callbacks and promises but was unable to sort it out to get the functionality I need. Here is my code.

function docombat()
{
    getplayerroll("1d20","initiative")
}
function getplayerroll(dice,reason)
{
    $.ajax({
        url: "myurl",
        type:"post",
        data:{dice:dice,reason:reason},
        success: function(newHTML, textStatus, jqXHR) 
        {
            $(newHTML).appendTo('body').modal({
                escapeClose: false,
                clickClose: false,
                showClose: false
            });
        }
    });

    //something like wait for the dice to be rolled and keep going
}

And then the modal

    <div id="diceroll""></div>

modal js

 function after_roll(res) { diceroll.innerHTML = res; }

so i need something in the original function that waits for after_roll()



لینک منبع

Javascript – object loop and organizing data within HTML


var obj = {
    ۰: {
        "Shirts": 0,
        "Jeans": 1,
        "Brand": "Lorem ipsum"
    },
    ۱: {
        "Color": {
            "blue" : 1,
            "red" : 0
        },
        "Size": {
            "Man": {
                "small": 1,
                "medium": 0,
                "large": 0
            },
            "Women": {
                "small": 1,
                "medium": 1,
                "large": 1
            }
        }
    },
    ۲: {
        "Shipping": {
            "overNight": "$ 10",
            "۳ days": "$ 4"
        }
    },
    ۳: {
        "Stock": {
            "Man": [
                {
                    "green jeans": 13,
                    "green shirts": 17,
                    "green shoes": 21
                },
                {
                    "black jeans": 1,
                    "black shirts": 12,
                    "black shoes": 53
                }
            ],
            "Women": [
                {
                    "green jeans": 2,
                    "green shirts": 53,
                    "green shoes": 11
                },
                {
                    "black jeans": 6,
                    "black shirts": 22,
                    "black shoes": 29
                }
            ]
        }
    }
}

var dataEl = document.getElementById('data');

var getProperties = function (obj) {
  for (var property in obj) {

    if (!obj.hasOwnProperty(property)) continue;

    if (obj.hasOwnProperty(property) && obj[property] !== null) {

      if (obj[property].constructor == Object) {
      
        dataEl.innerHTML += '<div class="row title">' + property + '</div>';
        getProperties(obj[property])
        
      } else if (obj[property].constructor == Array) {
        dataEl.innerHTML += '<div class="row title">' + property + '</div>';
        
        for (var i = 0; i < obj[property].length; i++) {
          getProperties(obj[property][i]);
        }
        
      } else {
      
        dataEl.innerHTML += '<div class="row"><span>' + property +'</span>: ' + obj[property] + '</div>';
        
      }

    }
  }
}
//getProperties(obj);
#data,
#preview {
  display: block;
  width: 80%;
  font-size: 12px;
  font-family: Arial, Helvetica;
  padding: 10px;
}
#data .row,
#preview .row {
  display: inline-block;
  width: 100%;
  margin-bottom: 2px;
}
#data .row.title,
#preview .row.title {
  font-weight: bold;
  font-size: 14px;
}
#data .row.indent-1,
#preview .row.indent-1 {
  padding-left: 20px;
}
#data .row.indent-2,
#preview .row.indent-2 {
  padding-left: 40px;
}
<div id="data"></div>

<!-- This is how it should be structured -->
<div id="preview">

  <div class="row"><span>Shirts:</span>0</div>
  <div class="row"><span>Jeans:</span>1</div>
  <div class="row"><span>Brand:</span>Lorem ipsum</div>
  
  <div class="row title">Color</div>
  <div class="row indent-1"><span>blue:</span> 1</div>
  <div class="row indent-1"><span>red:</span> 0</div>
  
  <div class="row title">Size</div>
  <div class="row title indent-1">Man</div>
  <div class="row indent-2"><span>small:</span> 1</div>
  <div class="row indent-2"><span>medium:</span> 0</div>
  <div class="row indent-2"><span>large:</span> 0</div>
  <div class="row title indent-1">Women</div>
  <div class="row indent-2"><span>small:</span> 1</div>
  <div class="row indent-2"><span>medium:</span> 1</div>
  <div class="row indent-2"><span>large:</span> 1</div>
  
  <div class="row title">Shipping</div>
  <div class="row indent-1"><span>overNight:</span> $ 10</div>
  <div class="row indent-1"><span>3 days:</span> $ 4</div>
  
  <div class="row title">Stock</div>
  <div class="row title indent-1">Man</div>
  <div class="row indent-2"><span>green jeans:</span> 13</div>
  <div class="row indent-2"><span>green shirts:</span> 17</div>
  <div class="row indent-2"><span>green shoes:</span> 21</div>
  <div class="row indent-2"><span>black jeans:</span> 1</div>
  <div class="row indent-2"><span>black shirts:</span> 127</div>
  <div class="row indent-2"><span>black shoes:</span> 53</div>
  <div class="row title indent-1">Women</div>
  <div class="row indent-2"><span>green jeans:</span> 2</div>
  <div class="row indent-2"><span>green shirts:</span> 53</div>
  <div class="row indent-2"><span>green shoes:</span> 11</div>
  <div class="row indent-2"><span>black jeans:</span> 6</div>
  <div class="row indent-2"><span>black shirts:</span> 22</div>
  <div class="row indent-2"><span>black shoes:</span> 29</div>
  
</div>



لینک منبع

javascript – Full Calendar Jquery UI


I’m super bad at Javascript and am trying to implement the full calendar Jquery plugin. Found here: https://fullcalendar.io/

I thought the default theme looked pretty ugly so I decided that I would make a theme using the Jquery UI ThemeRoller. Found here: https://jqueryui.com/themeroller/

According to the documentation, FullCalendar says that it supports theme roller (jquery ui) but I’m not exactly sure how to implement it. I tried adding the JS and CSS I got from the theme roller into the page with the calendar and then doing themesystem: ‘jquery-ui’ in the init for the calendar but still nothing.

Any one know how to specifically make it use Jquery-ui?

Below is my init.js file for the calendar.

$(document).ready(function() {

$("<link rel='stylesheet' type='text/css' href='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.7.0/fullcalendar.min.css' />").appendTo("head");

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,basicWeek,basicDay'
    },
    navLinks: true,
    editable: true,
    eventLimit: true, 
    events: '/schedule/data',
    themesystem: 'jquery-ui',
    cache: true,
    eventStartEditable: false,
    eventStop: function(event, delta, revertFunc){
        console.log(event);
        event_data = {
                id: event.id,
                startDate: event.start, 
                endDate: event.end
        }; 

        console.log("Now event data"); 
        console.log(event_data);
        rep = $.ajax({
            url: '/schedule/data/update', 
            data: event_data, 
            type: 'PATCH'
        })
    },
    eventClick: function(calEvent, jsEvent, view) {
        window.location.href='/schedule/appointments/'+calEvent.id+'/detail';            
    }
});

});

I would love some help with figuring this out. Thank you!



لینک منبع

javascript – Highlighting a table row when using css hover


function HilightRowOnClick() {
    //alert($(row).closest('tr').index())

    $(document).ready(function () {
        $('tr').click(function () {
            //if (this.style.background == "" || this.style.background == "#badecc") {
            if (this.style.backgroundColor == "#badecc") {
                alert($("Color is normal?"));
                $(this).css('background', 'burlywood');
            }
            else {
                $(this).css('background', '#badecc');
                alert("Color is not normal?");
            }
        });
    });
}
.DBTable {
    width: 100%;
}


.DBToprow {
    font-size: 180%;
    font-weight: 600;
}


.DBTable td {
    font-size: 50%;
    padding: 7px;
}


.DBTable th {
    border-style: solid;
    border-width: 1px;
    padding: 7px;
}


.DBTable tr {
    background: #badecc;
    border-style: solid;
    border-width: 1px;
}

.DBTable tr:hover {
    background-color: burlywood;
}
<table class="DBTable">
    <tr class="DBToprow">
        <td></td>
        <td>
            @Html.DisplayNameFor(model => model.ClientID)
        </td>
        <td>
            @Html.DisplayNameFor(model => model.Active)
        </td>
        <td>
            @Html.DisplayNameFor(model => model.BankID)
        </td>
    </tr>

    @foreach (var item in Model)
    {
        <tr onclick="HilightRowOnClick()">
            <th>
                @Html.DisplayFor(modelItem => item.ClientID)
            </th>
            <th>
                @Html.DisplayFor(modelItem => item.Active)
            </th>
            <th>
                @Html.DisplayFor(modelItem => item.BankID)
            </th>
        </tr>
    }
</table>



لینک منبع

Upload 5gb file directly to azure blob storage via FineUploader in chunks. Can we do this in javascript?


I have 5gb file and I am uploading this file to azure blob storage via FineUploader but due to session or any other reason(not sure why) the functionality breaks. It smoothly uploads 2gb file. Is there any approach to achieve this? Can I directly give call to FineUploader through javascript and upload file to azure blob storage in chunks?



لینک منبع

javascript – Storing multiple values (and expiration dates) in one cookie


I created a method to store multiple values in separate cookies with a 60 day expiration date. Now I was told I need to store them in one cookie instead and am a little lost. From the research I have done I have decided to use JSON to store them. Can you tell me if I am doing it correctly?

Working Code:

    function setCookie(name, value, days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expiration = date.toUTCString();

      document.cookie = name + "=" + value + "; path=/; expires=" + expiration;
    }

    function storeValues(form) {
      setCookie("firstName", form.firstName.value, 60);
      setCookie("lastName", form.lastName.value, 60);
      setCookie("organization", form.organization.value, 60);
      setCookie("numberVolunteers", form.numberVolunteers.value, 60);
      setCookie("email", form.email.value, 60);
      setCookie("phone", form.phone.value, 60);
      setCookie("state", form.state.value, 60);
      return true;
    }

My Proposed Method:

   function storeValues(form)  {  
      setCookie("form", JSON.stringify(
        [
          {name: "lastName", value:form.lastName.value, expires:60},
          { name: "organization", value: form.organization.value, expires:60},
          { name: "numberVolunteers", value: form.numberVolunteers.value, expires:60},
          { name: "email", value: form.email.value, expires:60},
          { name: "phone", value: form.phone.value, expires:60},
          { name: "state", value: form.state.value, expires:60}
        ]
      ));
      return true;
    }



لینک منبع

javascript – Hide Filters with no result of combination | Isotope JS


I am creating an application using Isotope.js with checkbox combination filter. I am managing to get everything working using examples etc..

However I finding an issue how to hide certain filters which will give no results on the filter.

I have created a JSFiddle to demonstrate my example.

Filter options:

<div id="options">
  <div class="option-set" data-group="brand">
    <input type="checkbox" value=""        id="brand-all" class="all" checked /><label for="brand-all">all brands</label>
    <input type="checkbox" value=".brand1" id="brand1" /><label for="brand1">brand1</label>
    <input type="checkbox" value=".brand2" id="brand2" /><label for="brand2">brand2</label>
  </div>
  <div class="option-set" data-group="type">
    <input type="checkbox" value=""        id="type-all" class="all" checked /><label for="type-all">all types</label>
    <input type="checkbox" value=".type1" id="type1" /><label for="type1">type1</label>
    <input type="checkbox" value=".type2" id="type2" /><label for="type2">type2</label>
  </div>
</div>

Items:

<div id="container">
  <div class="item brand1 type1 red"></div>
  <div class="item brand1 type1 red"></div>  
  <div class="item brand1 type1 red"></div>  
  <div class="item brand2 type2 blue"></div>  
  <div class="item brand2 type2 blue"></div>  
  <div class="item brand2 type2 blue"></div>  
</div>

In my example I have two filters brands & types. If brand 1 is selected as a filter only type 1 of that brand is available so I would like to hide the type 2 checkbox and works vice versa if all is selected.

It should work in a scalable way for any category and not hardcoded categories.

I have tried already achieving this by triggering isotope itself on the filters but didn’t work. Also creating events on arrange complete, but still not managing to get the available categories from the filtered items.

Method on arrange items I tried using:

$$container.on( 'arrangeComplete', function( event, filteredItems ) {
  filteredItems.forEach(function(elementsData){
console.log($(elementsData.element).attr('class));
});
});

Can someone guide me to the correct solution as I’ve been hours trying different activations.



لینک منبع

javascript – Removing element from react tree using recursion


I am new to react and i am trying to create a dynamic tree with react using recursion, which basically gives me the ability to add and remove child nodes, i got the tree working and i am able add the child node, however i am facing issues with child node,

Approach i have taken is to pass a callback functions from parent to remove the child node, the parent maintains a list of all the children, so in remove i am passing the callback functions of the id of the child that was clicked

However i see that removal is working fine but the render is not proper irrespective of whichever child node is clicked only the last node is getting removed.

class ChildNode extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            obj: props.obj,
            idx: props.idx,
        };

        this.removeChildNode = this.removeChildNode.bind(this);
        console.log("in constructor");
        console.log(this.state);
    }

    addChildNode() {
        let oldObj = this.state.obj;
        oldObj.subQueries.push(
            {
                queryName: "Child Query",
                queryClause: "",
                subQueries: [],
            }
        );
        this.setState({obj: oldObj, idx: this.state.idx});
        console.log(this.state);

    };

    setQueryClause(event) {
        this.state.obj.queryClause = event.target.value;
        console.log(this.state);
    }

    removeChildNode(ix) {
        let removedObj = this.state.obj;
        removedObj.subQueries.splice(ix, 1);

        console.log(removedObj);
        this.setState({obj: removedObj, idx: this.state.idx})
        console.log(this.state);
    }

    render() {
        let my = this;
        let btn = null;

        if(undefined != this.props.parentRemoveNode) {
            btn = <button onClick={() => this.props.parentRemoveNode(this.state.idx)}>Remove Node</button>
        } else {
            btn = <button>Remove Node</button>
        }

        console.log(this.state);

        return (
            <div>
                <h5>
                    {this.state.obj.queryName} - {this.state.idx} &nbsp;
                    {btn}
                </h5>
                <input type="text" name="queryClause" onChange={this.setQueryClause.bind(this)}/> &nbsp;
                <button onClick={this.addChildNode.bind(this)}>Add Node</button>

                <ol>
                    {
                        this.state.obj.subQueries.map(function (node, index) {
                            console.log(node);
                            return <li key={index}>
                                <ChildNode obj={node} idx={index} parentRemoveNode = {my.removeChildNode}/>
                            </li>
                        })
                    }
                </ol>
            </div>
        )
    }
}

enter image description here



لینک منبع

javascript – Auto select dependent dropdown with jquery json


I have a dynamic and dependent dropdown below. The parent dropdown fetch the active ID from database but how to auto select the child dropdown value that is stored in the same table and set it to “selected”?

Parent Dropdown (php pdo):

<?php

$keynr = new Keynr($db);
$stmt = $keynr->read();

// put them in a select drop-down
echo "<select id='key_dropdown' class='form-control' name='keyindex' required>";
    echo "<option value=''>Wähle Schlüssel...</option>";

    while ($row_content = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row_content);

         // current category of the product must be selected
        **if($position->keyindex==$id){
            echo "<option value='$id' selected>";**
        }else{
            echo "<option value='$id'>";
        }

        echo "$keynr - $content</option>";
    }
      echo "</select>"; 

?>

Child dropdown (Jquery):

<select id='repairkey_dropdown' name='keyindex2' class='form-control' required>
   <option value=''>Wähle Schadensbild ....</option>
</select>

<script>
$(document).ready(function(){
  //pageload
  $(function () {
    $("select#key_dropdown").change();
});
// detect change of dropdown
$("#key_dropdown").change(function(){

    // get id of selected team 
    var key_id=$(this).find(':selected').val();

        // set json url
        var json_url="keys_json.php?key_id=" + key_id;

        // get json data
        jQuery.getJSON(json_url, function(data){

            $("#repairkey_dropdown").html("");
            $("#repairkey_dropdown").append("<option value='0'>Wähle Schadensbild ....</option>");

            jQuery.each(data, function(key, val){
                $("#repairkey_dropdown").append("<option value='" + val.key_repairkey2 + "'>" + val.content + "</option>")
            });

        });
});
});
</script>

Child dropdown (Jquery Json):

<?php 
// set json headers
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');

$key_id=isset($_GET['key_id']) ? $_GET['key_id'] : die('Auftrags ID nicht gefunden.');

include_once '../config/database.php';
include_once '../objects/repairkeys2.php';

$database = new Database();
$db = $database->getConnection();

$repairkey2 = new Repairkey2($db);
$repairkey2->keyindex=$key_id;

$stmt = $repairkey2->readOneAdminDropDown();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($results);
?>

I´m not sure what is the best way to do this.

Thanks! 🙂



لینک منبع