Ajax response is undefined

Viewed 67

I'm a newbie coder. I'm trying to insert the var cPrice in my front-end HTML page. However, it is undefined and I can't figure out why.

///////////// Display Pop-up finciton //////////////////
//Start//

$('#button1').on('click', function() {
// Show the popup
$('#openPopup').show();
// Get the symbol and name and show it in the popup
const symbolID = document.getElementById("symbolSearch").value.toUpperCase();
document.getElementById("currentSymbol").innerHTML = symbolID;



$.get("http://localhost:5000/placeOrder", function(err, price) {
    console.log(price.currentPrice);

    var cPrice = price.currentPrice // On the server-side it prints the correct value.

    console.log(cPrice) // However, here the front-end value is undefined.
    if (err) { console.log(err) } else {
        document.getElementById("currPrice").innerHTML = cPrice
    }

});



// Execute the function for retrieving the price
//userAction();
1 Answers

Read the docs: jQuery.get() for the success function callback:
the first argument is the PlainObject data

jQuery.get( url [, data ] [, success ] [, dataType ] )
fn success
Type: Function( data, textStatus, jqXHR )
A callback function that is executed if the request succeeds. Required if dataType is provided, but you can use null or jQuery.noop as a placeholder.

There's also a

Deprecation notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

therefore you'd better go with a more readable code using .done() and .fail():

$.get("http://localhost:5000/placeOrder")
  .done((data) => {
    console.log(data);
    console.log(data.currentPrice);
  })
  .fail((jqXHR, textStatus, errorThrown) => {
    console.log(jqXHR);
  }); 
Related