Javascript sum form fields with decimal values

I have a function that sums a bunch of total fields on a page. It could be one field or many. The number could be different every time. It is working correctly but not summing the two decimal places.

So for this list of numbers:

312.69
39.00

It outputs 351 instead of 351.69

Any ideas why this is based on the following code?

settotal() {
this.totalTarget.value = Number(this.qtyTarget.value * this.costTarget.value).toFixed(2)
var arr = document.getElementsByName('total');
var tot=0;
var totf=0;
for(var i=0;i<arr.length;i++){
    if(parseInt(arr[i].value))
        tot += parseInt(arr[i].value);
        totf = (Math.round(tot * 100) / 100).toFixed(2);

}
document.getElementById('invoice_net_amount').value = totf;

}

.replace() not working for escaping back slashes in JavaScript for Google Tag Manager

I’m trying to dynamically populate schema into my company’s blog posts. Most things work just fine, but URLs, for some reason, have escape characters behind each /. Examples are denoted by ‘**’ below in the schema markup

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "HHHunts Commitment To RVA",
  "image": "",  
  "author": {
    "@type": "Organization",
    "name": "HHHunt"
    "url": "https://hhhunt.com"
  },  
  "publisher": {
    "@type": "Organization",
    "name": "HHHunt",
    "logo": {
      "@type": "ImageObject",
      **"url": "https://assets-global.website-files.com/61d6f3d648b8c96670b238ab/61d86f26213077625ab3a90e_logo-130.png"**
    }
  },
  "datePublished": "2022-03-28",
  "articleBody": "When ... ‍", // shortened
  **"thumbnailUrl": "https://assets-global.website-files.com/61d6f3d648b8c989b9b238c0/624311d33025d92e76fb34b9_Habitat-for-Humaity-(2).jpg",**
  "timeRequired": "PT3M",
  "description": "Growing up in Richmond, VA, Harry H. Hunt, III has always held a special place in heart for RVA and made a commitment to supporting and investing in the region.",
}
</script>

My code for replacing the escape characters is:

function() {
  var postUrl = document.getElementsByClassName('schema-blog-image')[0].innerText;
  var cleanPostUrl = postUrl.replace(/[\]/g,"")
  return cleanPostUrl;
}

where .schema-blog-image is the class selector for the blog’s featured image.

In the above ‘url’ fields, I was able to get the URL in no problem using Google Tag Manager’s JavaScript variable to get the image source from the HTML using the same class name. However, when I tried to use the function above using the same class name but for “image,” it returns an empty string (as seen above).

Some Googling led me to try return JSON.stringify(postUrl) (while removing the cleanPostUrl var), but that just gives me x22x22 as a result.

The function above worked perfectly when I tried it on the W3 Schools Try It Yourself editor, so I’m not sure what else to do to make the regex work.

None of this replaced the escape characters.

Random generated array push

I’m attempting to test feature to only push to this array 10% of the time, I’ve come up with a solution that works but is there a more dynamic way of handling this?

This is what I came up with:

const random = []

const randomNumber = Math.round(Math.random() * 9); 
console.log(randomNumber)

if (randomNumber === 5) {
random.push({
title: "testing"
})

console.log(random, 'testing push')
} else {
console.log('not this time')
}

I’m selecting 10 possibly numbers, if the number equals 5 then push to the array, if not don’t. This would make it a 1/10 chance if it pushing it to the array.

Is it possible to create a more dynamic solution of saying 10% of the time push the object to the array?

How to get checkbox value immediately after setting the state in react

I want the checkbox value immediately after setting the state.
on the below code i want the checkbox value inside the handelchange after setting the state
I have added console over there

state = {
status: false,
}

handleChange = (event) => {
this.setState((prevState) => {
   return {
      ...prevState,
      status: !prevState.status
   }
})
 ====console.log(this.state.status)====//if it checked and set i should get true
 }


<Form.Check
type="checkbox" 
label="Consigne temporaire"
value={this.state.status}
onChange={this.handleChange}
 />

Create “upcoming invoice” in Stripe

I would like to create invoice to a specific date. By that date invoice should be charged.

My mental model right now is to create DRAFT invoice, then run crontab which will check if “period_start” is current date, if so finalize and try to charge the invoice. But it seems way too complicated for such a simple usecase.

Stripe seems to have API for retrieving the UPCOMING invoice, i see in documentation to create invoice standard way and doesn’t let me to set due_date unless the type is “send_invoice” which i don’t want

So my question is – is there a way to create UPCOMING invoice which will be charged automatically from the card by specified date?

Promise.all returns undefined [duplicate]

I realize I’m probably just severely misunderstanding the logic here, but how do I go about setting the collectionData state array to the result of the Promise.all? I think the piece that’s missing in my mental understanding is returning the actual result.

Because stats returns as an array with n entries of undefined.

export default function Dashboard (props) {
    const [collectionData, setCollectiondata] = useState([])
    const globalState = useContext(GlobalStateContext)
    const dispatch = useContext(GlobalDispatchContext)

    useEffect(() => {
        async function getCollectionData() {
              const collections = globalState.collections;
              const stats = Promise.all(collections.map(async collection => {
                  console.log('Fetching data for: ' + collection)
                  await fetch(`https://api-to-query.foo.bar/${collection}/stats`)
                  .then((response) => response.json())
                  .then((data) => {
                      console.log(data)
                  })
                }))

                return stats
            }
        }

        getCollectionData().then((result=> {
            setCollectiondata(result)
        }))
    }, [])
    ```

gifted chat is not showing up React Native

When I am on the chat screen the GiftedChat component is not displayed.
I use android-studio and javascript.
I try do the next example: https://github.com/FaridSafi/react-native-gifted-chat.
No error is displayed on the console

import {
    SafeAreaView,
    ScrollView,
    StatusBar,
    View,
} from 'react-native';

import { Component } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';

class Chat extends Component {

    constructor(props) {
        super(props);
        this.state = {
            party: this.props.route.params.party,
            participant: undefined,
            owner: false,
            user: { _id: "mateo" },
            messages: []
        }

        this.getParticipant(this.props.route.params);
        this.getParticipant = this.getParticipant.bind(this);
    }

    onSend(messages) {
    }

    render() {
        const { messages } = this.state;

        return (
            <SafeAreaView>
                <StatusBar />
                <ScrollView
                    contentInsetAdjustmentBehavior="automatic">
                    <View>
                        <GiftedChat
                            messages={messages}
                            onSend={newMessages => this.onSend(newMessages)}
                            user={{
                                _id: 1
                            }}
                            renderUsernameOnMessage
                        />
                    </View>
                </ScrollView>
            </SafeAreaView>
        );
    };
   }
export default Chat;

Add dots to truncate multiline overflow CSS

i need to add 3 dots ‘…’ to truncate long text multinine. We can Not use

-webkit-line-clamp: X;

Since we do not know the number of rows or owr text. The phader item has fixed height and the text can be changed, so, its long will be different. I have tested several ways, the most ideal is this one:

overflow: hidden;
display: inline-block;
max-height: 96%

It works but I need to add 3 dots at the end of truncate text.

Any help? thank you in advance

Why is the nav bar position=sticky not working?

<!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">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <nav>
        <navl>
        <ul>
            <li><img src="" alt="logo"></li>
            <li><input type="search"></li>
            <li><img src="" alt="hit"></li>
        </ul>
        </navl>

        <navr>
            <ul>
                <li><img src="" alt=""dp></li>
                <li>Name</li>
                <li>i1</li>
                <li>i2</li>
                <li>i3</li>
                <li>i4</li>
                <li>i5</li>
            </ul>
        </navr>
    </nav>
    <main>
        <left>
            <span>left</span>
        </left>
        <center>
            <span>center</span>
        </center>
        <right>
            <span>right</span>
        </right>
    </main>


</body>
</html>

*{
    padding: 0vw;
    margin: 0vw;
}

nav{
    background-color: rgba(52, 52, 146, 0.829);
    display: inline-flex;
    justify-content: space-around;
    align-items: center;
    width: 100vw;
    height: 45px;
    position:sticky;
}

ul {
    display: inline-flex;
    list-style-type:none;

}

navl{
    border-color:red ;
    border-style: dotted;
    align-items: center;
}
navr{
    border-color:red ;
    border-style: dotted;

}

main{
    justify-content: space-between;
    display: flex;
}
left{
    border-color: red;
    border-style: dotted;
    width: 30vw;
    height: 400px;
    display: inline-flex;
    position: sticky;
}
center{
    border-color: red;
    border-style: dotted;
    width: 35vw;
    height:5000px;
    display: inline-flex;
}
right{
    border-color: red;
    border-style: dotted;
    width: 30vw;
    height: 300px;
    display: inline-flex;
}

Why is the nav bar position:sticky attribute not working ? But if i set position to fixed, it works in that case. I want it to become fixed on the top as we scroll just as facebook. I am trying to create a clone-facebook. I am beginner trying to learn web-development.
1st code is HTML while 2nd is CSS Stylesheet

Building dynamic form with dropdown and radio button

I’m trying to build a dynamic form with react which is auto populated with components when received data from api, here I’m able to display and render the components which are the n numbers of dropdowns and radio buttons on my form basis on what I’ll be receiving from the api response, but still I want to pass the data selected from the from on onSubmit() function. I’m facing certain challenges in collecting the data altogether, as I’m using rfce, I can get data of single selection whereas I want a collective selection data.
Below attached is my code.

This is the main card component. Which is responsible for getting api and passing props to sub components that are dropdowns and radio button based on their types

import React, { useEffect, useState } from "react";
import { Card, Button, FloatingLabel, Form } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import {
  SurveyDropdown,
  SurveyRadioButton,
} from "./subcomponents/SurveyComponents";
import { getQuestions } from "../util/http";

const SurveyCard = () => {
  const [surveyData, setSurveyData] = useState([]);
  useEffect(() => {
    // Update the document title using the browser API
    getQuestions()
      .then((resp) => {
        setSurveyData(resp.data);
      })
      .catch((err) => {
        console.log(err);
        if (
          !err.response ||
          !err.response.data ||
          !err.response.data.errorCode
        ) {
          console.log("server failed to response");
          return;
        }
        switch (err.response.data.errorCode) {
          case 50: // Survey submitted
            window.location.replace("/surveysubmitted");

            break;

          default:
            console.error("Error code not registered ");
            break;
        }
      });
  }, []);
  return (
    <>
      <Card>
        <Card.Header></Card.Header>
        <Card.Body>
          <Card.Title>Please provide your feedback</Card.Title>
          {surveyData.map((question) => {
            if (question.type === "dropdown") {
              return <SurveyDropdown key={question.id} value={question} />;
            } else if (question.type === "button") {
              return <SurveyRadioButton value={question} />;
            }
          })}
          <FloatingLabel
            controlId="floatingTextarea2"
            label="Comments"
            className="for-spacing"
          >
            <Form.Control
              as="textarea"
              placeholder="Leave a comment here"
              style={{ height: "100px" }}
            />
          </FloatingLabel>{" "}
          <br />
          <Button variant="primary">Submit</Button>
        </Card.Body>
      </Card>
      <br />
      <br />
    </>
  );
};

export default SurveyCard;

This is component which is rendering all the dropdowns and radio buttons. Here I’m trying to get the collective data from all displayed dropdowns and radio button, but instead am getting only one state a time.

import React, { useState } from "react";
import { Form, FloatingLabel } from "react-bootstrap";

export const SurveyDropdown = (props) => {
  const [selectedOption, setSelectedOption] = useState();
  console.log("Selected Option", selectedOption);
  function handleSelectChange(event) {
    setSelectedOption(event.target.value);
  }

  return (
    <React.Fragment>
      <FloatingLabel
        className="for-spacing"
        controlId="floatingSelect"
        label={props.value.surveyQuestion}
      >
        <Form.Select onChange={handleSelectChange}>
          {props.value.option.map((surveyD, index) => (
            <option
              value={surveyD}
              key={index}
              selected={surveyD === selectedOption}
            >
              {surveyD}
            </option>
          ))}
        </Form.Select>
      </FloatingLabel>
    </React.Fragment>
  );
};

export const SurveyRadioButton = (props) => {
  const [checkedOption, setCheckedOption] = useState([]);
  console.log("Checked Option", checkedOption);
  function handleCheckedChange(event) {
    setCheckedOption(event.target.value);
  }

  return (
    <div className="for-spacing">
      <label>{props.value.surveyQuestion}</label>
      <Form>
        {["radio"].map((type) => (
          <div key={`inline-${type}`} className="mb-3">
            {props.value.option.map((answer, index) => {
              return (
                <Form.Check
                  inline
                  label={answer}
                  key={index}
                  name="group1"
                  type="radio"
                  value={answer}
                  id={`inline-${type}-1`}
                  onChange={handleCheckedChange}
                />
              );
            })}
          </div>
        ))}
      </Form>
    </div>
  );
};

what shall I try, please help!
Thanks!

Loader works only on the first ajax call

I want the loader to stay until the complete execution is complete and statement $(“#xyzDiv”).html(data) has been executed. Currently the loader gets hidden after the first ajax call. Even if i add “beforeSend: function () { $(“#loader”).show(); }” to GetDataList(), the loader is not staying.

$.ajax
({
    type: "POST",
    url: ajaxUrl,
    data: dataObj,
    beforeSend: function () { $("#loader").show(); },
    success: function (data)
    {
        if (data.result)
        {
            GetDataList();
            toastr.success(data.strMsg);
        }
        else
        {
            toastr.error(data.strMsg);
        }
    },
    error: function (jqXHR, textStatus)
    {
         var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
        console.log(msg);
        toastr.error('An error occurred. Please try again');
    },
    complete: function () { $("#loader").hide(); }
});

function GetDataList()
{
    $.ajax
    ({
        type: "Get",
        url: ajaxUrl,
        data: dataObj,
        success: function (data)
        {
            $("#xyzDiv").html(data);
        },
        error: function (jqXHR, textStatus) 
        {
            var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
            console.log(msg);
            toastr.error('An error occurred. Please try again');
        }
    });
}

How to generate SMIL with javascript

I am trying to generate a svg with SMIL and having a hard time figuring out why it is not working.

The code is following

// targeting the svg itself
const svg = document.querySelector("svg");

// variable for the namespace 
const svgns = "http://www.w3.org/2000/svg"

//assigning svg element attribute 
svg.setAttribute('class', 'layer1');
svg.setAttribute('xmlns', svgns);
svg.setAttribute('viewBox', '0 0 1280 720');

let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute("width", '1280');
bg.setAttribute("height", '720');
bg.setAttribute("fill", "#F1C40F");
svg.appendChild(bg);

let pth = document.createElementNS(svgns, 'path');
pth.setAttribute('class', 'pth');
pth.setAttribute('id', 'pth');
pth.setAttribute('d',
    'M10,20, L110,20, L110,140, L10,140 ,Z'
);
pth.style.setProperty("stroke-width", ".5");
pth.style.setProperty("stroke", "red");
pth.setAttribute('fill', 'red');

svg.appendChild(pth);

let anim = document.createElementNS(svgns, 'animate');
anim.setAttribute('attributeName', 'd');
anim.setAttribute('attributeType', 'XML');
anim.setAttribute('values', "M10,20, L110,20, L110,140, L10,140 ,Z; M10,20, L210,20, L210,140, L10,140 ,Z; ;M10,20, L110,20, L110,140, L10,140 ,Z");
anim.setAttribute('keyTimes', '0;0.5;1');
anim.setAttribute('begin', '0s');
anim.setAttribute('end', '1s');
anim.setAttribute('repeatCount', 'indefinite');
svg.appendChild(anim);
pth.appendChild(anim);
<!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">
    <title>Document</title>
</head>

<body>
    <link rel="stylesheet" href="style.css">
    </link>
    <svg>
        <script href="index.js"></script>
        <!--
        <rect class="bg" id="bg" width="1280" height="720" fill="#F1C40F"></rect>
        <path class="pth" id="pth" d="M10,20, L110,20, L110,140, L10,140 ,Z" fill="red"
            style="stroke-width: 0.5; stroke: red;">
            <animate attributeName="d" 
                attributeType="XML" 
                values=
                "M10,20, L110,20, L110,140, L10,140 ,Z
                ;M10,20, L210,20, L210,140, L10,140 ,Z
                ;M10,20, L110,20, L110,140, L10,140 ,Z" 
                keyTimes="0;.5;1"
                begin="0s"
                dur="1s" 
                repeatCount="indefinite"
                />
        </path>-->
    </svg>

</html>

However, the uncommented SVG works fine with SMIL

<!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">
    <title>Document</title>
</head>

<body>
    <link rel="stylesheet" href="style.css">
    </link>
    <svg>
        <script href="index.js"></script>
        
        <rect class="bg" id="bg" width="1280" height="720" fill="#F1C40F"></rect>
        <path class="pth" id="pth" d="M10,20, L110,20, L110,140, L10,140 ,Z" fill="red"
            style="stroke-width: 0.5; stroke: red;">
            <animate attributeName="d" 
                attributeType="XML" 
                values=
                "M10,20, L110,20, L110,140, L10,140 ,Z
                ;M10,20, L210,20, L210,140, L10,140 ,Z
                ;M10,20, L110,20, L110,140, L10,140 ,Z" 
                keyTimes="0;.5;1"
                begin="0s"
                dur="1s" 
                repeatCount="indefinite"
                />
        </path>
    </svg>

</html>

Syntax in crac-webpack-rewired to solve webpack polyfills error

I created my project in React using create-react-app, but after sometime I got to this error in the console

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
@ ./node_modules/loader-utils/lib/index.js 7:25-54
@ ./node_modules/file-loader/dist/index.js 11:19-42
@ ./node_modules/file-loader/dist/cjs.js 3:15-33
@ ./src/App.js 13:0-35
@ ./src/index.js 7:0-24 11:33-36

After reading this post, I reached the conclusion I had to modify the webpack.config.js that I did not have because I created the project with create-react-app. Instead of ejecting (it is not very recommended), I used the npm package advised at the end of this thread. The problem is that there are no examples on how to use it. My question is which syntaxis do I have to follow to modify config/webpack.extend.js? This is the code at the moment:

module.exports = {
  dev: (config) => {
    //override webpack configuration
    config.externals =[..];
    return config;
  },
  prod: (config) => {
    //override webpack configuration
    config.externals =[..];
    return config;
  }
};

I have tried using console.log(config) but it never gets to print as errors are printed back.

Which is better to fetch data one time in App.js and send it as one of the props or fetch data in every components where I use the data?

I have a question about React and am a newbie. So, my concern is what is the best practice when fetching kind of large data. I have some components that require data called quizzes. As I was writing, I noticed I wrote useEffect to get all of the quizzes I have in Firestore and started wondering, “how about fetching all quizzes in App.js and include it as one of the props in components that require the data. On the other hand, the next Because App.js called every time, to fetch quizzes in App.js can make my app work slow. I recently have only a few quizzes so I don’t really think or see how slow my app becomes between the two ways. If I have large data, it takes some time to fetch all of the quizzes, right?? So, I also concern how to use async await for fetching data.

My code will work in both ways, but I just wanna know the best practice for fetching large data to step up to a mid-level React developer.
Thanks for your time and effort in advance here:)

App.js

// Import from 3rd parties
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { onAuthStateChanged } from 'firebase/auth'
import { collection, onSnapshot } from 'firebase/firestore';

// Import files existing in this project
import './styles/Style.css';
import './styles/quiz.css';
import Header from "./components/Header";
import Footer from "./components/Footer";

import Test from "./components/Test";
import QuizHeader from "./components/QuizHeader";
import QuizEdit from "./components/QuizEdit";
// import About from "./components/About";
import ErrorPage from "./components/ErrorPage";
import Profile from "./components/Profile";
import QuizHome from "./components/QuizHome";
import AllQuizzes from "./components/AllQuizzes";
import FormikNewQuiz from "./components/FormikNewQuiz";
import { auth, db } from './config/firebase';


// Actual Coding
function App() {
  const [currentUser, setCurrentUser] = useState({});
  const [quizzes, setQuizzes] = useState({});

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      if (user !== null) {
        setCurrentUser({ username: user.displayName, uid: user.uid, email: user.email, photoURL: user.photoURL })
      }
    })
    const collectionRef = collection(db, 'quizzes');
    const unsub = onSnapshot(collectionRef, {
      next: snapshot => {
        setQuizzes(snapshot.docs.map(doc => ({ ...doc.data(), id: doc.id })));
      },
      error: err => {
        console.error('quizes listener failed: ', err);
      },
    });
    return unsub;
  }, [])

  console.log(currentUser)
  console.log(quizzes)

  return (
    <BrowserRouter>
      <Header user={currentUser} />
      <div id="main">
        <Routes>
          <Route path="kinniku-quiz/" element={<QuizHeader />} >
            <Route path="home" element={<QuizHome />} />
            <Route path="new" element={<FormikNewQuiz uid={currentUser === {} ? null : currentUser.uid} username={currentUser === {} ? null : currentUser.username} />} />
            <Route path="test" element={<Test />} />
            <Route path="all-quizzes" element={<AllQuizzes uid={currentUser === {} ? "" : currentUser.uid} />} />
            <Route path="edit/:id" element={<QuizEdit quiz={"quiz props!!"} />} />
          </Route>
          <Route path="profile/:uid" element={<Profile setCurrentUser={setCurrentUser} user={currentUser} />} />
          <Route path="*" element={<ErrorPage />} />
        </Routes>
      </div>
      <Footer />

    </BrowserRouter>
  );
}

export default App;

This is an example component in which I used useEffect to fetch all quizzes.

Test.jsx

import { useEffect, useState } from 'react';
import { collection, onSnapshot } from 'firebase/firestore';
import Loading from 'react-simple-loading';

import {db} from '../config/firebase';
import GoodBad from './GoodBad';
import GoNextQuizBtn from './GoNextQuizBtn';
import GoPrevQuizBtn from './GoPrevQuizBtn';
import QuizResultWindow from './QuizResultWindow';
import { biCircle, biPlus } from '../icons/icons';

const Test = () => {
  const [quizzes, setQuizzes] = useState([]);
  // const [clickedAnswers, setClickedAnswers] = useState([]);
  const [currentQIndex, setCurrentQIndex] = useState(0);
  const [points, setPoints] = useState(0);
  const [usersCorrectAnswers, setUsersCorrectAnswers] = useState([]);
  const [clickedAnswerIndex, setClickedAnswerIndex] = useState();

  useEffect(() => {
    const collectionRef = collection(db, 'quizzes');
    const unsub = onSnapshot(collectionRef, {
      next: snapshot => {
        setQuizzes(snapshot.docs.map(doc => ({ ...doc.data(), id: doc.id })));
      },
      error: err => {
        // don't forget error handling! e.g. update component with an error message
        console.error('quizes listener failed: ', err);
      },
    });
    return unsub;
    // const unsub = onSnapshot(collectionRef, snapshot => {
    //   setQuizzes(snapshot.docs.map(doc => ({ ...doc.data(), id: doc.id })));
    // });
    // return unsub;
    // getData(): run once
    // onSnapshot(): listen for realtime updates
  }, []);

  const handleJudge = async (e, answer, quiz, answerIndex, quizIndex) => {
    // It may be unnecessary to add 1. I jsut thought users don't like index 0 for answer/quiz 1.
    answerIndex++;
    quizIndex++;

    const correctAnswerIndex = quiz.correctAnswer;
    console.log(
      `answer => ${answer}, answerIndex => ${answerIndex}, correctAnswerIndex => ${correctAnswerIndex}, quizIndex => ${quizIndex}`
    );

    setClickedAnswerIndex(answerIndex);

    // When an answer is clicked:
    // 1. make all disable to be clicked <- can be done by adding the same className to all.
    // 2. show the answer with a slight dif style
    // 3. add style to a selected answer.

    // add some styles to answers depending on correct or not
    if (correctAnswerIndex === answerIndex) {
      setPoints(prevState => prevState + 1);
      setUsersCorrectAnswers([...usersCorrectAnswers, quizIndex]);
      e.target.className = await 'selected correctAnswerClicked';
    } else {
      e.target.className = await 'selected incorrectAnswerClicked';
    }
  };

  const goNextQuiz = () => {
    if (currentQIndex !== quizzes.length) {
      setCurrentQIndex(prevState => prevState + 1);
    }
    setClickedAnswerIndex();
  };
  const goPrevQuiz = () => {
    if (currentQIndex !== 0) {
      setCurrentQIndex(prevState => prevState - 1);
    } else {
      setCurrentQIndex(currentQIndex);
    }
    setClickedAnswerIndex();
  };

  return (
    <div className='quizContainer'>
      {quizzes.length === 0 ? <Loading color={'#005bbb'} /> : ''}
      {quizzes.map((quiz, quizIndex) => {
        if (quizIndex === currentQIndex) {
          return (
            <div key={quiz.id} className='quiz'>
              <div className='quizHeader'>
                <span className='createdBy'>Created by: {quiz.username ? quiz.username : "Anonymous"}</span>
                <span className='quizNumber'>
                  {quizIndex + 1}/{quizzes.length}
                </span>
              </div>
              <div className='quizQuestionContainer'>
                <p className='quizQuestionText'>{quiz.question}</p>
              </div>
              <ul
                className={
                  clickedAnswerIndex
                    ? 'quizAnswersContainer answerDefined'
                    : 'quizAnswersContainer'
                }
              >
                {quiz.answers.map((answer, answerIndex) => (
                  <li
                    key={answer}
                    onClick={e => {
                      handleJudge(e, answer, quiz, answerIndex, quizIndex);
                    }}
                    className={
                      clickedAnswerIndex &&
                      answerIndex + 1 === clickedAnswerIndex
                        ? 'selected'
                        : null
                    }
                  >
                    <span className='answer'>{answer}</span>
                    <div className='correctIncorrectIcons'>
                      <span className='correctIcon'>{biCircle}</span>
                      <span className='incorrectIcon'>{biPlus}</span>
                    </div>
                  </li>
                ))}
              </ul>
              <div className='quizFooter'>
                {quizIndex !== 0 ? (
                  <GoPrevQuizBtn
                    goPrevQuiz={goPrevQuiz}
                    text='Prev'
                    disable=''
                  />
                ) : (
                  <GoPrevQuizBtn
                    goPrevQuiz={goPrevQuiz}
                    text='Prev'
                    disable='disable'
                  />
                )}

                <GoodBad quiz={quiz} />
                {quizIndex + 1 === quizzes.length ? (
                    <GoNextQuizBtn goNextQuiz={goNextQuiz} text='Result' clickedAnswerIndex={clickedAnswerIndex ? true : false } />
                  ) : (
                    <GoNextQuizBtn goNextQuiz={goNextQuiz} text='Next' clickedAnswerIndex={clickedAnswerIndex ? true : false } />
                  )
                }
              </div>
            </div>
          );
        }
      })}
      {quizzes.length !== 0 && currentQIndex >= quizzes.length ? (
        <QuizResultWindow
          usersCorrectAnswers={usersCorrectAnswers}
          points={points}
          quizzes={quizzes}
        />
      ) : (
        ''
      )}
    </div>
  );
};

export default Test;

AJAX call fails with SyntaxError: Unexpected end of JSON input

Sorry for making a post with a generic error but I just can’t figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array(‘status’ => ‘success’)); while I’m debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input

I’ve tried sending just data[‘pid’]=’csv’ in case the json needed to have something in it, but still get the same error.

AJAX call

function runDataDownload() {
    var data = {};
  //  data['rawFiles'] = $('#projectIDs').val(); 
  //  data['metadata'] = $('#getData').val();
  //  data['type']=  $('#submitType').val();
  //  data['pid']='csv';
  //  data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
    var qcRunId="csv" + Date.now();
    var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
    $.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
            .done(function(result) {
                console.log(result);  

                if (result.status==='success'){ 
                    // begin checking on progress                     
                    checkRunStatus(qcRunId, loopIndex);                   
               }
                else if (result.status==='failed'){ 
                   $('#' + errorId + ' > li').remove();                                                
                   $.each(result.errors, function(key, value) {
                       $('#' + errorId).append( "<li>" + value + "</li>" );
                   });                                                
                   $('#' + statusId).hide();                    
                   $('#' + errorId).show(); 
                }
                else {
                   $('#' + errorId + ' > li').remove();  
                   $('#' + errorId).append( "<li>Invalid return from ajax call</li>" );  
                   $('#' + errorId).show(); 
                   // PTODO - may not be needed
                   // make sure it is visible
                   $('#' + errorId).get(0).scrollIntoView();
               }           
            }) 
                .fail(function(jqXHR, status, err) { 
                    console.log(jqXHR + status + err);
                    $('#' + errorId + ' > li').remove();  
                    $('#' + errorId).append( `<li>Error in ajax call.  Error: ${status} (${err.name}: ${err.message})</li>`);                          
                    $('#' + errorId).show(); 

            });  
}

And my php code:

    public function ajax_runBg($qcName, $runId) {
         echo json_encode(array('status' => 'success'));
    }

Thank you!