Utilizing the fetch() method to transmit GET data within the body rather than directly embedding it in the URL

I am in the process of converting this jQuery call to vanilla JavaScript using fetch() following the guidance provided by MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options).

        $.ajax(
        {
            method: "GET",
            url: CB_ABS_URI + "ajax/get-checkin.php",
            dataType: "json",
            data: { DwellingUnitID:DwellingUnitID },
        })

and I wish to change it to:

// Illustrative POST method example:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'GET', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *client
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return await response.json(); // transforms JSON response into native JavaScript objects
}

        postData(CB_ABS_URI + "ajax/get-checkin.php", { DwellingUnitID: DwellingUnitID })
          .then((data) => {
            console.log(data); // Data parsed from JSON by `response.json()` call
          });

However, I am experiencing difficulties sending GET data through the body. Is modifying ajax/get-checkin.php to incorporate the query my sole option?

Answer №1

I'm encountering difficulty sending GET data within the request body

fetch clearly distinguishes between the query string in the URL and the data in the request body (unlike jQuery which blends them based on the request method).

Is including the query in ajax/get-checkin.php the only solution?

Absolutely, refer to the official documentation:

If you need to manipulate URL query parameters:

var url = new URL("https://geo.example.org/api"),
    params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

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

Tips on harnessing the power of AngularJS $scope

In need of assistance! I have a paragraph and a counter that I want to update whenever the user clicks on the paragraph, all using AngularJS. Below is the code snippet I've come up with: <!DOCTYPE html> <html> <head> <script src= ...

Webster Barron code script

I'm attempting to replicate the concept of this video https://www.superhi.com/video/barron-webster using text, but I am encountering difficulties in achieving the desired effect. The design text is currently overlapping my name and displaying in rev ...

Form that adjusts input fields according to the selected input value

I am in need of creating a dynamic web form where users can select a category and based on their selection, new input fields will appear. I believe this involves using JavaScript, but my searches on GitHub and Stack Overflow have not yielded a suitable sol ...

Error: Unable to access the lexical declaration 'useStyles' before it has been initialized in the React Collapse Component. This issue occurred while trying to fetch data using axios in the Material-

I am facing an issue while trying to display data fetched from the backend (array with objects) and hide a portion of it under a collapsible button using Material-UI in React. The code works perfectly when all lines are written within a single component ca ...

Launch a fresh fancybox once the previous one has exited

I am currently facing an issue with my password change process through a fancybox window. Whenever a user enters the wrong password, a "Wrong Password" iframe opens up. However, the challenge arises when I try to reopen the "Password Change" iframe after c ...

Can a custom function be executed using setTimeout in Node.js?

I am currently facing an issue with stopping the execution of my code for 2 seconds so that all ongoing animations can finish. I am attempting to implement a delay using setTimeout in Node.js. Here is what I have tried: this.userActivity = function(a,b, ...

Authentication not being triggered by Adal.js

I have been attempting to incorporate adal.js into my application. Here is the code I am using. Can someone please help me understand why the authentication process is not being triggered? var app = angular.module('TestWebApp', [ 'ngRout ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

The JSON.Parse function in Google Apps Script is leading to a 'server connection error' message during debugging

I'm not a professional developer, but I do code occasionally. Currently, I am working on some Apps Script code to interact with an API and store the data in SQL. Most of it is working fine, but I have encountered an issue while debugging in the Apps S ...

The mystery behind React rendering twice, even when React strict mode is disabled

My code is error-free, but React seems to render this component twice for some reason. I can't figure out why. Here is an image showcasing the issue: https://i.stack.imgur.com/hKvug.png Index.js Page : import LandingPage from '../components/Ho ...

Error: The JavaScript variable 'undefined' is being used as a function, which is incorrect. This error occurs when trying to execute the function `mockBackend

I am currently working on unit testing an AngularJS controller using Karma and Jasmine. Below is the test suite I have created: describe('Controllers', function(){ var $scope, ctrl; beforeEach(module('curriculumModule')); ...

The $.getJSON function seems to be malfunctioning and is not returning the expected data, instead, showing [object Object

I seem to be encountering a common issue with my ajax call not retrieving the JSON data. It appears that it may be due to an array and not using the correct index, although I am indeed utilizing an index on the front-end. Despite trying various solutions f ...

Django is unable to establish sessionid Cookies due to Webpack's restrictions

After setting up my React application with Webpack and Django for Backend, I encountered an issue with session authorization. Whenever I attempt to make a request, I receive a 200 OK status Response, but the session-id is visible in the Set-Cookie header, ...

Adonis 5 and Vue encountering the error message 'E_ROUTE_NOT_FOUND'

I am currently working on a project using Adonis v5 as the backend and Vue 2 as the frontend. I have encountered an issue where, after building the Vue frontend into the public Adonis folder, accessing a specific route directly in the browser results in an ...

Enhanced User Experience Through Triggered Content Recommendations based on Scrolling Patterns

When a user scrolls beyond a certain point on a webpage, I would like a recommended content popup to slide out from the right side at the bottom of the page. An excellent example can be seen on USAToday where a blue recommended box appears as you scroll d ...

"Using jQuery's Ajax feature to efficiently delete a record

I am currently facing an issue with deleting a value from a comma-separated string in a table. The script responsible for deletion (delete_url.php) functions correctly when I manually set the post values, however, I am encountering difficulty in passing th ...

Evaluating the functionality of Express Js Server with mocha and chai

I'm currently struggling to properly close the server connection in my Express server when testing it with Mocha and Chai. It seems that even after the test is completed, the server connection remains open and hangs. Index.js const express = require( ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

Create and adapt dynamic tiles to fit within the available width

I am looking to create a dynamic tile (div) that adjusts based on the number of users available, similar to how it works in Microsoft Teams meetings. For example, if there is only one user, the div should occupy the full screen. When there are two users ...