Guide to initiating an AJAX request to the GraphHopper Route Optimization API

Currently, I am exploring the functionalities of GraphHopper Route Optimization API for solving Vehicle Routing Problems (VRP) with pickups and deliveries. To test it out, I am using an example from . The specific request I am making is as follows:

var vrp = {
      "vehicles": [
        {
          "vehicle_id": "my_vehicle",
          "start_address": {
            "location_id": "berlin",
            "lon": 13.406,
            "lat": 52.537
          }
        }
      ],
      "services": [
        {
          "id": "hamburg",
          "name": "visit_hamburg",
          "address": {
            "location_id": "hamburg",
            "lon": 9.999,
            "lat": 53.552
          }
        },
        {
          "id": "munich",
          "name": "visit_munich",
          "address": {
            "location_id": "munich",
            "lon": 11.57,
            "lat": 48.145
          }
        },
        {
          "id": "cologne",
          "name": "visit_cologne",
          "address": {
            "location_id": "cologne",
            "lon": 6.957,
            "lat": 50.936
          }
        },
        {
          "id": "frankfurt",
          "name": "visit_frankfurt",
          "address": {
            "location_id": "frankfurt",
            "lon": 8.67,
            "lat": 50.109
          }
        }
      ]
    };

    $.ajax({
    beforeSend: function(xhrObj){
        xhrObj.setRequestHeader("Content-Type","application/json");
        xhrObj.setRequestHeader("Accept","application/json");
    },
    type: "POST",
    url: 'https://graphhopper.com/api/1/vrp/optimize?key=[...]',       
    data: vrp,               
    dataType: "json",
    success: function(json){
       console.log(json);
    }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upon sending the request, I receive the following response: screenshot

I am facing an issue with this setup. Any insights on what the problem could be?

Answer №1

I stumbled upon the solution in a different Stack Overflow question Send JSON data with jQuery.

The key is to simply utilize the following code: data: JSON.stringify(vrp)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Build a Node.js application with Express to host static files

I am attempting to provide my static files "web.html" and "mobile.html", but I want them to be served only if the user is accessing from a web or mobile device. After some research, I came up with this code: var express = require('express'); va ...

Troubleshooting a problem with AJAX returning the data

Currently, I have a javascript function that calls another javascript function called zConvertEmplidtoRowid. This second function utilizes an ajax call to execute a query and retrieve data stored in a variable named rowid. My challenge lies in figuring out ...

Having trouble adjusting the color on Material UI select in ReactJS?

Here is the code snippet I am working with: const useStyles = makeStyles({ select: { '&:before': { borderColor: 'white', }, '&:after': { borderColor: 'white&apos ...

The width of Highcharts increases proportionally to the growth of the chart's width

I want to create a highcharts graph where the width increases as data points increase. Currently, I have: I am using vuejs with highcharts, but it should work similarly with jquery or other frameworks. <div class="col-md-6" style= ...

Swapping out 'useResult' in graphql for Vue and Apollo: A step-by-step guide

I need to replace the useResult function that is fetching data from GraphQL with a computed function. const locationOptions = useResult( result, [], ({ getLocations }): Option[] => formatOptions(getLocations) ) Instead, I want ...

What is the best way to utilize recently added modules in React if they are not listed in the package.json "dependencies" section?

[I have updated my question to provide more details] As a newcomer to working with React, I may be asking a basic question. Recently, I installed several modules and will use one (example: @react-google-maps/api) for clarification. In my PC's termin ...

Iterate through an HTML table and transfer matching items along with their corresponding calculated amounts to a separate table

<html> <body> <div> <table border="1" id="topTable"> <thead> <th>Item</th> <th>Sold</th> </thead> <tbody id="topTableBody"> <tr> ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Display an alert message using alert() if duplicate data is submitted through ajax

I'm using a form and jQuery to submit the form via AJAX. $("form#form").submit(function (event) { //submitting vendor name event.preventDefault(); var formData = new FormData($(this)[0]); //validation for duplicates goes here ...

Watch as objects materialize after using the zoom function in THREE.JS

I am facing an issue with THREE.JS involving the addition of 3D text to my scene using the following code: var loader = new THREE.FontLoader(); loader.load( '3rdparty/three.js/fonts/helvetiker_regular.typeface.json',function ( font ) { var ma ...

CSRF validation did not pass. The request has been cancelled. The failure occurred due to either a missing or incorrect CSRF token

Upon hitting the submit button in the login form, I encountered the following error message: Forbidden (403) CSRF verification failed. Request aborted. CSRF token missing or incorrect. settings.py MIDDLEWARE = [ 'django.middleware.security.Secur ...

Utilizing Jquery Ajax to retrieve profile images from Twitter and Facebook, alongside handling HTTP

I've come across various discussions about the challenges of working with jquery ajax and dealing with http 302 redirects on different platforms, including Stack Overflow and other websites. Some sources claim that it's an issue without a viable ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Exploring the power of Django: Leveraging AJAX requests and utilizing path

I am currently exploring ways to pass variables to a specific JavaScript file that initiates an AJAX request within Django. Assume we have a URL with a path parameter linking to a particular view: url(r'^post/(?P<post_id>\d+)/$', Tem ...

"Encountering an unidentified custom element in Vue 2 while exploring Vue libraries

In my Vue project, I have integrated libraries like FusionCharts and VueProgressBar. However, I encountered an error in my console: Unknown custom element: <vue-progress-bar> - did you register the component correctly? For recursive components, make ...

The dropdown menu is being filled with 'undefined' values when using AJAX as the data source in Typeahead

I've been trying to implement typeahead functionality, but I can't seem to find a solution on Stack Overflow that works for me. I am using an ajax source to retrieve JSON data for my products, however the typeahead feature is returning all matche ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

Are undefined variables in jquery safe to use for ensuring compatibility across different platforms and for potential future applications?

Question Example: In the first lengthy if statement, if the first two conditions are met, there could be various scenarios where $(this).val().split("@")[1].split(".")[1] may be undefined. Is it considered safe to utilize this approach with javascript/jqu ...

Troubleshooting the React D3 Component Error: "Encountered issue with BarChart: Unable to access property 'map' on undefined"

There seems to be a recurring type error in the bundle.js file. "Cannot read property 'map' of undefined" appears in the bundle.js for BarChart. It seems like an object is undefined and attempting to map to an array. However, it's unclear w ...