didn’t work convert json decoded string to array in php which is send by ajax method

i have js object

data=[{'quest':'sometext'},{'option':['a','b', 'c']}, {'cor':[0,1,0]},{'sol':'again tetx'}]

Submited as ajax data using jquery

... data:{'qs':JSON.stringify(data)}, ...

i recieved the as post and try to convert to array

$array=json_decode(json_encode($_POST['qs']), true);

but output is

print_r($array); \is

[{"quest":"sometext"},{"option":["a","b", "c"]}, {"cor":[0,1,0]},{"sol":"again tetx'}]

i want to make it array in php

Parsing data then mapping from JSON using Fetch API

As a beginner to React, I have been struggling with this issue for a couple days now and any direction is appreciated. I am able to console log my JSON result from my API but I cannot get the data to display in my component. I want to map the data to the component. I have individual sections for each data entry from my JSON.

My App.js is:

fetch("MY_URL", requestOptions)
.then(response => response.json())
.then(data => {
  console.log(data)
  airData.setState({
    content: data 
  })
});



class App extends Component {
  
  render () {
        
        return (
          <div className="app">
            <Header />
            <div className="spacer"></div>
            <OverallStatus />
              {airData.map(data=>{
                return (
                  <div>
                    <div className='qualityFactor'>
                      <h1><img src={iconHumidity} alt="Logo" className="iconSmall" />Humidity {data.humidity}%</h1>
                      <ProgressBar completed={data.humidity}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconAirPressure} alt="Logo" className="iconSmall" />Air Pressure {data.AirPressure} hPa</h1>
                      <ProgressBar completed={data.AirPressure}
                      maxCompleted={1030} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonDioxide} alt="Logo" className="iconSmall" />Carbon Dioxide {data.CO2} ppm</h1>
                      <ProgressBar completed={data.CO2}
                      maxCompleted={2000} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconVOCs} alt="Logo" className="iconSmall" />VOCs {data.TVOC} ppb</h1>
                      <ProgressBar completed={data.TVOC}
                      maxCompleted={1000} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconParticulateMatter} alt="Logo" className="iconSmall" />Particulate Matter 2.5 {data.PM25} ug/m3</h1>
                      <ProgressBar completed={data.PM25}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonMonoxide} alt="Logo" className="iconSmall" />Carbon Monoxide {data.CO} ppm</h1>
                      <ProgressBar completed={data.CO}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconNitrogenDioxide} alt="Logo" className="iconSmall" />Nitrogen Dioxide {data.NO2} ppb</h1>
                      <ProgressBar completed={data.NO2}
                      maxCompleted={200} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconOzone} alt="Logo" className="iconSmall" />Ozone {data.Ozone} ppb</h1>
                      <ProgressBar completed={data.Ozone}
                      maxCompleted={100} className="statusBar" />
                    </div>
                  </div>
              );})}
          </div>
        )
    }
  }
  
  

export default App;

How to set chartJs Doughnut labels on right side?

Actually i’m using chart js chartJs Doughnut chart, this is working fine but how can I set chartJs Doughnut labels on right side?

My Code:-

   const countryChart = new Chart(document.getElementById('countryChart').getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: ['India', 'Netherlands', 'UAE', 'Egypt', 'Others'],
                datasets: [{
                    label: 'Revenue',
                    data: [12, 19, 3, 5, 2],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }],
            },
        });
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="countryChart" height="150"></canvas>

ThankYou for your efforts!

I am using react-native here and the library react-native-google-places-autocomplete I have imported my API key but autocomplete is not working. pleas

this is the code Which I have written please help.
I am using react-native here and the library react-native-google-places-autocomplete I have imported my API key but autocomplete is not working. please help

import { SafeAreaView, View, Image } from 'react-native';
import React from 'react';
import tw from 'tailwind-react-native-classnames';
import NavOptions from '../components/NavOptions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import { GOOGLE_MAPS_APIKEY } from "@env";

const HomeScreen = () => {
   // console.log(GOOGLE_MAPS_APIKEY) HERE I AM GETTING A OUTPUT
    return (
        <SafeAreaView style={tw`bg-white h-full`}>
            <View style={tw`p-5`}>
                <Image
                    style={{ width: 100, height: 100, resizeMode: "contain" }}
                    source={{
                        uri: "https://links.papareact.com/gzs"
                    }}
                />

                <GooglePlacesAutocomplete
                    style={{

                    }}
                    query={{
                        key: GOOGLE_MAPS_APIKEY,
                        language: 'en',
                    }}
                    placeholder='Where from?'
                    nearbyPlacesAPI='GooglePlacesSearch'
                    debounce={400}
                />
                <NavOptions/>
            </View>
        </SafeAreaView>
    );
};

export default HomeScreen;

Glucose measurement from cordova-plugin-ble-central Accu Chek Mobile

I try to read glucose measurement from cordova-plugin-ble-central.

I found how obtain different values like manufacturer, or serial number.

But I can’t get the readings glucose measurement.

I do that

var databuffer = new Uint8Array(2);
    databuffer[0] = 0x01;
    databuffer[1] = 0x01;

console.log("startwrite");
    
    ble.write(localStorage.getItem('ACMid'), "1808", "2A52", databuffer.buffer, 
        function(data){
                
            int8data = new Uint8Array(data);            
            console.log("Hooray we have data write : " + JSON.stringify( data ));
            console.log("Hooray we have data write : " + JSON.stringify( int8data));                
        }, 
        function(failure){
            addMyContenu("Failed write from device. " + JSON.stringify(failure), 1);
            console.log("Failed write characteristic from device. " + JSON.stringify(failure));
        });

how to call a function after completion of setting a state variable of a functional component in reactjs

I have a state variable where it is continuously changing and after the final state change I have to call a function which removes duplicate from final state variable.

while I am setting state variable, I am using prevstate to merge the present state value

code is below

const setevent = async(events) =>{
    await setevent((prevstate) => [...prevstate,...events])
}

I have to call a function using final event variable as props.

how can I do this?

actually I have seen a approach where after completing the setstate it is like below

const setevent = async(event) =>{
    await setevent(event,() => {
      //calling the function which I need
      getunique(event)
  })
}

but I cant make it work because I am already using prevState.

Thanks in advance

JavaSCript find not working with template literals [duplicate]

The following code is working for me.

const employee = [ {
 name:"Albert",
 job: "Graphic Designer" 
},
{
 name:"David",
 job: "UX/UI Designer" 
},
{
 name:"John",
 job: "Software Developer" 
},
];

let a = employee.find((elem)=>{
return elem.job === "Software Developer";
});

But it is not working when i use template literals as following.

return `${elem.job} === "Software Developer"`;

Anyone has answer for this. Thanks in Advance!

Output only one possible result looping thru 2 arrays with if-statement

I have two arrays. Each element of which I compare numbers of first array are greater than the seconds’ and if it finds (through if statement) any number from first array greater than any number from second array, I console.log them. However, there might be more than one coincidence but per one request in need to console.log only first result.

Say,
First array has [0.4,0,6]
Second array has [0.5,0.5]

It produces 2 results since there are two matches. How to get only first one.

My code looks like that:

https://jsfiddle.net/oxpwb0j3/2/

const numbers = [0.6,0.4];

for(a = 0; a < numbers.length; a++) {
     var res_num1 = numbers[a];
   
   const numbers2 = [0.5,0.5];
   
   for(b = 0; b < numbers2.length; b++) {
         var res_num2 = numbers2[b];
       
       if(res_num1 > res_num2){
            console.log(res_num1+" = "+res_num2);
       }
   }
}

it outputs:

0.6 = 0.5
0.6 = 0.5

as I explained in the beginning how to limit to only log the first result like so 0.6 = 0.5.

I’m new to JS and learning. Thank you!

Chrome extension – Input value set in JS won’t get submitted

I am trying to set value of an input field that is on a webpage via Chrome extension. The value does get filled successfully, however when form is submitted, it gives error of input field being empty.

Input field code:

<input type="text" class="text-center CustomTextBox ng-pristine ng-valid ng-isolate-scope ng-not-empty ng-valid-maxlength ng-touched" autocomplete="off" min="0" maxlength="6" jcs-decimals="2" jcs-allow-null="false" jcs-decimals-hide-zero="true" ng-model="p.quantity" ng-disabled="p.OutOfStock" ng-blur="vm.QtyEntered(p)" ng-change="vm.qtyChanged(p)">

Javascript:

var foundinput = getElementsByTagName('input').item(0);
foundinput.value = 5.00;

P.S. When value is entered manually, the form does submit successfully.

How To get run time REST API code coverage?

I am interested in generating a REST API coverage report. We’re currently writing code for API in Python Programming language

Is there any way (preferably in Python and Javascript) that I can track a set of (existing) unit tests and ensure that all related API resources/methods have been exercised, all status codes have been generated etc.? At the moment the coverage reports will only tell us if we’ve exercised the code which implements the API, but not which parts of the API have been exercised during testing.

A code coverage tool should be dynamic. While running the code in background API code coverage must be calculated for particular file.

Running .filter and .map synchronously

Hello I am having an issue running this function wherein im trying to filter this an array of objects then afterwards im reorganizing by reassigning my id with the index of the .map The issue that occurs is that the .filter is not deleting/removing an items in the function. Here is my code as reference:
What do be the best solution of this. Any input would be helpful thank you.

 const removeData = (id) => {
        const del = idleData.filter(idle => id !== idle.id).map((item,index) => (
            {
                id: index, 
                days: item.day,
                comments: item.comments,
                cost: item.cost,
                reason: item.reason,
                portCallVoyageId: item.portCallVoyageId,
                changedBy: item.changedBy
            }
        ));
        setIdleData(del);
    }

Are there ways on which html submit button .md file can be created directly to the webserver?

In the HTML you can add and delete rows and also there is a submit button. Submit button is used after finishing filling up the details on the tabulated form in the HTML. When submitting button is clicked, “. MD file” is downloaded/created.

Goal:

  1. Is there a way on which the created file will be automatically be created on the web server once the submit button is clicked? – Based on research is that PHP can be used in order to achieve this kind of goal.

  2. Is conversion from HTML to PHP possible? OR from HTML>javascript>PHP?

  3. What will be the correct code for PHP in order for this to be executed? – The code created is not working.

ERROR IN PHP:
array to string conversion

CODE FOR HTML:

<!DOCTYPE html>
<html>
   <head>
      <style>
         {font: 17px Calibri;} 
         table {width: 70%;}
         table, th, td {border: solid 1px #DDD;
         border-collapse: collapse; padding: 2px 3px; text-align: center;
         }
      </style>
   </head>
   <body onload="createTable()">
      <div id="container"></div>
      <!-- the container to add the TABLE -->
      <p>
         <input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
         <input type="button" id="btnDelete" value="Delete Row" onclick="delete_Row()" />
         <input type="button" id="bt" value="Submit" onclick="submit()" />
      </p>
      <p id='output'></p>
   </body>
   <script>
      var arrHead = new Array();
      arrHead = ['', 'Last Name', 'First Name', 'Middle Name', 'Telephone No.', 'Occupation', 'Age'];
  
      function createTable() {
          var empTable = document.createElement('table');
          empTable.setAttribute('id', 'empTable'); 
  
          var tr = empTable.insertRow(-1);
          for (var h = 0; h < arrHead.length; h++) {
              var th = document.createElement('th');
              th.innerHTML = arrHead[h];
              tr.appendChild(th);
          }
  
          var div = document.getElementById('container');
          div.appendChild(empTable);  
      }
  
      function addRow() {
          var empTab = document.getElementById('empTable');
  
          var rowCnt = empTab.rows.length;   
          var tr = empTab.insertRow(rowCnt); 
          tr = empTab.insertRow(rowCnt);
  
          for (var c = 0; c < arrHead.length; c++) {
              var td = document.createElement('td'); 
              td = tr.insertCell(c);
  
              if (c == 0) {      
  
                      var button = document.createElement('input');
  
                      set input attributes.
                      button.setAttribute('type', 'button');
                      button.setAttribute('value', 'Remove');
  
                      add button's 'onclick' event.
                      button.setAttribute('onclick', 'removeRow(this)');
  
                      td.appendChild(button);
  
  
                    var chkbox = document.createElement("INPUT");
                    chkbox.setAttribute("id", "id_chkbox");
                    chkbox.setAttribute("type", "checkbox");
                    td.appendChild(chkbox);
              }
              else {
  
                  var ele = document.createElement('input');
                  ele.setAttribute('type', 'text');
                  ele.setAttribute('value', '');
  
                  td.appendChild(ele);
              }
          }
      }
  
          function removeRow(oButton) {
              var empTab = document.getElementById('empTable');
              empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); 
          }
  
      function delete_Row() {
          var empTab = document.getElementById('empTable').getElementsByTagName('tr');
          var root = empTab[0].parentNode;
          var allInp = root.getElementsByTagName('input');
          for (var i = allInp.length-1; i >= 0; i--){
              if ((allInp[i].getAttribute('type') == 'checkbox') && (allInp[i].checked)) {
              root.removeChild (allInp[i].parentNode.parentNode)
              }
          }
      }
  
      function submit() {
          var myTab = document.getElementById('empTable');
          var arrValues = new Array();
  
           loop through each row of the table.
          for (row = 1; row < myTab.rows.length - 1; row++) {
             loop through each cell in a row.
              for (c = 0; c < myTab.rows[row].cells.length; c++) {  
                  var element = myTab.rows.item(row).cells[c];
                  if (element.childNodes[0].getAttribute('type') == 'text') {
                      arrValues.push("'" + element.childNodes[0].value + "'");
                  }
              }
          }
  
        var myTab = document.getElementById('empTable')
              for (var x = 1; x < myTab.rows.length - 1; x++) {
  
                  for (var y = 0; y < myTab.rows[x].cells.length; y++) {
      var element = myTab.rows.item(x).cells[y];
                      arrValues.push(element.childNodes[0].value);
                  }
              }
      
          // The final output.
      var j = arrValues.join("|");
      var k = j.split('on');
      var l = k.join('n');
      var m = l + "|";
      document.getElementById("output").innerHTML = m;
          //console.log (arrValues);   
  
      var data = document.getElementById("output").innerHTML
          var file = document.createElement("a")
          file.download = "test.md"
      
          var dataBlob = new Blob([data], {type: "text/plain"});
          file.href = window.URL.createObjectURL(dataBlob);
          file.click();
      }
   </script>
</html>

CODE FOR PHP:

“;
foreach ( $_POST[“last_name”] as $last_name ) // $_POST[“last_name”] IS AN ARRAY.
echo $last_name . “
“;

echo “

” .
“First Name:
“;
foreach ( $_POST[“first_name”] as $first_name ) // $_POST[“first_name”] IS AN ARRAY.
echo $first_name . “
“;

echo “

” .
“Middle Name:
“;
foreach ( $_POST[“middle_name”] as $middle_name ) // $_POST[“middle_name”] IS AN ARRAY.
echo $middle_name . “
“;

echo “

” .
“Telephone No.
“;
foreach ( $_POST[“telephone_number”] as $telephone_number ) // $_POST[“telephone_number”] IS AN ARRAY.
echo $telephone_number . “
“;

echo “

” .
“Occupation:
“;
foreach ( $_POST[“occupation”] as $occupation ) // $_POST[“occupation”] IS AN ARRAY.
echo $occupation . “
“;

echo “

” .
“Age:
“;
foreach ( $_POST[“age”] as $age ) // $_POST[“age”] IS AN ARRAY.
echo $age . “
“;

}
else echo “Error: no data”;

?>

Firestore, adding value to an existing array field

I want the new ph value to be added in the arraylist but instead, it keep updating the first value of the arraylist

my firestore

var insBtn = document.getElementById("InsBtn");

 async function AddDocument_CustomID() {
    var ref = doc(db,"pHvalue", "pH");

     await setDoc(
        ref, {
            pH: [pH.value]
        });
}


insBtn.addEventListener('click', AddDocument_CustomID);

JS $.post > dump PHP $_POST data to file

I’ve been trying this for hours and finally give up.
As you can tell I’ve a huge noob and have little to no idea what I’m doing…

I have some JS being called from a button onclick= which POSTs to a PHP file. I’d like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.

I’ve tried various methods, but none seem to work – either not writing the data at all, or writing “()”, “[]” (if trying to encode the POST data as JSON), or just the word “array” and so on.

Methods I’ve tried;

file_put_contents('test.txt', file_get_contents('php://input'));  //this I thought *should* definitely work...

var_dump / var_export / print_r

I’ve tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.

I’m mostly trying to use fopen/write/close to do the deed (because that’s all I really “know”). File is writable.

(part of the) JS I’m using to POST:

(from button onclick="send('breakfast'))

function send(food){
if(food == 'breakfast'){
    $.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());

I’m not looking to extract(?) values from the POST data, just write it “as-is” to a file, and I’m not bothered on the formatting etc.

Would someone please assist in putting me out of my misery?