Javascript – Save data in JSON file with AJAX

I have a problem saving data to a file. I use AJAX to take data from the createUser.js file.

let $ = require('jquery');
let fs = require("fs");

$(document).ready(function () {
  $("#myBTN").click(function (e) {
    e.preventDefault();
    $.ajax("../../pages/createUser.js", {
      type: "GET",
      data:{
        domain: $("#domenaJ").val(),
        name: $("#nameJ").val(),
        email: $("#emailJ").val()
      },
      success: function (data) {
        fs.writeFileSync();
        alert("success");
      },
      error: function () {
        alert("NOK");
      },
    });
  });
});

I tried to use fs.writeFileSync () / fs.wirteFile even though I use think functions in AJAX browser and scream that fs.writeFileSync () / fs.wirteFile is not a function, maybe it only works for node js. I need to save AJAX data in a new file called tmpI.json. Does anyone have a role or something that helps me?
Thanks for your help.

javascript – How to develop a functional flatlist to respond to native supporting crud operations

I am developing an admin app for Woocommerce and am new to responding natively and using React-Navigation and Expo.

To update a view that consists of an unstructured list of product list data retrieved on the network when the product data changes by editing the product screen through the rest of the API. Any help would be appreciated.

Here is the summary of my previous code structure.

Main Navigator (App.js)
- Tab Navigator -> Product Stack Navigator, Order Stack Navigator
- - Product Stack Navigator -> Product List Screen, Single Product Screen, Edit Product Screen
- -  Order Stack Navigator -> Order List Screen, Order Details Screen

Here is my product list

import React, { Component } from 'react';
import { StyleSheet, Text, View, FlatList, Image, ActivityIndicator, TouchableOpacity } from 'react-native';
import * as SecureStore from 'expo-secure-store';

export default class ProductsList extends Component {

    static navigationOptions = {
        headerTitle: 'Products',
        headerStyle: {
            backgroundColor: '#96588a',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            fontWeight: 'bold',
        },
    };

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: (),
            page: 1,
            seed: 1,
            error: null,
            refreshing: false,
            base_url: null,
            c_key: null,
            c_secret: null,
        };
    }

    async componentDidMount() {
        await this.getCredentials();
        this.fetchProductList();
    }

    getCredentials = async () => {
        const credentials = await SecureStore.getItemAsync('credentials');
        const credentialsJson = JSON.parse(credentials)
        this.setState({
            base_url: credentialsJson.base_url,
            c_key: credentialsJson.c_key,
            c_secret: credentialsJson.c_secret,
        })
    }

    fetchProductList = () => {
        const { base_url, c_key, c_secret, page } = this.state;
        const url = `${base_url}/wp-json/wc/v3/products?per_page=20&page=${page}&consumer_key=${c_key}&consumer_secret=${c_secret}`;
        this.setState({ loading: true });
        console.log(url);
        setTimeout(() => {
            fetch(url).then((response) => response.json())
                .then((responseJson) => {
                    this.setState({
                        data: (...this.state.data, ...responseJson),
                        error: responseJson.error || null,
                        loading: false,
                        refreshing: false
                    });
                    this.state.data.forEach(item => console.log(`${item.sku}: ${item.stock_quantity}`))
                    console.log('end')
                }).catch((error) => {
                    this.setState({
                        error,
                        loading: false,
                        refreshing: false
                    })
                });
        }, 1500);
    };

    renderListSeparator = () => {
        return (
            
        )
    }

    renderListFooter = () => {
        if (!this.state.loading) return null;

        return (
            
                
            
        )
    }

    handleRefresh = () => {
        this.setState(
            {
                page: 1,
                refreshing: true,
                seed: this.state.seed + 1,
            },
            () => {
                this.fetchProductList();
            }
        )
    }

    handleLoadMore = () => {
        this.setState(
            {
                page: this.state.page + 1,
            },
            () => {
                this.fetchProductList();
            }
        )
    }

    render() {
        return (
             item.id.toString()}
                refreshing={this.state.refreshing}
                extraData={this.state}
                onRefresh={this.handleRefresh}
                onEndReached={this.handleLoadMore}
                onEndReachedThreshold={100}
                ItemSeparatorComponent={this.renderListSeparator}
                ListFooterComponent={this.renderListFooter}
                renderItem={({ item }) =>
                     {
                        this.props.navigation.navigate('SingleProduct', {
                            productId: item.id,
                            productName: item.name,
                            productData: item,
                            base_url: this.state.base_url,
                            c_key: this.state.c_key,
                            c_secret: this.state.c_secret
                        });
                    }}>
                        
                            
                                 { this.props.source = require('../../../assets/images/blank_product.png') }}
                                    style={{ height: 115, width: 115 }} resizeMode='contain' />
                            
                            
                                
                                    {item.name}
                                    SKU: {item.sku}
                                    Price: {item.price}
                                    Stock Status:  {item.stock_status}
                                    Stock: {item.stock_quantity}
                                    Status: {item.status}
                                
                            
                        
                    
                }
            />
        );
    }
}

const styles = StyleSheet.create({
    titleText: {
        fontSize: 20,
        fontWeight: 'bold',
    }
});

Here is my product detail screen:

import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, ScrollView, ActivityIndicator } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
export default class SingleProduct extends Component {
    constructor(props) {
        super(props);
        this.state = { loading: false };
        productData = this.props.navigation.getParam('productData');
        base_url = this.props.navigation.getParam('base_url');
        c_key = this.props.navigation.getParam('c_key');
        c_secret = this.props.navigation.getParam('c_secret');
    }

    static navigationOptions = ({ navigation }) => {
        return {
            title: navigation.getParam('productName', 'Product'),
            headerStyle: {
                backgroundColor: '#96588a',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
                fontWeight: 'bold',
            },
        };
    };

   render() {
        if (this.state.loading) {
            return (
                
                    
                
            )
        }

        return (
            
                
                    
                        {this.getProductImages()}
                    
                    
                        {productData.name}
                        Sku: {productData.sku}
                        Slug: {productData.slug}
                        Total Ordered: {productData.total_sales}
                    
                
                 {
                        this.props.navigation.navigate('EditProduct', {
                            productId: productData.id,
                            productName: productData.name,
                            productData: productData,
                            base_url: base_url,
                            c_key: c_key,
                            c_secret: c_secret
                        });
                    }}
                >
                    
                
            
        );
    }
}

const styles = StyleSheet.create({
    section: {
        marginTop: 15,
        marginLeft: 15,
        marginRight: 15
    },
    titleText: {
        fontSize: 20,
        fontWeight: 'bold',
    },
});

Here is my EditProduct:

import React, { Component } from 'react';
import { StyleSheet, Text, View, Switch, KeyboardAvoidingView, TouchableOpacity, Image, ScrollView, ActivityIndicator, TextInput, Picker, Button } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';

export default class EditProduct extends Component {
    constructor(props) {
        super(props);
        productData = this.props.navigation.getParam('productData');
        base_url = this.props.navigation.getParam('base_url');
        c_key = this.props.navigation.getParam('c_key');
        c_secret = this.props.navigation.getParam('c_secret');
        this.state = {
            loading: false,
            error: null,
            name: productData.name,
            sku: productData.sku,
            regularPrice: productData.regular_price,
            salePrice: productData.sale_price,
            dateOnSaleFrom: productData.date_on_sale_from,
            showDateOnSaleFrom: false,
            dateOnSaleTo: productData.date_on_sale_to,
            showDateOnSaleTo: false,
            manageStock: productData.manage_stock,
            stockStatus: productData.stock_status,
            stockQuantity: productData.stock_quantity,
            weight: productData.weight,
            length: productData.dimensions.length,
            width: productData.dimensions.width,
            height: productData.dimensions.height,
            productType: productData.type,
            virtual: productData.virtual,
            downloadable: productData.downloadable,
        };
    }

    static navigationOptions = ({ navigation }) => {
        return {
            title: 'Edit Product',
            headerStyle: {
                backgroundColor: '#96588a',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
                fontWeight: 'bold',
            },
        };
    };

    render() {
        if (this.state.loading) {
            return (
                
                    
                
            )
        }

        return (
            
                
                    
                        Product Name
                        
                    
                    
                        Pricing
                        
                            
                                Regular Price: 
                            
                            
                                
                            
                        
                        
                            
                                Sale Price: 
                            
                            
                                
                            
                        
                        
                            
                                Sale Date From: 
                            
                            
                                
                                    {this.state.dateOnSaleFrom ? new Date(this.state.dateOnSaleFrom).toDateString() : 'Select Date'}
                                
                                {this.state.showDateOnSaleFrom && }
                            
                        
                        
                            
                                Sale Date To: 
                            
                            
                                
                                    {this.state.dateOnSaleTo ? new Date(this.state.dateOnSaleTo).toDateString() : 'Select Date'}
                                
                                {this.state.showDateOnSaleTo && }
                            
                        
                    
                    
                        Inventory
                        
                            
                                Manage Stock: 
                            
                            
                                
                            
                        
                        
                            
                                Stock Status: 
                            
                            
                                
                                    
                                    
                                    
                                
                            
                        
                        
                            
                                Stock Quantity: 
                            
                            
                                
                            
                        
                    
                    
                        Shipping
                        
                            
                                Weight: 
                            
                            
                                
                            
                        
                        
                            
                                Length: 
                            
                            
                                
                            
                        
                        
                            
                                Width: 
                            
                            
                                
                            
                        
                        
                            
                                Height: 
                            
                            
                                
                            
                        
                    
                    
                        Type
                        
                            
                                Product Type: 
                            
                            
                                
                                    
                                    
                                    
                                    
                                
                            
                        
                        
                            
                                Virtual: 
                            
                            
                                
                            
                        
                        
                            
                                Downloadable: 
                            
                            
                                
                            
                        
                    
                
                

Javascript – About Bootstrap 4 JS main file

Hey hai i am new to bootstrap 4 so i have this question. I downloaded a Bootstrap 4 web template that contained some Javascript Libraries like (lib / bootstrap / js / bootstrap.bundle.min.js) (lib / easing / easing.min.js) (lib / superfish / superfish.min.js)
(lib / venobox / venobox.min.js) (lib / owlcarousel / owl.carousel.min.js). It also has the same libraries in CSS also (lib / owlcarousel / assets / owl.carousel.min.css) (lib / venobox / venobox.css). Why there are two libraries in two different languagesjs and CSS,

And I went through the code and some classes were declared with it I would and were called CSS With
#, And declare a class in I would means only in Javascript However, there is no JavaScript code that I downloaded in this web template.

Why this?

How do I use async / await with Javascript classes?

I created a class with a method asyncHowever, when I instantiate this class and run the method, an error is generated in my console. Follow the sample code and error below:

JS

class MyClass{
  async method(){
    const x = await 10; // exemplo meramente ilustrativo
    return x
  }
}

const instance = new MyClass()

const result = await instance.method()

console.log(result)

Error:

const result = await instance.method()
               ^^^^^

SyntaxError: await is only valid in async function

Does async / await work differently when it comes to methods of an object? Or am I doing something wrong?

Javascript – If you click on a certain Th, you open a modal

I have a grid that shows some fields:

@Html.DisplayNameFor(model => model.DataCriacao) @Html.DisplayNameFor(model => model.FuncionarioCadastro) @Html.DisplayNameFor(model => model.Descricao) Ações

I try that when the user clicks on the text of the description (not in the title, in the content (@ Html.DisplayNameFor (model => model.Descricao)), a window (modal? Container?) Is opened that is complete Displays description.

I created this window like this:


How do I open the window when the user clicks on the description?

Javascript – I am trying to create a task list app with Jquery, but I cannot delete any newly added entries in the list

$("#add").css("color","blue");

$("#add").on("click",function(){
	
	$("input").fadeToggle();
})


$("#input").keypress(function(event){
	console.log("jjj");
	if(event.which===13){
		console.log("new entry...")
		var tr=$(this).val();
		$("table").append(''+tr+'');
		$(this).val("");
	}
})

$("td button").click(function(){
	console.log("deleting...");
	$(this).parent().parent().remove();
})



	To Do list
	
	
	



	
To Do list
Do something
helloo

Render javascript array as table

I have the following object:

"menu": {
        "Bebidas": {
            "Cervejas": {
                "1": {
                    "item": "Cerveja EISENBAHN Pilsen Long Neck Garrafa 355ml",
                    "valor": 4.29
                },
                "2": {
                    "item": "Cerveja Petra Origem Puro Malte 355ml",
                    "valor": 3.54
                },
                "3": {
                    "item": "Cerveja STELLA ARTOIS Garrafa 550ml",
                    "valor": 9.50
                },
                "4": {
                    "item": "Cerveja Skol Garrafa 600ml",
                    "valor": 9.50
                },
                "5": {
                    "item": "Cerveja Brahma Garrafa 600ml",
                    "valor": 9.50
                },
                "6": {
                    "item": "Cerveja Itaipava Garrafa 600ml",
                    "valor": 9.50
                },
                "7": {
                    "item": "Balde c/3 Brahma Garrafa 600ml",
                    "valor": 28.50
                },
                "8": {
                    "item": "Balde c/3 Skol Garrafa 600ml",
                    "valor": 28.50
                },
                "9": {
                    "item": "Balde c/3 Itaipava Garrafa 600ml",
                    "valor": 28.50
                }
            },
            "Sucos": {
                "Laranja": {
                    "1": {
                        "item": "Suco de laranja copo com 300ml",
                        "valor": 7
                    }
                },
                "Morango": {
                    "1": {
                        "item": "Suco de morango com leite 300ml",
                        "valor": 7
                    },
                    "2": {
                        "item": "Suco de morango com água 300ml",
                        "valor": 6.50
                    }
                },
                "Maracuja": {
                    "1": {
                        "item": "Suco de maracujá com leite",
                        "valor": 7
                    },
                    "2": {
                        "item": "Suco de maracujá com água 300ml",
                        "valor": 6.50
                    }
                }
            }
        },
        "Porções": {
            "Fritas": {
                "1": {
                    "item": "Fritas c/ bacon",
                    "valor":23.00
                },
                "2": {
                    "item": "Fritas c/ cheedar",
                    "valor":23.00
                },
                "3": {
                    "item": "Fritas",
                    "valor":19.00
                }
            },
            "Frango": {
                "1": {
                    "item": "Frango a passarinho (Média)",
                    "valor": 26.50
                },
                "2": {
                    "item": "Frango a passarinho (Grande)",
                    "valor": 29.50
                },
                "3": {
                    "item": "Iscas de frango (Média)",
                    "valor": 29.50
                },
                "4": {
                    "item": "Iscas de frango (Grande)",
                    "valor": 29.50
                }

            }
        },
        "Destilados": {
            "Caipirinhas": {
                "1": {
                    "item": "Caipirinha de morango",
                    "valor": 16
                },
                "2": {
                    "item": "Caipirinha de kiwi",
                    "valor": 16
                }
            },
            "Whisky": {
                "1": {
                    "item": "Whisky Johnnie Walker Red (Dose)",
                    "valor": 14
                },
                "2": {
                    "item": "Whisky Johnnie Walker Black (Dose)",
                    "valor": 14
                }
            }
        }
    }

I would like to render this data in a table in HTML, where the "type" (beer, portions, etc.) should be the table header and the elements corresponding to the rows.

Thanks in advance.

Javascript – React Native does not work

Hey guys, blz?

I want to build applications using React Native. I have already installed the necessary programs to start them. However, when I issue the cmd "npx react-native run-android" command, it loads for a long time and does not give me a message on the Android screen (& # 39; Welcome to React Native & # 39;), I don't know whether there has to be a mistake or something. I have already researched but found nothing.

Below I placed the photo of my screen that is only on it and does not change anything.

Insert picture description here

Javascript function to get the ratio of the number of positive, negative and zero values ​​within an array in relation to its length

I wrote a function that checks the ratio of the number of positive, negative, and zero values ​​within an array to length.
The code I wrote is the following:

function plusMinus(arr) {

    /**first I declare 3 variables to store the positive, negative and null elements inside them*/

    let numPositive = ();
    let numNegative = ();
    let numZero = ();

    /**then I write a loop that will check whether 
    the elements of the input array are positive, negative or null,
    e.g. if the element(i) is positive, then the array 
    numPositive pushes the positive element(i) inside it, 
    and so on for the rest of the numbers and arrays*/

    for (let i=0; i0){
            numPositive.push(arr(i)>0);
        }else if (arr(i)<0){
            numNegative.push(arr(i)<0);
        }else{
            numZero.push(arr(i)==0)
        }
    }

    /**finally, the ratios are given as a result of 
    the length of the pushed arrays and the length of the original array*/

    console.log(numPositive.length/arr.length);
    console.log(numNegative.length/arr.length);
    console.log(numZero.length/arr.length);
}

I would like to receive feedback on why my code's logic is not working.

Javascript – Microsoft Bot Framework speech recognition web chat integration

const { createCognitiveServicesSpeechServicesPonyfillFactory, createDirectLine, renderWebChat } = window.WebChat;

const styleOptions = {
		botAvatarInitials: 'Bot',
		userAvatarInitials: 'You'
		};


         renderWebChat(
            {
               directLine: createDirectLine({
                  secret: 'FFFFFFFFFFFFFFFF'
               }),
			   
	     language: 'de-DE',
	     webSpeechPonyfillFactory: await createSpeechRecognitionOnlyPonyfillFactory({
	     region: 'westeurope',
	     subscriptionKey: 'FFFFFFFFFFFFFFFFFFFFFF'
	     }),
			   	      
	      styleOptions
  	     
            },
            document.getElementById('webchat')
	);
         
document.querySelector('#webchat > *').focus();