skip to Main Content

i want to get json response from server on button click and parse to div, but i stuck how to do it.

<button type="submit" id="btPay" name="btPay"> Go for Payment </button><br>
<div id="notif"></div>

My external js as follow:

  var resJson;
  async function myFunction() {
    var settings = {
      "url": "urlApi",
      "method": "POST",
      "timeout": 0,
      "headers": {"headerContents"},
      "data": JSON.stringify({"inputData"})
    };
    
    $.ajax(settings).done(function (response) {
      resJson = $.parseJSON(response);
    });
  }

  async function setResponse() {
    $("#notif").html(resJson);
  }

  $('#btPay').bind('click', function() {
    myFunction();    
    setResponse();
  })

The problem is i cannot get Json response value. based my js, do i missed something?

Thanks and appreciate for help.

3

Answers


  1. Chosen as BEST ANSWER

    when try in postman with data:

    json.stringfy ({
      "external_id": "invoice-{{$timestamp}}",
      "amount": 1800000,
      "payer_email": "[email protected]",
      "description": "Invoice Demo #123",
      "payment_methods": [
        "CREDIT_CARD"
      ]
    )
    

    The response I get like follow:

    {
      "id": "658xxx",
      "external_id": "invoice-1703409000",
      "user_id": "599xxx",
      "status": "PENDING",
      "merchant_name": "Test Cashpay",
      "merchant_profile_picture_url": "https://url",
      "amount": 1800000,
      "payer_email": "[email protected]",
      "description": "Invoice Demo #123",
      "expiry_date": "2023-12-25T09:10:00.915Z",
      "invoice_url": "https://url",
      "available_banks": [],
      "available_retail_outlets": [],
      "available_ewallets": [],
      "available_qr_codes": [],
      "available_direct_debits": [],
      "available_paylaters": [],
      "should_exclude_credit_card": false,
      "should_send_email": false,
      "created": "2023-12-24T09:10:01.030Z",
      "updated": "2023-12-24T09:10:01.030Z",
      "currency": "USD"
    }
    

  2. I think it is better to use await to get the answer to get the answer!
    just like this:

    $.ajax(settings).done(function(response) {
      resJson = await $.parseJSON(response);
    });
    async function setResponse() {
     await $("#notif").html(resJson);
    }
    

    I hope it helped you.

    Login or Signup to reply.
  3. In your event handler for the button click you call the functions myFunction() and setResponse() directly one after the other. The second function will be called before the first will have received the results from the AJAX call. To make it work the setResponse() function needs to be called from within the done() callback function in your AJAX call in myFunction():

    // var resJson;
      function myFunction() {
    var settings = { // simplified AJAX call to turn this into a workable snippet
      "url": "https://dummyjson.com/users/13",
      "method": "GET"
    };
    
    $.ajax(settings).done(function (response) {
      // `response` contains already a JavaScript object,
      // parsing it again will not work. 
      // Instead I convert it back into a JSON string:
      let resJson = JSON.stringify(response);
      setResponse(resJson);
    });
      }
    
      function setResponse(html) {
        $("#notif").html(html);
      }
    
      $('#btPay').bind('click', function() {
        myFunction();    
        // setResponse();
      })
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <button id="btPay">get the data</button>
    <div id="notif"></div>

    Another change I made is that I stopped using the global variable respJson. The JSON string is stored in a local variable of the same name and used as the first parameter in the function call setResponse(respJson).

    Since the deferred jQuery function $.ajax() has not been called with the await keyword (but is resolved in a done() callback instead) there is no need for the surrounding function to be an asynchronous one and the async keyword can be safely dropped.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search