Como passar dados de uma página para a outra com React?

Boa tarde!
Estou desenvolvendo um quiz e queria passar os dados da página de início tipo informações que o usuário irá digitar para a próxima página que já é do quiz. Desejo passar o campo nome para a página do quiz pra colocar “Welcome, Teste”. Quero passar o nome da página de QuestionCategory para a Question. Segue as imagens do código:
QuestionCategory.js
Questions.js

Javascript: recreating Array.from?

I came across this code for stripping Marketo forms of their included stylesheets. Let’s assume that the code author is a super senior engineer. Array.from() could have been used instead of defining arrayFrom (functionally at any rate), so why use the latter?

For my part I’m trying to understand the arrayFrom definition (first line of the codeblock):

  1. bind() sets this to the provided value, here [].slice (why?)
  2. call() allows us to call getSelection with the this value bound by bind.
  3. getSelection() returns a Selection object (or string in Firefox) of the selected text. This I’m unsure about.
    In its use, arrayFrom gets passed an array (or NodeList) of stylesheets and returns an array of the same stylesheets (a shallow copy thereof?) no differently than if Array.from were used, so the functional bit of bind and call must be to alter the this value in a desirable way. Not sure how that acts on [].slice though.

Anyone? I’m clearly missing something.

const arrayFrom = getSelection.call.bind([].slice);

// remove element styles from <form> and children
const styledEls = arrayFrom(formEl.querySelectorAll("[style]")).concat(
formEl
);

styledEls.forEach(function (el) {
     el.removeAttribute("style");
});

     
// create an array of all stylesheets in document
const styleSheets = arrayFrom(document.styleSheets);

// loop through stylesheets and check for ownerNode properties on each
styleSheets.forEach(function (ss) {
    if (
    //array of <link/> elements tied to stylesheets
    [mktoForms2BaseStyle, mktoForms2ThemeStyle].indexOf(ss.ownerNode) !=
      -1 ||
    formEl.contains(ss.ownerNode)
    ) {
      ss.disabled = true;
      } 
});

How To create dynamically select dropdown and pull data in it using json ajax function?

I want to know that for example I collected a json data like there were 4 arrays in it, I made them dropdown using js and also created select element from js itself and got the data pulled in those 4 select elements but I want that This select should also be created dynamically like if there are 6 arrays in the data, then 2 arrays should be created automatically, I do not have to create the select element again and again for each array, is it possible?

jQuery(document).ready(function($) {
$.ajax({
  type: 'GET',
  url: "/jwordpress/wp-admin/admin-ajax.php",
  data: {'action' : 'get_custom_filter'},
  dataType: 'json',
  success: function(data) {
        var jb_type = (data.data.job_type);
        var job_types_var = Object.values(jb_type);   
        var select_1 = $("<select></select>").attr("id", "filters_sub_1").attr("name", "Job Types");
        $.each(jb_type,function(index,jb_type){
        });  
        $("#filters").append(select_1);
            var $job_type_lists = $('#filters_sub_1'); 
            $('#filters_sub_1').append($('<option>', {
                text: 'Job Type'
            }));                
            $.each(job_types_var, function(i, job_types_var){
            $job_type_lists.append('<option value="'+JSON.stringify(job_types_var.name).replace(/"/g, "") +'">'+JSON.stringify(job_types_var.name).replace(/"/g, "") +'</option>');
        });
        console.log(select_1);
         

        var country_drop = (data.data.job_location);
        var countries_dropdown = Object.values(country_drop);   
        var select_2 = $("<select></select>").attr("id", "filters_sub_2").attr("name", "Job Location");
        $.each(country_drop,function(index,country_drop){
        });  
        $("#filters").append(select_2);
        var $country_lists = $('#filters_sub_2');
            $('#filters_sub_2').append($('<option>', {
                text: 'Job Location'
            }));
            $.each(countries_dropdown, function(i, countries_dropdown){
            $country_lists.append('<option value="'+JSON.stringify(countries_dropdown.name).replace(/"/g, "") +'">'+JSON.stringify(countries_dropdown.name).replace(/"/g, "") +'</option>');
            
        }); 
        console.log(select_2);

        
        var owner_drop = (data.data.owner);
        var owner_dropdown = Object.values(owner_drop);
        var select_3 = $("<select></select>").attr("id", "filters_sub_3").attr("name", "Owners");
        $.each(owner_drop,function(index,owner_drop){
        });  
        $("#filters").append(select_3);
        var $owner_lists = $('#filters_sub_3');
            $('#filters_sub_3').append($('<option>', {
                text: 'Owner'
            }));
            $.each(owner_dropdown, function(i, owner_dropdown){
            $owner_lists.append('<option value="'+JSON.stringify(owner_dropdown.name).replace(/"/g, "") +'">'+JSON.stringify(owner_dropdown.name).replace(/"/g, "") +'</option>');
        }); 
        
        
        var company_drop = (data.data.job_company);
        var company_dropdown = Object.values(company_drop);
        var select_4 = $("<select></select>").attr("id", "filters_sub_4").attr("name", "Company");
        $.each(company_drop,function(index,company_drop){
        });  
        $("#filters").append(select_4);
        var $company_lists = $('#filters_sub_4');
            $('#filters_sub_4').append($('<option>', {
                text: 'Company'
            }));
            $.each(company_dropdown, function(i, company_dropdown){
            $company_lists.append('<option value="'+JSON.stringify(company_dropdown.name).replace(/"/g, "") +'">'+JSON.stringify(company_dropdown.name).replace(/"/g, "") +'</option>');
        }); 
        
  }
});     
return false;

});

Capture a text from input and display on p class

i have an input:

<input class="input title mb-10" name="title" id="title" type="text" maxlength="60" placeholder="title" value="<?= htmlchars($Post->get("data.title")) ?>">

So i need to display this input here:

<a href="#"><p class="button-link-story">HERE</p></a>

How i can do it?

In Angular why will my Dynamic Tabs / Tab Panes work initially but not after update?

I am currently using version 3.4 of CoreUI for my Angular App and I am attempting to use their Tabs setup.

Currently it works fine if I populate the tabs oninit but if I update them it breaks. The entire purpose of being able to use this is to have a dynamic list of tabs and content in those tabs so I am at a loss for why this wouldn’t work.

I made a very dumbed down version below to show what I am trying. Note that the first instance of this._tabs works fine, after my await calls when I update to the second version it fails to display correctly.

HTML

<c-card>
  <c-card-header>
    Tabs <code><small>nav-underline</small></code>
  </c-card-header>
  <c-card-body>
    <c-tabset class="nav-underline nav-underline-primary">
      <c-tablist>
        <c-tab *ngFor="let tab of tabs"  >
          {{tab.header}}
        </c-tab>
      </c-tablist>
      <c-tab-content>
        <br>
        <c-tab-pane *ngFor="let tab of tabs">
          <p>
            {{tab.panel}}
          </p>
        </c-tab-pane>
      </c-tab-content>
    </c-tabset>
  </c-card-body>
</c-card>

Component

import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { DbService, DashCpResult, IssuerGroup } from '../../db.service';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  // Arrays
  DashCpResults: Array<DashCpResult>;

  private _setTab: number;
  get setTab() {
    return this._setTab;
  }
  set setTab(value: number) {
    this._setTab = value || 0;
  }

  private _tabs: any[] = [];

  public get tabs() {
    return this._tabs;
  }


  constructor(
    private DbService: DbService,
    private route: ActivatedRoute,
    private router: Router,
  ) {
    this.setTab = 0;
  }

  rungetDashCpResult(id) {
    return new Promise((resolve) => {
    this.DbService.getDashCpResult(id).subscribe(DashCpResults => this.DashCpResults = DashCpResults,
      (err) => { 
        console.log('ERROR: ' + JSON.stringify(err)); 
    },() => {
    resolve(1);
    });
    })
    }
    

  async ngOnInit() {
    this._tabs = [
      { header: 'Home', panel: 'Home'},
      { header: 'Home2', panel: 'Home2'},
      { header: 'Home3', panel: 'Home3'},
      { header: 'Home4', panel: 'Home4'}

    ];

    // Get Screen detail for Tabs
    try { await this.rungetDashCpResult(1); } catch (e) {console.log(e)}
    // Update Tabs for a test
    this._tabs = [
      { header: 'Home5', panel: 'Home5'},
      { header: 'Home6', panel: 'Home6'},
      { header: 'Home7', panel: 'Home7'},
      { header: 'Home8', panel: 'Home8'}

    ];
    }
  }

How can I pass an ID from selected table row to my AJAX function that fetching data

I wanted to pass the ID of the selected table row to my AJAX function and use it for my query

this is the code for my table row

<div class="container">

<h2 style="margin-top: 12px;" class="alert alert-success">Details</h2><br>
    <div class="row">
      <div class="col-12">
      <table class="table table-bordered" id="">
      <thead>
      <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Email</th>
      <td colspan="2">Action</td>
      </tr>
      </thead>
      <tbody id="users-crud">
      @foreach($merchants as $merchant)
      <tr id="user_id_{{ $merchant->id }}">
      <td>{{ $merchant->id}}</td>
      <td>{{ $merchant->first_name }}</td>
      <td>{{ $merchant->email }}</td>
     <td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a> 
     </td>
      </tr>
      @endforeach
      </tbody>
      </table>
      {{ $merchants->links() }}
      </div> 
    </div>
  </div>

upon click show ID should pass it to my AJAX function,
this is the code of the script

   <script type=text/javascript>
      $(document).ready(function() {
       });
    
       function getData(id){
      $('#myModal').modal('show');
          $.ajax({  //create an ajax request to display.php
          type: "GET",
       url: "getproducts/",
       // dataType: 'json',
        data: {id: id}, // This will be {id: "1234"}     
        success: function (data) {
       $("#id").html(data.id);
       $("#first_name").text(data.first_name);
       }
       });
    
      };
    
    </script>

And ID will be use for my query in my controller, this is my controller’s code, note that the number 1 in my where query is hard coded, I wanted to put the ID that I get from the selected table

public function getproducts()
{
    $merchants  = DB::table('merchants')
    ->select('merchants.*', 'product.product_name as product_names')
    ->join('product','product.id','=','merchants.id')
    // THE NUMBER 1 IS HARD CODED
    ->where('merchants.id', 1)
    ->paginate(8);
    return response()->json($test, 200);
}

Need to make browser back button go back to previous page root url sitewide on WordPress

I have a particular problem on a site that I’m working on and can’t seem to get things working on WordPress. I have a tab section of the site that uses # to function properly. I also have anchor links to these sections as well. Everything works great, but when I navigate off of the page and click the browser back button, I have to click through each # until I get to the root page. I realize that this is the normal browser behavior, but need to find a workaround if possible. I’ve tried all sorts of code, and could post some things I’ve tried but nothing is working thus far. Any help would be greatly appreciated.

Thanks so much

How to manage dynamically created bootstrap.Tooltip() with vanilla JS?

Hi I’m working on a multi-page registration system and I want to provide a tooltip (ALWAYS VISIBLE) for each indicator as shown in my image bellow.

screenshot 1

HOWEVER:

I have noticed that when I create my tooltips using the method below, it will only work with hover event. And when I create it with new bootstrap.Tooltip() it will work as intended as long as I call the .show() function as shown below in the code.

(FYI, the first tooltip shown in the image is actually the <span> and I’m hovering the mouse. The bootstrap.Tooltip() has style display: none only for blue indicator. So both <span> and bootstrap.Tooltip() overlap in case of display: block)

Something strange that I have also noticed is that when a tooltip is created via newbootstrap.Tooltip() a new <div> is created at the top of the page which will have the information of the <span> but will not take the id or className. It has it’s own id which is random on every page reload (e.g. tooltip768493, tooltip714418, tooltip9188236)

What I’m trying to figure out is how to set a default className or id on each of the bootstrap.Tooltip() so that I can change their title dynamically as shown below:

  • Blue – You are here
  • Red – Missing or Invalid
  • Green – Valid
  • Grey – Optional

Here is how I created the tooltip targets:

   //in a for loop create 6 spans to hold tooltips:

   //Indicator Progress Span (above bullet with text) 
   span = document.createElement("span");
   span.className = "indicator-tooltip-target";
   span.style.zIndex = "3";
   span.setAttribute("data-toggle","tooltip");
   span.setAttribute("data-original-title", "test");
function show_tooltips(){
    let tooltips_target = document.getElementsByClassName("indicator-tooltip-target");
    for(var i=0; i<tooltips_target.length; i++){
        let tooltip = new bootstrap.Tooltip(tooltips_target[i]);
        tooltip.show();
    }
}

$.ajax error. How to solve “Undefined array key “final_price”” in this situation?

If I just write echo $_POST['final_price']; it says “Undefined array key “final_price”” but if I put it in an isset() “if” statement nothing shows up. The URL is correct, the console.log returns the correct value so it is getting the variable value and supposedly sending it to the “kosarica.php” file but in the file itself it doesn’t work. Please help.

JS:

var $subtotal = 0;

$subtotal = parseInt($deal_price.text()) - parseInt(item_price);

$.ajax({url: "kosarica.php", type : 'post', data : { final_price : $subtotal}}).done(function(){console.log($subtotal);});

PHP:

if (isset($_POST['final_price'])){
   echo $_POST['final_price'];
}

Error: Warning: Undefined array key “final_price”

Oracle Cloud ERP – Document Downloading from a XSLT template report using javascript and SOAP

I am trying to create a SOAP call in javascript to query our cloud to return a document. This is to avoid using the standard Inquiry Reporting. Our Cloud uses Single Sign On and regular password login scenario won’t work for the general user. I looking for the appropriate syntax of a SOAP call against Oracle to download documents from the repository and the appropriate syntax to get the authorization token to send to the Cloud to allow for the SOAP call to execute. Currently I am getting a 401 error from a POST command but a GET call has a response. I am unsure whether I should be referencing oraclecloud.com/crmCommonBulkExport/BulkExportService?WSDL or oraclecloud.com/fscmService/ServiceCatalogService?wsdl. I have read some similar posts on this topic but clearly I am missing something. Any assistance or advice is appreciated. The outline of the code with some substitution is below and testing it through the browser console”.

//Organization instance remove replaced with your-instance

var url = “https://your-instance.oraclecloud.com/crmCommonBulkExport/BulkExportService?WSDL”;

var xhr = new XMLHttpRequest();

//Response is 401; recieve a repsonse with a GET

xhr.open(“POST”, url,true);

xhr.onreadystatechange = function () {

if (xhr.readyState === 4) {

console.log(xhr.status);

console.log(xhr.responseText);

}};

//SOAP call for attactments

var data = `<soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:typ=”http://xmlns.oracle.com/apps/crmCommon/bulkExport/bulkExportServiceV2/types/”>

soapenv:Body

<dsig:KeyInfo xmlns:dsig=”http://www.w3.org/2000/09/xmldsig#”>

</dsig:KeyInfo>

typ:getAttachmentsForBatch

typ:batchId300000024150497</typ:batchId>

</typ:getAttachmentsForBatch>

</soapenv:Body>

</soapenv:Envelope>`;

//regualr authorization causes issues because of SSO

//xhr.setRequestHeader(“Content-Type”, “text/xml”);

//SSO needed

xhr.setRequestHeader(‘Bearer’, ”);

xhr.send(data);

How to access the root component data from a child template in VueJs?

Is is possible to access this.$root from within a template in VueJs ?

Example:

<template>
    <v-card elevation="this.$root.$refs.report.cardElevation">
      Foo
    </v-card>
</template>

I know I can add a property in the data object and point that to $root.cardElevation, but since I’m going to have many components use this value I’d like to be able to access it directly from the template.

Read sound from webcam and send to Tesnor flow Js model

I have downloaded the Yamnet a Audio classification tensor flow model. i have the model.json file in my local system. I have to read the sound from the webcam and need to pass to the model so that it can classify what the sound is

currently i am sending the random noise. can some one help to read sound from the webcam or speaker of laptop and send to model to classify the sound ?

below is the code i have in java script which

const model = await tf.models.modelFromJSON(myModelJSON)
const waveform = tf.zeros([16000 * 3]);
  const [scores, embeddings, spectrogram] = model.predict(waveform);
  scores.print(verbose=true);  // shape [N, 521]
  embeddings.print(verbose=true);  // shape [N, 1024]
  spectrogram.print(verbose=true);  // shape [M, 64]
  // Find class with the top score when mean-aggregated across frames.
  scores.mean(axis=0).argMax().print(verbose=true);
  // Should print 494 corresponding to 'Silence' in YAMNet Class Map.