"include" in javascript or something similar to reduce code size

Asked

Viewed 706 times

0

I have a Dashboard where when some value or information is updated, automatically the other values are recalculated without refresh.

An example is that when adding an expense to the table, it needs to recalculate all expenses, update the BD, update various other information like total expenses, balance... Anyway I already have all this, but for example when one edits only the product, I need to put all that code again, because everything needs to be updated. My JS this very big pq are many actions on the same page.

I researched and saw that something similar to the inlude of PHP could not be used in this case, but it would have to do something like put all the information update code inside a type function

$(function() { });

This is an excerpt of two distinct strokes that start different but if ajax returns no error, both need to do the same function "update all data".

$(document).on('click','#addCom', function (){
var data        = $("#dataAddCom").val();
var funcionario = $("#funcionarioAddCom").val();
var valor       = $("#valorRecAddCom").val();
var idJob       = $("#idJob").html();

if(data == '' || funcionario == '' || valor == ''){
    $.notify({
        message: 'Preencha todos os campos!',
        },{
        // settings
        element: 'body',
        position: null,
        type: "danger",
        placement: {
            from: "top",
            align: "center"
        }
    });
}else{  
    $.ajax({
        type : 'POST',
        url  : '../conexao/addDespesa.php',
        data : { cadastraCom:"1", data: data, funcionario: funcionario, valor: valor, idJob: idJob },
        dataType: 'json',
        success :  function(retorno){
            if(retorno.erro == 0){

           **Varias funções que atualizam os dados**

           }else{
           }
    });
}
});

Another action (edit).

$(document).on('click','#boxCom .save-edit', function (){
var idCom       = $(this).closest('.center').siblings('.id-despesa').text();
var data        = $(this).closest('.center').siblings('.data-despesa');
var funcionario = $(this).closest('.center').siblings('.funcionario-despesa');
var valorRep    = $(this).closest('.center').siblings('.valor-rep');

var idJob      = $("#idJob").html();

var dataText = data.find('.temp input').val();
var funcionarioText = funcionario.find('.temp select').val();
var valorRepText = valorRep.find('.temp input').val();

var boxOrig = $(this).closest('.actions').find('.orig');
var boxTemp = $(this).closest('.actions').find('.temp');

if(dataText == '' || funcionarioText == '' || valorRepText == ''){
    $.notify({
        message: 'Preencha todos os campos!',
        },{
        // settings
        element: 'body',
        position: null,
        type: "danger",
        placement: {
            from: "top",
            align: "center"
        }
    });
}else{
    //alert(idCom+dataText+funcionarioText+valorRepText)
    $.ajax({
        type : 'POST',
        url  : '../conexao/addDespesa.php',
        data : { editCom:"1", dataEdit: dataText, funcionario: funcionarioText, valorRep: valorRepText, idJob: idJob, id: idCom },
        dataType: 'json',
        success :  function(retorno){
            if(retorno.erro == 0){

           **Varias funções que atualizam os dados (novamente)**

           }else{
           }
    });
}
});

Most of the codes I use for the update are like this.

var valorComSoma = 0;
$('#boxCom .valor-rep').each(function (i) {   
                    valorComSoma = parseFloat($(this).text().replace(/[^0-9]/g, '')) + valorComSoma;});

$("#boxValorTotal1").text(numberParaDolar(valorDespesaSoma/100));

$(function () {
    var totalRec = 0;
    $('#boxCom tr').each(function () {
        var funcDespesa = $(this).find('.funcionario-despesa > p').text().trim();
        if (funcDespesa === 'Cesar') {
            totalRec += parseInt($(this).find('.valor-rep > p').text().replace(/[^0-9]/g, '').trim());
        }
    });
    if (resultadoFinalSoma > lucroEsperado) {
        var saldoTotal = lucroEsperado;
    } else {
        var saldoTotal = resultadoFinalSoma;
    }
    var comisao = saldoTotal * 0.45;
    var saldo = comisao - totalRec;
    $("#saldoComCesar").text(numberParaDolar(saldo / 100));
});

It would have to put all the update code inside a function, and then just call it?

  • Are you only using HTML and Javascript? There is no language on the Server side?

  • I’m using PHP too.

  • So, you can write all this Javascript code in PHP and make a call to the ones you use. I’ll put the example in the answer.

  • actually there is javascript include too but it’s with jquery, and I like using https://api.jquery.com/jquery.getscript/

1 answer

1


The code in question you can write in PHP and then include the Script in others who will use the functions.

Example: funcoes.php

<?php
var valorComSoma = 0;
$('#boxCom .valor-rep').each(function (i) {   
                    valorComSoma = parseFloat($(this).text().replace(/[^0-9]/g, '')) + valorComSoma;});

$("#boxValorTotal1").text(numberParaDolar(valorDespesaSoma/100));

$(function () {
    var totalRec = 0;
    $('#boxCom tr').each(function () {
        var funcDespesa = $(this).find('.funcionario-despesa > p').text().trim();
        if (funcDespesa === 'Cesar') {
            totalRec += parseInt($(this).find('.valor-rep > p').text().replace(/[^0-9]/g, '').trim());
        }
    });
    if (resultadoFinalSoma > lucroEsperado) {
        var saldoTotal = lucroEsperado;
    } else {
        var saldoTotal = resultadoFinalSoma;
    }
    var comisao = saldoTotal * 0.45;
    var saldo = comisao - totalRec;
    $("#saldoComCesar").text(numberParaDolar(saldo / 100));
});
?>

So to call the script use the following code:

<?php require_once 'funcoes.php'; ?>
  • Intendi, if I had the direct script on the page would not be a problem, because I did a small test. But in case I have all my script on a JS sheet on which I bring to my page by <script src=".. /js/functionsTrabalhos.js" type="text/javascript"></script> e la na folha JS esse require_once funciona não funciona!

  • Well, you could then separate the code that is most used and put it in another file ../js/js2.js and the call you can make so: var js2 = document.createElement('script'); js2.src = '../js/js2.js'; document.head.appendChild(js2);

  • It worked now Carlos, thank you very much!

  • Not at all, friend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.