PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to declare a variable in axios get json

 October 14, 2022     axios, get, http, javascript, php     No comments   

Issue

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.


Solution

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)
   })


Answered By - Bernardo Moraes
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing