Api call in Next JS

Reading the documentation of NextJs i noticed that this framework has this feature:

function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

So, this getServerSideProps allows to make http requests using SSR approach.
Question: It is correct if i will say that SSR requests are available only for get requests? I say this because only this function allows us to make SSR requests and i can not imagine how to make a POST request using NEXT JS, like the user submit a form and want to send on back-end, so how in this case to use getServerSideProps? Also, it is correct that NEXTJs allows us to make SSR requests only within pages but not components?

code debugger:the Array.split() function split ‘foo-the’ to [‘the’] but not [‘foo’,’the’]

let see line 81,the value of words is ‘foo-the’

enter image description here

and step next see line 69,split ‘foot-the’ with ‘-‘ ,it turns out ‘the’

enter image description here

the problem comes from when solving the leetcode algorithm question
description :
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.

You can return the answer in any order.

full code as follows:

 var s = "barfoofoobarthefoobarman"

var words = ["bar", "foo", "the"]
var arr = []
var position = []

function dfs(index, temp, words) {

    var wordsP = words.split('-')

    if (wordsP.length) {
       temp = temp.concat(wordsP[index])
        wordsP.splice(index, 1)
    }
    if (!wordsP.length) {
        arr.push(temp)
        return;

    }

    for (var i = 0; i < words.length; i++) {
        dfs(i, temp, wordsP.join('-'))
    }
}

for (k = 0; k < words.length; k++) {
    dfs(k, '', words.join('-'))
}
//
arr.forEach((item) => {
    if (s.indexOf(item) != -1) {
        position.push(s.indexOf(item))
    }

})

Url from webview in react native

I want to know the URL everytime it changes in webview. I searched online a lot. And according to that, I have done these changes. But it is still not working.

What am I doing wrong here. Why its not working.

It only logs for the first time. or it works when I click some other button on the screen.
What am I missing?

import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';

const initialUrl = 'https://www.youtube.com/';
let url = '';

class App extends Component {

  state = {
    url: initialUrl,
  };

  onNavigationStateChange = navState => {
    console.log("navstate=== ",navState)
    if (url!==navState.url) { 
      url = navState.url;
      alert(url);
      this.setState({
        url: url
      })
    }
  };

  render() {
    const { url } = this.state;
    const injectedJs = `
      var linkElements = document.getElementsByTagName("a");
        
      linkElements[0].addEventListener("click", function() {
        window.postMessage("addAccountSuccess?token=abc1234");
      });
      
      linkElements[1].addEventListener("click", function() {
        window.postMessage("addAccountError");
    `;
    return (
      <View style={{paddingTop: 24, flex: 1}}>
        <Text style={{backgroundColor: 'black', color: 'white'}}>{ url }</Text>
        <WebView
          style={{ flex: 1}}
          source={{
            uri: initialUrl,
          }}
          injectedJavaScript={injectedJs}
          startInLoadingState
          scalesPageToFit
          javaScriptEnabledAndroid={true}
          javaScriptEnabled={true}
          domStorageEnabled
          startInLoadingState={false}
          onNavigationStateChange={this.onNavigationStateChange.bind(this)}
          onMessage={event => {
            alert('MESSAGE >>>>' + event.nativeEvent.data);
          }}
          onLoadStart={() => {
            console.log("LOAD START ");
          }}
          onLoadEnd={() => {
            console.log('LOAD END');
          }}
          onError={err => {
            console.log('ERROR ');
            console.log(err);
          }}
        />
      </View>
    );
  }
}

export default App;

Angular loading icon from material Registery is not preloaded

I have registered some svg’s in app.component

public static MAT_ICONS_TO_REGISTOR: { name: string, url: string }[] = [
    {name: 'galaxy-icon', url: '../assets/imgs/galaxy.svg'},
    {name: 'sources-icon', url: '../assets/imgs/camera_in.svg'}
 ];  



AppComponent.MAT_ICONS_TO_REGISTOR.forEach(icon => {
      this.matIconRegistry.addSvgIcon(icon.name,
        this.domSanitizer.bypassSecurityTrustResourceUrl(icon.url));
    });

But its not loaded on component init, ex:

  <div *ngIf="!isApproval">
            <mat-icon  svgIcon="broom"
                      (click)="onResubmitAction()">
            </mat-icon>
</div> 

In this case when the condition becomes true a get request will be sent to get the icon from assets (‘http://localhost:4200/assets/imgs/broom.svg’) but it should load it on component init.

How do I fetch login data from PHP script to my MainActivity?

This is my PHP script:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

    $con=mysqli_connect($server,$username,$pass);
    $connection=mysqli_select_db($con,$database);

    $sql="SELECT * FROM `electric_database_users` WHERE 
    `User name/no`='".$_POST["username"]."' AND `Password`='".$_POST["password"]."'";
    $result = $con->query($sql);
    if ($result->num_rows > 0)
        echo "login found";
    else
        echo "Invalid login";

    $con->close();
 ?>

In javascript, I could fetch the data using $ajax call:

$.ajax({
    url: '/login_screen/backend.php',
    type: 'POST',
    data: { "input": "sign in",
          "username":  username,
          "password": password},
    success: function(response) {
        if(response=="login found")
            //Login successful
    },
    complete: function() {}
  });

Now I want to implement the same logic from my android app i.e., I want to fetch the login details from my backend.php. Is there something equivalent to $ajax call in android?

  empno=(EditText) findViewById(R.id.empno);
  pass=(EditText) findViewById(R.id.pass);
  login=(Button) findViewById(R.id.login);

  login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

             //how do I proceed here?
        }
  });       

Jquery GET Function Returning Previous Result

I’m running into a rather strange problem. When the webpage loads, I automatically run a jQuery GET request on an internal PHP script that essentially prints a JSON output from a backend application.

jQuery

$.get(urls.validateSession, function(data){

     console.log(data); //For debugging
     var response = JSON.parse(data);

     //Do more things with returned data

});

PHP

<?php

    include 'include/backend.php';
    
    //Send POST request to backend application
    $response = sendPostRequest($urls->session->validate, json_encode($defaultRequest));

    /* sendPostRequest Function Definition */
    /*
    function sendPostRequest($url, $data){
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        
        return $response;
    }
    */

    echo $response;

?>

This works as expected in my local xampp server, and will print a JSON output to the console similar to the following:

{
   "status":"SUCCESS",
   "time":"02-21-2022 02:14:03",
   etc...
}

Though when I run this same code on a remote apache server, instead of jQuery running the GET request each time the webpage loads and writing the received data to the console, jQuery will not run the GET request again and write the data received from the previous GET request to the console. Almost like the previous result of the GET request was cached and used again for the subsequent request.

I know jQuery is not running the GET request each time the page is reloaded because the “time” field in the JSON output always stays the same. As well, I do not see subsequent requests reaching the backend application. So jQuery is not bothering to make a new GET request to fetch new data, and is just using the previous result.

Though when I force refresh the webpage (Shift + F5), this seems to force jQuery to run the GET request again, and the new expected JSON output with an updated timestamp is written to the console.

Any ideas about what could be happening here?

Angular 13 build not creating polyfills-es5.js file

After trying to migrate form Angular 9 to 13, ng build –configuration production is not creating the polyfills-es5.js file which I need for IE 11.

I tried below things

Updated tsconfig.json file to target to es5

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "module": "es2020",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

Updated polyfills.ts files

 * BROWSER POLYFILLS
 */
import 'core-js';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js';  // Run `npm install --save classlist.js`.

I also read somewhere to update the browserslist file, but I am not able to find browserslist file in my project folder.

What can really be used as an alternative to setInterval in C#

This page will not work properly because of the while loop, but I must use C# to update the information to achieve the operation of the page, is there any good advice to provide?
My question

I tried this way, and it did get the results I wanted, but I was looking for other ways than refreshing the page to re-read the latest data in the database.

<meta http-equiv="refresh" content="3">

Prevent Defaults prevents whole document from been clicked

On my web site i listen for clicks on a href and swap my html using ajax using the code below

$(document).on('click','a', function (e){
e.preventDefault();
$.ajax({})
.........
})

but the prevent default prevents me from clicking any other thing on the page until the ajax complete.
I am listening to the click on tags while referencing the document as root because if the ajax swaps the content, using just and listening to events on that won’t be called because of the changes done by swapping the dom.
What can be done to fix this behavior. Thanks

How to send the data from the script to HTML page?

I am using Firebase to get the data

code:

const admin = require('firebase-admin');
const serviceAccount = require("C:/Users/santo/Downloads/bestmpos-firebase-adminsdk.json");

admin.initializeApp({
 credential: admin.credential.cert(serviceAccount)
});

let fs = admin.firestore();
let auth = admin.auth();

const listAllUsers = async (nextPageToken) => {
  try {
    let result = await auth.listUsers(100, nextPageToken);
    result.users.forEach((userRecord) => {
      start(userRecord.toJSON())
    });
    if (result.pageToken) {
      listAllUsers(result.pageToken);
    }
  } catch(ex) {
      console.log('Exception listing users:', ex.message);
  }
}

async function first(){
    await listAllUsers();
}
first();

async function start (object){
  const info = await fs.collection('users').doc(object.uid).get();
  if (!info.exists) {
    console.log('No document');
   } else {
    console.table([info.data()]);
   }
} 

but I want to send data console.log(info.data()) to HTML page to simply show information,

How can I do that, I don’t want to use react or any other
can someone help me?
and I also is this Nodejs or plain javascript?

Compare 2 arrays and find an attribute’s value from one array to another

I have 2 arrays mentioned below.

const arr1 = [{ Id: "a153O000001mjD1QAI", Document_ID__c: 176767 }];


const arr2 = [
  {
    classification: "Scientific Response",
    core_san_localization_translation: ["No"],
    core_san_verbal_only: "false",
    id: "176767",
    major_version_number: "1",
    minor_version_number: "0",
    name: "Advance Search Doc_General Information",
    response_type: ["General"],
    size: 70953,
    subtype: "Local",
    title: "Advance Search Doc_General Information",
    type: "Medical Information",
  },

  {
    classification: "Scientific Response",
    core_san_localization_translation: ["No"],
    core_san_verbal_only: "false",
    id: "127462",
    major_version_number: "1",
    minor_version_number: "0",
    name: "APPROVAL verdict APPROVED FOR USE",
    response_type: ["Administration"],
    size: 1362339,
    subtype: "Local",
    title: "ahsdjhsahdasld",
    type: "Medical Information",
  },

  {
    classification: "Scientific Response",
    core_san_localization_translation: ["No"],
    core_san_verbal_only: "false",
    id: "127461",
    major_version_number: "2",
    minor_version_number: "0",
    name: "APPROVAL verdict APPROVED ,MINOR CHANGES",
    response_type: ["Administration"],
    size: 1362339,
    subtype: "Local",
    title: "ahsdjhsahdasld",
    type: "Medical Information",
  },

  {
    classification: "Scientific Response",
    core_san_answer: "Dosage",
    core_san_localization_translation: ["No"],
    core_san_verbal_only: "false",
    id: "176776",
    major_version_number: "1",
    minor_version_number: "0",
    name: "General Info Test 2",
    response_type: ["Pharmacokinetics and Pharmacodynamics"],
    size: 25432,
    subtype: "Local",
    title: "General Info Test 2",
    type: "Medical Information",
  },
];

I want to search the value of attribute ‘Document_ID__c’ from arr1 in arr2 and if it matches ‘176767’ on any element in arr2,
just create a new array and store that element.

For e.g my desired output is

const finalarray = [
  {
    classification: "Scientific Response",
    core_san_localization_translation: ["No"],
    core_san_verbal_only: "false",
    id: "176767",
    major_version_number: "1",
    minor_version_number: "0",
    name: "Advance Search Doc_General Information",
    response_type: ["General"],
    size: 70953,
    subtype: "Local",
    title: "Advance Search Doc_General Information",
    type: "Medical Information",
  },
];

Please help me on this.

Random word generator never prints fourth word in array – Javascript [duplicate]

I have three random word generators on the same page. One prints an adjective, one a verb, and one a noun upon clicking their respective buttons. If two of the arrays have three words, and one array has four words, why wont the fourth word in the third array every print?

<form>
  <div id="displayAdjective"></div>
  <input type="button" value="display adjective" onclick="randomAdjective()" class="wordFormButton">
</form>
<form>
  <div id="displayVerb"></div>
  <input type="button" value="display verb" onclick="randomVerb()" class="wordFormButton">
</form>
<form>
  <div id="displayNoun"></div>
  <input type="button" value="display noun" onclick="randomNoun()" class="wordFormButton">
</form>

I’m unsure why the 4th word in the nouns array never prints.

adjectives = ["adjectiveOne", "adjectiveTwo", "adjectiveThree"];

verbs = ["verbOne", "verbTwo", "verbThree"];

nouns = ["nounOne", "nounTwo", "nounThree", "nounFour"];

function randomAdjectiveAlt() {
  var randomAdjective = Math.floor(Math.random() * adjectives.length);
  document.getElementById('displayAdjective').innerHTML = adjectives[randomAdjective];
}

function randomVerbAlt() {
  var randomVerb = Math.floor(Math.random() * adjectives.length);
  document.getElementById('displayVerb').innerHTML = verbs[randomVerb];
}

function randomNounAlt() {
  var randomNoun = Math.floor(Math.random() * adjectives.length);
  document.getElementById('displayNoun').innerHTML = nouns[randomNoun];
}

Here’s a link to the jsfiddle showing the full example.

how to save multiple products in a single run

i have this issue
trying to save de Order(detalle products) from my Sale, i don’t know how to do it

class Sale(models.Model):
    sale_id = models.IntegerField(primary_key=True)
    cli = models.ForeignKey(Clientes ,on_delete=models.CASCADE,null=True)
    date_joined = models.DateField(default=datetime.now)
    subtotal = models.DecimalField(default=0.00, max_digits=9, decimal_places=2)
    iva = models.DecimalField(default=0.00, max_digits=9, decimal_places=2)
    total = models.DecimalField(default=0.00, max_digits=9, decimal_places=2)

class Order (models.Model):
    order_id = models.AutoField(primary_key=True)
    orden = models.IntegerField()
    sale_id = models.ForeignKey(Sale ,on_delete=models.CASCADE,null=True)
    codigo_producto = models.IntegerField()
    precio = models.IntegerField()
    cantidad = models.IntegerField()
above you can see my to models and here is how i called in my views

    def mod_venta(request,orden_actual=0):
    if request.session.get("codigo_usuario"):
        listaorder=Order.objects.all()
        listatabla=producto.objects.all()
        listacliente=Clientes.objects.all()
        if request.method=="GET":
            return validar(request, "venta.html",{"listaorder":listaorder,"listacliente":listacliente,"listatabla":listatabla})
        if request.method=="POST":
            if orden_actual==0:
                venta_nueva=Order(order_id=request.POST.get('orden_actual'),
                    codigo_producto=request.POST.get('codigo'),
                    precio=request.POST.get('precio'),
                    cantidad=request.POST.get('canti'))
                venta_nueva.save()

        return redirect("../venta/0")     
    else:
        return redirect("login")

and only try to save with a form, only saving one element in the “OrderDetalle”, (i only work with for a month ) so I wanted to know how I could do to bring all the sales data in orders

Why does the position of where you add to a return value of a recursive function matter?

I’m trying to figure out why the following returns 10 correctly:

    function recurSum(n) {
      if (n <= 1)
        return n;
      return n + recurSum(n - 1);
    }
    console.log(recurSum(4)) //output 10

but when you add “n” after the recursive call in the return, you get the wrong result. The following returns 6 incorrectly

    function recurSum(n) {
      if (n <= 1)
        return n;
      return recurSum(n - 1) + n;
    }
    console.log(recurSum(4)) //output 6

Why does this happen?