Utilizing Ajax for Updating Data in a RESTful API

Just dipping my toes into the world of API's and still struggling with JS/Ajax. Apologies if this question sounds silly.

I have managed to make the following code work, which I sourced from the developers documentation and made a few tweaks:

var token = getParameterByName('access_token');
    
    $.ajax({
        url: "https://api.myapp.de/api/v2/users/me",
        type: "GET",
        beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'bearer ' + token);},
        success: function(data) {
            console.log(data);
        }
    });

This script successfully retrieves my user information and displays it in the console.

Now, I am working on creating a web app (to improve my coding skills) that requires updating information using the PATCH method. How can I achieve this with Ajax?

I specifically need to update the following information in the JSON file: "id": "idIwantToUpdate", "ringNumber": 4. I've searched extensively online and came across some resources that might have the solution (e.g., https://www.rfc-editor.org/rfc/rfc7396), but they seem overly complex for me to grasp. After spending hours on this without much progress, is there anyone who can explain it in simpler terms? Appreciate any help!

Answer №1

Utilizing VanillaJS in your development, you have the option to integrate the external library Axios for additional functionality.

var token = getTokenFromQuery();

fetch('https://api.myapp.com/api/v2/users/me', {
      headers: {
        "Authorization": `Bearer ${token}`,
        "Content-type": "application/json; charset=UTF-8"
      },
      method: 'PATCH',
      body: JSON.stringify({
        id: userId,
        desiredIdToUpdate: desiredId,
        newRingNumber: updatedRingNumber
      });
    });

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

Having trouble transferring a JavaScript variable to PHP through AJAX and receiving an 'Undefined index' error

I'm struggling with a problem and I can't seem to find a solution – it's really frustrating! My goal is to transfer a JS variable to a PHP variable every time a key is pressed. Here's an excerpt from my PHP file (located at http://l ...

The background image spanning across the entire screen, not just confined to the center

view image details here Can anyone explain why my background image for the main game is displaying like this? I want to set it for the entire screen as I have different backgrounds planned for the menu of the game and the game itself. Any suggestions to ma ...

Ways to determine if a user is using a PC using JavaScript

I am developing a website using node.js that will also serve as the foundation for a mobile app. The idea is to have users access the website on their phones and use it like an app. But I want to implement a feature that detects when the site is being vi ...

Develop an application using ASP.NET MVC that allows for returning a JavascriptResult along with a

Imagine this situation When using MVC, it is quite simple to send a Javascript code back to the client for execution public ActionResult DoSomething() { return JavaScript("alert('Hello world!');"); } On the client side, ...

Choose a numeric value and then adjust it to display with exactly two decimal places

My goal is to create a code that achieves the following tasks: Add an ID to every nth child Round the number in each nth child to 2 decimal places Prefix the numbers with a pound sign (£) Loop through until all the nth children in a table are processed ...

Is it possible to erase the text area in MarkItUp?

I'm currently facing an issue with clearing my MarkItUp editor. I've successfully managed to insert text using the $.markItUp function, but I'm struggling to clear the text box afterward. I attempted to use replaceWith: "", however, I encoun ...

Managing and Streaming Music in a Rails Application

Currently, I am storing mp3s using paperclip and they only play back if I utilize Amazon S3. However, I am hesitant to use Amazon S3 because I am unsure how to secure the files. Now, I am reconsidering my approach as I need to secure the mp3s and provide ...

Search form with a variety of fields that allows for searching without needing to repeat the component for each condition

I am currently facing an issue with my form that consists of multiple fields, each used to search through an API and display matching data in a table below. While I have successfully implemented this for one field, I now need it to work for all fields with ...

Modifying classes using external file components

My navigation is stored in a separate file and linked to my main pages using a <?php require statement. Each menu item has a class on the <li> element that changes the color of the text to white instead of gray. Here's an example: <li cla ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Using jQuery Mobile and Phonegap on Android without Ajax integration

UPDATE: Workaround for JQuery Mobile + Phonegap AJAX Issues: The subdomains="true" property in config.xml is not functioning properly with Phonegap 2.9.0. When making a request to a subdomain, the response will be 200, but the success function of $.ajax w ...

Refresh a specific div element within an HTML file when the AJAX call is successful

After uploading the image, I want it to be displayed right away. To achieve this, I am looking to refresh the div with id="imagecontainer" within the success function of my ajax call. However, I would prefer not to rely on ("$id").load("href") as it does ...

Google map with a fully visible HTML element on top

When certain points on a Google map are clicked, a small popup box appears. This works fine in the regular small Google map mode. However, when the Google map is switched to full screen mode by clicking the full screen button (which is shown when `fullScr ...

Exploring the possibilities of utilizing various functions within an API endpoint

I am currently working on implementing an API GET Route to retrieve all the players from the team of the authenticated user. I believe my const variables are set up correctly, but I am uncertain if my approach is viable. I am attempting to use an async fun ...

Using axios to call a web API method from within a ReactJS web worker

Currently, I am utilizing Web Worker alongside ReactJS (Context API schema) and encountering a particular issue. The design of my Web API and Context is outlined below: WebWorker.js export default class WebWorker { constructor(worker) { let code = ...

Graphics vanishing during printing on document

Partaking in the Daily UI challenge to enhance my skills, but have encountered a hurdle. After entering numbers into the Card Number field, it appears to be replacing the images I uploaded. There might be something glaringly obvious that I'm missing ...

Unable to display the "detailed form" on the next page pagination of the DataTables

Every time I click on the class="detail" button, the detail-form displays perfectly. However, after clicking on the datatable paging to go to the next page (next record of datatable), the detail-form does not show up. I attempted to change the datatables c ...

Is there a way for me to locate a forum using a JWT Token?

I am searching for a way to retrieve forums using JWT Token. If a user has created 3 forums, I want to display them in a list. My Request is structured like this : ### http://localhost:8080/forum/getByOwnerID Authorization: Bearer {{adminToken}} Alternat ...

The API call within the app's service.js is not communicating with the page's controller

When my app accesses an API, it retrieves an array of 'card' objects and showcases each one on the user interface. The HTML file for card search is: card-search.html <div class="main-view container"> <h1>Card Search</h1> ...

Dealing with permission-based errors on the interface

I've been working on implementing authorization in my Angular project for hours now, following this example. I have created an HTTP interceptor to handle errors, but I'm unsure how to display these errors in my login view. I have tried passing a ...