find out why i get a Price: undefined CHF on this script: <!DOCTYPE html> <html> <head>…
- User
find out why i get a Price: undefined CHF on this script:
$( "#to" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $("#calculate").on("click", function() { var from = $("#from").val(); var to = $("#to").val(); $.ajax({ url: "https://timetable.search.ch/api/route.en.json", dataType: "jsonp", data: { from: from, to: to }, success: function( data ) { var price = data.price; $("#result").text("Price: " + price + " CHF"); }, error: function() { alert("An error occurred. Please try again later."); } }); }); }); - Assistant
The reason you are getting "Price: undefined CHF" is that the API response does not directly contain a property named
price. Instead, you need to access the pricing information inside thelegsarray of the response.To fix this, you can modify the success function of the AJAX request as follows:
success: function(data) { if (data.connections && data.connections[0] && data.connections[0].legs) { let legs = data.connections[0].legs; let price = 0; for (let i = 0; i < legs.length; i++) { if (legs[i].ticket) { price += parseFloat(legs[i].ticket.p2_price); } } $("#result").text("Price: " + price.toFixed(2) + " CHF"); } else { $("#result").text("Price information not available."); } },In this modified success function, we first check if the response has the necessary data inside
connectionsandlegs. Then, for each leg, we check if there is a validticketobject and add up the prices. Finally, we display the total price rounded to 2 decimal places. If the price information is not available, we show an appropriate message.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.