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 get "Price: undefined CHF" is that the
dataobject returned by the API does not contain apriceproperty directly. To access the price information, you need to navigate through the JSON response correctly.Here's the modified success function:
success: function(data) { if (data.connections && data.connections.length > 0 && data.connections[0].legs) { var price = null; for (var i = 0; i < data.connections[0].legs.length; i++) { if (data.connections[0].legs[i].offers) { price = data.connections[0].legs[i].offers[0].price.amount; break; } } if (price) { $("#result").text("Price: " + price + " CHF"); } else { $("#result").text("Price: not available"); } } else { $("#result").text("Price: not available"); } },Now, it checks if there are connections and legs available in the response. If so, it iterates through the legs and tries to find the first available offer's price. If there's no price information, it will display "Price: not available".
Please update the success function in your code with the one provided above to fix the issue.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.