Home > OS >  Not able to access Ajax post response Object properties
Not able to access Ajax post response Object properties

Time:01-02

I'm trying to fetch some data using POST method. The URL is sending proper response, which is of course an Object. When I try to access the responseJSON which is a property of the response Object, it returns undefined. But when try to do the same thing on console, it works fine! objectName.responseJSON works properly in this case. But why it's not working the same way while I use it in my code? Also, on a button click, which changes a little bit of the fetched data, it again works fine. Means... that response Object and it's properties work fine on a button click but on $(document).ready or $(document).load. Why this is happening?

//Fetching data from URL
oldData = $.post("{$_url}reports/get_all_transactions", {
            'startDate': document.getElementById('startDate').value,
            'endDate': document.getElementById('endDate').value
        });

//Printing the result on Console
$(document).ready(function() {
            console.log(oldData); //This prints the whole response object
            console.log(oldData.responseJSON); //This outputs 'undefined'
        })

I even tried JSON.parse(), JSON.stringify() and their combination on the object. But on Stringify, it's just converting the first property of the object into String and not the whole object. And the Parse method returns error.

Then how can I access my desired object property?

CodePudding user response:

Better to use native fetch instead, no need for jQuery these days.

  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        startDate : document.getElementById('startDate').value,
        endDate   : document.getElementById('endDate').value
    })
  });
  const text = await response.text();
  const obj = JSON.parse(text)
  

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

  • Related