¿ como puedo mandar un json de php a javascript?

Tengo un problema a la hora de llamar una funcion de php desdde javascript y es que en la funcion de php retorno un json pero a la hora de tratar de ver el json me manda 0 como resultado.

esa es la funcion de php que estoy creando para añadir todos los posts a json

   function get_alliances() {
     $colaboracion_terms = $_POST('colaboracion');
     $paged = 1;
     $posts_per_page = -1;

     $args = array(
       'post_type' => array('empresa'),
       'posts_per_page' => $posts_per_page,
       'paged' => $paged,
       'order' => 'ASC',
       'orderby' => 'date',
      );


     $args('tax_query') = array(
       'relation' => 'AND',
        addTaxQuery('colaboracion', $colaboracion_terms),
      );

      $ajaxposts = new WP_Query( $args );

      $json_response = json_encode($ajaxposts -> get_posts());

      return $json_response;
   }

y este es el codigo que utilizo en javascript:

function getAllColaboratorsMobile() {
    form = new FormData();
    form.append("action", "get_aliances_mobile");
    getAlliances(form);
}

function getAlliances(data) {
    $.ajax({
        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
        data: data,
        cache:false,
        processData: false,
        contentType: false,
        success: function (data) {
            console.log(data);
        },
        error: function (MLHttpRequest, textStatus, errorThrown) {
            console.log("ERROR", errorThrown);
        }
    });
}

ahora lo que me retorna es:

introducir la descripción de la imagen aquí

javascript – Fire HTML input-event only once when more than one character is typed

I’m creating an input field where some data should be fetched (by AJAX) and displayed every time the user enters data into that field. However, if the user types several characters, say he types “test” to get all records who contain the string “test”, it would not be necessary to do 4 queries after every character pressed, but one query after he stopped typing. I can think of several solutions with a global variable where I check if the same event has been fired again, but is there a really elegant way to do this? Maybe check if there is something in the keyboard buffer and only proceed if it is empty? Or is there an event that is only fired once the keyboard buffer is empty and all characters are in the input field?

javascript – Is there any global variable i can use for mobile phone?

Im trying to prevent default on form refresh on mobile phone. It works fine for my mac laptop but on my laptop it still resubmits the form.

This code works for Mac because i can use the “window” global variable, is there a global variable or code that would work for my mobile phone? Anything that pertains to a mobile phone?

      if ( window.history.replaceState ) {

         window.history.replaceState( null, null, window.location.href );
     }

Problemas ao enviar os dados do checkbox pro javascript

O programa tem que mostrar a variação do preço da moeda selecionada em um determinado período de tempo, mas ele não está pegando os dados do checkbox. Quando eu seleciono uma moeda e aperto o botão de “mostrar” ele mostra uma moeda aleatória, não necessariamente a que eu selecionei. Além disso, ele mostra somente uma moeda, quando eu preciso que mostre todas que forem selecionadas.

            function converterData(date){
                // converte um string de yyyy-mm-dd para mm-dd-yyyy
                const (ano, mes, dia) = date.split("-")
                return (mes, dia, ano).join("-")
            }
            
            // Mostra gráfico na tela
            function draw($dados){
                const tagDestino = document.getElementById('grafico');
                google.charts.load('current', {'packages':('corechart')});
                google.charts.setOnLoadCallback(drawChart);

                function drawChart() {
                var data = google.visualization.arrayToDataTable($dados);
                var options = {
                    title: 'Cotação',
                    curveType: 'function',
                    legend: { position: 'bottom' }
                };

                var chart = new google.visualization.LineChart(tagDestino);

                chart.draw(data, options);
                }
            }
            
            function drawCharts(dados){

                draw((("data", "cotacao"),...dados))
            }
            
            const convertToCharts = json => json.map(objeto => (objeto.dataHoraCotacao, objeto.cotacaoVenda))

            var servidor = 'https://dadosabertos.bcb.gov.br/dataset/taxas-de-cambio-todos-os-boletins-diarios';
            
            function print(){
                {document.getElementById('sobre').innerHTML = 'Sobre nós: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';}
            }
            
            function print1(){
                {document.getElementById('ajuda').innerHTML = 'FAQ: Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.';}
            }
            
            function replaceUrl(dataInicial,dataFinal,moeda){
                return `https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoMoedaPeriodo(moeda=@moeda,dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?@moeda='${moeda}'&@dataInicial='${dataInicial}'&@dataFinalCotacao='${dataFinal}'&$top=10000&$skip=0&$format=json&$select=cotacaoVenda,dataHoraCotacao`
            }

            function fetchData(dataInicial,dataFinal,moeda){
            const url = replaceUrl(dataInicial,dataFinal,moeda)

                console.log(url)

                const dados = fetch(url)
                .then(res => res.json())
                .then(dados => {
                    const dadosFiltrados = convertToCharts(dados.value)
                    drawCharts(dadosFiltrados)
                })
            
            }
            
            function execute(){


                const dataInicial = document.getElementById("dateIni").value
                const dataFinal = document.getElementById("dateFim").value
                
                console.log(dataInicial,dataFinal)

                fetchData(converterData(dataInicial),converterData(dataFinal),'USD')
                fetchData(converterData(dataInicial),converterData(dataFinal),'EUR')
                fetchData(converterData(dataInicial),converterData(dataFinal),'GBP')

            }

            const botao = document.getElementById("submit")
            botao.addEventListener("click",execute)
        </script>

javascript – Recorrer respuesta laravel con jquery y valir si existe valor dentro

quisiera por favor me orientaran sobre la siguiente situación…creo algo estoy haciendo mal.

Estoy en laravel 8

Controlador :

    public function index(){
    $permisos = Permission::all();
    return view('vista.index', compact('permisos'));
}

Mi vista.blade.php :

<script>
$(document).ready(function () {
    jobs = @json($permisos);//Recibo la variable desde laravel
    console.log(jobs);
    console.log(jobs.includes('permiso_modulo_editar"')); //Validar que el valor enviado exista en el array proviente de laravel
});
</script>

La respuesta al mostrar lo que trae la variable $permisos desde el controlador :

introducir la descripción de la imagen aquí

La respuesta del “includes(‘permiso_modulo_editar’)” para validar si existe o no dentro :

introducir la descripción de la imagen aquí

En resumen, necesito enviar la variable $permisos desde el controlador a mi index.blade.php y en la sección < script> con jquery validar si un valor cualquiera existe en su interior.

Agradecere su ayuda, gracias.

javascript – The file uploads well to the folder but problem is : the name of the file which is in the folder is different from the one saved in the DB

enter image description here 1. This is my model

const mongoose = require('mongoose')
let TicketSchema = new mongoose.Schema({
     _id: String,
    ticketTitre:  String,
    ticketCategorie: String,
    ticketDescription: String,
    ticketImage:{
        data: Buffer,
        contentType: String
    }
})
module.exports = mongoose.model('Ticket', TicketSchema)
  1. Here is my index

    const boom = require(‘boom’)
    const { nanoid } = require(“nanoid”);
    const idLength = 2

//Get Data Models

const Ticket = require(‘./Ticket’)

const fastify = require('fastify')({
    logger: true
}),
    mongoose = require('mongoose'),
    fs = require('fs'),
    path = require('path'),
    fileUpload = require('fastify-file-upload'),
    fastifyStatic = require('fastify-static'),
    cors = require('fastify-cors');

fastify.register(fastifyStatic, {
    root: path.join(__dirname, 'public')
});

fastify.register(fileUpload);

// Connect to DB
mongoose.connect('mongodb://localhost:27017/bdfiles', { useNewUrlParser: true })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.log(err))

fastify.post('/uploadd', function (req, reply) {
    // contains text field together with files
    //console.log(req.raw.body); 
    
    let ticketTitre = req.body.ticketTitre;
    let ticketCategorie = req.body.ticketCategorie;
    let ticketDescription = req.body.ticketDescription;
    //let ticketImage = req.raw.files('myImage').name;
    let ticketImage =  getPath('uploads', getRandomFileName());
    
   // console.log(ticketTitre,ticketCategorie,ticketDescription,ticketImage)
  //let tickett = { ticketTitre,ticketCategorie,ticketDescription,ticketImage}
    
    // return response to client
    //reply.header('Location', 'success.html').code(303).send();
    // (!) stream file to disk just for example, use it only if needed
    const imageBuffer = req.raw.files('myImage').data;
    //console.log(imageBuffer);
    const fileName = getPath('uploads', getRandomFileName());
    const stream = fs.createWriteStream(fileName);
    stream.once('open', function (fd) {
        stream.write(imageBuffer);
        stream.end();
    });
    
    /*var tickett = {
        ticketTitre: req.body.ticketTitre,
        ticketCategorie: req.body.ticketCategorie,
        ticketDescription: req.body.ticketDescription,
        ticketImage : {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'image/png'
        }
    }
    console.log(tickett)*/

    try {
        //req.raw.body
        const ticket = new Ticket({ticketTitre,ticketCategorie,ticketDescription,fileName})
        //const ticket = new Ticket({ticket})
        ticket._id = nanoid(idLength)
        return ticket.save()
      } catch (err) {
        throw boom.boomify(err)
      }
});

// Run the server!
const start = async () => {
    try {
        await fastify.listen(3000)
        fastify.log.info(`server listening on ${fastify.server.address().port}`)
    } catch (err) {
        fastify.log.error(err)
        process.exit(1)
    }
}

start()

function getRandomFileName() {
    return 'file' + String(parseInt(Math.random() * 10000)) + '.png';
}

function getPath(...parts) {
    return path.join(__dirname, ...parts);
}

regular languages – Add more button not working for my javascript code

regular languages – Add more button not working for my javascript code – Computer Science Stack Exchange

javascript – Unobtrusive client validation only firing on first property in collection

I’m wrote a custom ValidationAttribute that also implements IClientValidatable so that I can perform client-side validation using the Jquery.Unobtrusive library.

The issue I have is that even though I have multiple items in the EditLeadViewMode.AssociatedUsers collection, the GetClientValidationRules method only fires once, for the first item in the collectio and only the first item on the form is validated on the client. I can’t figure out why it won’t fire/validate for all of the items in my collection.

Sample HTML from the form. You can see that the data-val-requiredassignedto attribute is not set on the second box

<select id="AssociatedUsers(1).UserId" name="AssociatedUsers(1).UserId" class="form-control valid" data-val-requiredassignedto="ErrorMessage" aria-describedby="AssociatedUsers(1).UserId-error" aria-invalid="false"><option value="">-- Assign To --</option>
<option selected="selected" value="2">A.Carlie Predovic</option>
<option value="4">A.Earline Pfeffer</option>
<option value="10">F.Dorris Dare</option>
<option value="7">I.Alexandrea Hane</option>
<option value="8">I.Alexandrea Rogahn</option>
<option value="6">I.Heber Greenfelder</option>
<option value="9">I.Maeve Koepp</option>
</select>


<select id="AssociatedUsers(2).UserId" name="AssociatedUsers(2).UserId" class="form-control" ><option value="">-- Assign To --</option>
<option value="2">A.Carlie Predovic</option>
<option value="4">A.Earline Pfeffer</option>
<option value="5">A.Jarrod Breitenberg</option>
<option selected="selected" value="3">A.Sheridan Maggio</option>
<option value="10">F.Dorris Dare</option>
</select>

ViewModel bound to the view

public sealed class EditLeadViewModel : IHelperSetup
    {
        public EditLeadViewModel()
        {
        }

        public IEnumerable<UserInLeadRole> AssociatedUsers { get; set; }
    }

public class UserInLeadRole
    {
        (AssignToUserValidationAttribute)
        public int? UserId { get; set; }
    }

Custom Attribute

 public class AssignToUserValidationAttribute : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //Server side validation here
        }
        
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new List<ModelClientValidationRule>
            { 
                new ModelClientValidationRule{
                    ValidationType = "requiredassignedto",
                    ErrorMessage = "This field is required"
                }
            };

        }
    }

Javascript for wiring up my custom unobtrusive adapter

 function addRule(name, params, ruleFn)
    {
        $.validator.addMethod(name, ruleFn);
        $.validator.unobtrusive.adapters.add(name, params,
            function (options)
            {
                options.rules(name) = options.params;
                options.messages(name) = options.message;
            });
    }
   
    addRule("requiredassignedto",(),
        function (value, el, params) {
            ///Client side validation logic here
        });

})(jQuery);

I can’t find any documentation saying that a custom validator will only fire once on a collection, but I’m obviously missing something.

javascript – JS script fetching GitHub API for personal website

I’ve built a quite simple personal website, everything is in a single file because it is very straightforward, but I think the JS script could be better structured. All it does is fetch some repos from the GitHub API and displays them in a horrible format.

This is it (index.html):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta
      name="description"
      content="The successful warrior is the average man, with laser-like focus."
    />
    <title>Mauricio Robayo</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <style>
      :root {
        font-size: 14px;
      }
      * {
        margin: 0;
        color: gainsboro;
      }
      body {
        font-family: "IBM Plex Mono", monospace;
        background-color: darkblue;
        padding: 0.5rem;
      }
      h1,
      h2,
      h4 {
        font-size: 1rem;
      }
      h1 {
        margin-bottom: 2rem;
      }
      h2 {
        font-weight: 400;
      }
      h4 {
        margin-top: 1rem;
      }
      ul {
        list-style: none;
        list-style-position: inside;
        padding-left: 0rem;
      }
      .error,
      .error a {
        color: red;
      }
      section {
        margin: 2rem 0;
      }
      .repo-loader {
        margin-right: 0.5rem;
      }
      .meta {
        color: darkgray;
      }
      .repo-header > *:not(:last-child) {
        margin-right: 1rem;
      }
      @media screen and (min-width: 768px) {
        :root {
          font-size: 16px;
        }
        body {
          padding: 1rem;
        }
        .repo-header {
          display: flex;
          align-items: flex-end;
        }
      }
    </style>
  </head>
  <body>
    <h1>Mauricio Robayo</h1>
    <ul>
      <li>
        <a
          href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#114;&#102;&#109;&#97;&#106;&#111;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;"
          >&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#114;&#102;&#109;&#97;&#106;&#111;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a
        >
      </li>
      <li>
        <a href="https://www.linkedin.com/in/mauriciorobayo"
          >https://www.linkedin.com/in/mauriciorobayo</a
        >
      </li>
    </ul>
    <section id="recent-projects"></section>
    <section id="starred-projects"></section>
    <footer>
      <p>No frameworks were harmed in the making of this site.</p>
      <p>Analytics and bloatware free.</p>
      <p>
        Updated:
        <a href="https://youtu.be/dQw4w9WgXcQ?autoplay=1">27 July 1987</a>.
      </p>
    </footer>
    <script>
      loadProjects(document.getElementById("recent-projects"), "updated", 3, (
        "language",
        "updated_at",
      ));
      loadProjects(document.getElementById("starred-projects"), "stars", 3, (
        "language",
        "stargazers_count",
      ));

      function loadProjects(projectsContainer, sort, limit, meta) {
        const url = `https://api.github.com/search/repositories?q=user:MauricioRobayo&sort=${sort}&per_page=${limit}`;
        const projectsTitle = document.createElement("h2");
        const projectsBody = document.createElement("div");
        const loader = document.createElement("span");
        const link = document.createElement("a");
        const cacheStatus = document.createElement("p");
        const cacheExpirationTime = document.createElement("p");
        const cacheKey = `projects-${sort}`;

        projectsBody.classList.add("projects-body");
        loader.classList.add("repo-loader");
        link.href = url;
        link.textContent = url;

        const loaderSymbols = ("\", "|", "/", "—");
        let i = 0;
        loader.textContent = loaderSymbols(i % loaderSymbols.length);
        const interval = setInterval(() => {
          i++;
          loader.textContent = loaderSymbols(i % loaderSymbols.length);
        }, 500);

        const cache = JSON.parse(localStorage.getItem(cacheKey));

        projectsTitle.append(
          loader,
          "Fetching ",
          link,
          cacheStatus,
          cacheExpirationTime
        );
        projectsContainer.append(projectsTitle, projectsBody);

        if (cache?.expirationTime > Date.now()) {
          cacheStatus.textContent = "localStorage cache hit";
          cacheExpirationTime.textContent = `Expires: ${cache.expirationTime}`;
          loadContent({ repos: cache.repos, projectsBody, loader, meta });
          clearInterval(interval);
        } else {
          cacheStatus.textContent = "localStorage cache miss";
          fetch(url, {
            headers: {
              accept: "application/vnd.github.v3+json",
            },
          })
            .then((response) => {
              if (!response.ok) {
                throw new Error(
                  `${response.status ? response.status : ""} ${
                    response.statusText ? response.statusText : ""
                  }`
                );
              }

              const rateLimitElements = Array.from(response.headers)
                .filter(((key)) => key.toLowerCase().startsWith("x-ratelimit"))
                .map((header) => {
                  const headerElement = document.createElement("p");
                  headerElement.textContent = header.join(": ");
                  return headerElement;
                });
              projectsBody.append(...rateLimitElements);

              return response.json();
            })
            .then(({ items: repos }) => {
              localStorage.setItem(
                cacheKey,
                JSON.stringify({
                  repos,
                  expirationTime: Date.now() + 60 * 60 * 1000,
                })
              );
              loadContent({ repos, projectsBody, loader, meta });
            })
            .catch((err) => {
              loader.textContent = "✗";
              projectsContainer.append(err);
              projectsContainer.classList.add("error");
            })
            .finally(() => {
              clearInterval(interval);
            });
        }
      }

      function loadContent({ repos, projectsBody, loader, meta }) {
        const reposContainers = repos.map(
          ({
            name,
            description,
            html_url,
            language,
            stargazers_count,
            updated_at,
          }) => {
            const repoContainer = document.createElement("div");
            const metaFields = { language, stargazers_count, updated_at };
            repoContainer.innerHTML = `
        <div class="repo-header">
          <h4><a href="${html_url}">${name}</a></h4>
          ${buildMeta(
            Object.fromEntries(
              Object.entries(metaFields).filter(((key)) => meta.includes(key))
            )
          )}
          </div>
          <div class="repo-body">
            <p>${description ? description : ""}</p>
          </div>
        `;
            return repoContainer;
          }
        );
        loader.textContent = "✔";
        projectsBody.append(...reposContainers);
      }

      function buildMeta(meta) {
        const rtf1 = new Intl.RelativeTimeFormat("en", { style: "narrow" });

        return Object.entries(meta)
          .map(((key, value)) => {
            if (key === "updated_at") {
              const updatedDate = new Date(value);
              const millisecondsDiff = updatedDate.getTime() - Date.now();
              const daysDiff = Math.floor(
                millisecondsDiff / 1000 / 60 / 60 / 24
              );
              const relativeTime = rtf1.format(daysDiff, "day");
              return `<span class="meta">updated ${relativeTime}</span>`;
            }
            if (key === "stargazers_count") {
              return `<span class="meta">${value} stars</span>`;
            }
            return `<span class="meta">${value}</span>`;
          })
          .join("");
      }
    </script>
  </body>
</html>

I would appreciate any input on the JS script to make it more readable, clean, and maintainable, althought any feedback regarding the CSS and the HTML (better structure, semantic markup, accessibility, etc) would also be great. Thanks in advance!

javascript – Resetar/esvaziar campo de input file no react

const InputFile = ({
  customerDocument,
  clearErrors,
  InputProps,
  register,
  setValue,
  disabled,
  setError,
  index,
  ...props
}) => {
  const (loading, setLoading) = useState(false);
  const name = `document.(${index}).content`;
  const type = `document.(${index}).type`;

  function onLoading() {
    setLoading((old) => !old);
  }

  async function handleFiles({ target }) {
    
    var file = target.files(0);
    
    if (file) {
      register(name);
      const fileSize = Math.round(file.size / 1024);
      
      if (fileSize > 1532) {
        setError(name, {
          type: 'manual',
          message: 'Arquivo máximo 1.5mb',
        });
        setValue(name, '');
        
      } else {
        var value = await toBase64(file, onLoading);
        setValue(type, customerDocument.id);
        setValue(name, value);
        clearErrors(name);
        alert(target.value)               
      }
    }
  }

  return (
    <Input
      {...props}
      name={name}
      type="file"
      onChange={handleFiles}
      onClick={(event)=> {
       
        event.target.value = null;
      }}
      disabled={disabled || loading}
      label={customerDocument.nome}
      InputProps={{
        ...InputProps,
        endAdornment: (
          <Box padding="0 10px 0 0">
            <Publish color="primary" />
          </Box>
        ),
      }}
    />
  );
};

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies 5000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Buy Cheap Private Proxies; Best Quality USA Private Proxies