Home > Back-end >  How to declare a variable in axios get json
How to declare a variable in axios get json

Time:07-09

I am using axios.get to retrieve the element I want, and it return successfully with json data showen below:enter image description here

It gooes fine, with [ and { perfectly allocated. Here is my duty, I want to retrieve one column element (this json only has one templete), let's say OrederReferencePreffix, it returns undefined instead of [[\t ... I've try these declaration below:

var attempt_one= json_only[0].InvoiceNumberPreffix; //undefined
var attempt_two= response.data.InvoiceNumberPreffix; //undefined
var attempt_three= response.data[0].InvoiceNumberPreffix; //undefined
var attempt_four= json_only.InvoiceNumberPreffix; //undefined

The php returns the correct one like above, and in js

axios.get('http://localhost/backend/get_templete.php', {
            params: {
                clciked_cpy: cpy
            }
          })
            .then(function(response) { //attempt above, need to put my ans in here; tried 
    var json_only = pre_cpy_cut.exec(response.data.toString());
            console.log("=]"   json_only);
} #reponse.data

in case you need, php:

$json = array(); 
while($row = mysqli_fetch_assoc($result)) { 
  $json[] = $row;


}
mysqli_free_result($result);
echo json_encode( $json, JSON_UNESCAPED_SLASHES ); //return as same as the picture above

#response.data already gives me json and stuff for me already. Why it still not return the column data I want? How to do that.

CodePudding user response:

I think you could gave more informations about your code, but for what I understood you aren't manipulating the JSON correctly. You need to parse the data retrieved by the axios request. Try:

axios.get('http://localhost/backend/get_templete.php', {
    params: {
        clciked_cpy: cpy
    }
  })
    .then(function(response) { 
        const parsedResponse = JSON.parse(response.data)
        // now you can access correctly the response data.
        console.log(parsedResponse.anyVariableYouWant)
   })
  • Related