Converting PHP code to Typescript

Currently, I am working on developing a function for firebase that will trigger a POST request to call a specific URL. While I have successfully implemented GET requests, tackling the POST method has proven to be more challenging.

I have some sample code utilizing fetch for making the call, but I am unsure about how to properly structure the parameters in the following snippet:

<?php

$url = 'https://profootballapi.com/schedule';

$api_key = '__YOUR__API__KEY__';

$query_string = 'api_key='.$api_key.'&year=2014&week=7&season_type=REG';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);

curl_close($ch);

echo $result;

?> 

My sample code takes the form of a POST request and here is what it looks like:

const apiKey = "myAPIkey";
const url = "https://profootballapi.com/schedule";
const response = await fetch(url, {
  method: 'POST',
  body: 'api_key'= apiKey, '&year=2018&week=7&season_typeRG';
  headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}});

if (!response.ok) {/* Handle */}

  // If you care about a response:
  if (response.body !== null) {
    functions.logger.log(response.body); 
  }

Answer №1

You are very close to the solution. However, there are some syntax errors in your TypeScript code:

curl_setopt($ch, CURLOPT_URL, $url);

You have correctly passed the URL.

curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);

This is simply providing an HTTP body for the request. While you attempted this in the fetch function, there are still some syntax issues present. You should replace the body with the following:

body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

This is unnecessary. The fetch function automatically handles returning the response in response.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

If this code will be running on a browser, it may not be possible to disable SSL verification. This command instructs the client to verify the server's SSL certificate. It is recommended to avoid disabling this security feature if possible.

After testing the code, I received somewhat reasonable results using Chrome's debugging tools:

const foo = async function () {
  const apiKey = "myAPIkey";
  const url = "https://profootballapi.com/schedule";
  const response = await fetch(url, {
    method: 'POST',
    body: `api_key=${apiKey}&year=2018&week=7&season_type=REG`,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  });

  return response;
}

foo().then(response => console.log(response));

Although it resulted in a 500 error, I suspect this could be due to an invalid API key. It is up to you to resolve how to send a valid API request.

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

Updating Multiple Divs with AJAX and PHP

Hey there, everyone! I found this code snippet on a website and need some help with it. var xmlhttp function showCustomer(str,str2) { xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("It seems like your browser doesn't support AJAX. Pleas ...

What is the proper method for displaying a table in php that contains a column with brackets in the column name?

How can I reference a table with columns containing brackets () and alias the column names? The table in question is material detail, and the columns are Panjang(mm) and Lebar(mm). In my Controller: public function GetDataID() { $id = $this->inp ...

What is the proper way to code a Curl request in PHP with jsonrpc parameters?

My curl command works perfectly from the SSH shell, but I can't seem to get it working with PHP Version 7.4.3. I've attempted multiple times using various examples found on the Internet, but all of them result in a blank html page when executed. ...

Guide on incorporating external .d.ts files for a module

I'm currently delving into the process of utilizing an external .d.ts file that is not included in the module. My intention is to make use of xlsx, which lacks its own type definitions, and instead incorporate them from the package @types/xlsx. Afte ...

The absence of a template or render function in a Vue.js 3 and Quasar 2 component has resulted in an

I am currently working on creating a dynamic component and passing a prop to it. However, I am encountering a warning message that says: Component is missing template or render function. Although the component is being rendered, I am still receiving the wa ...

Obtain the data from the hyperlink destination

Having some trouble extracting a value from an href link to use in my database operations. Unfortunately, I couldn't retrieve the desired value. Displayed below is the code for a button: <a class="btn btn-info" href="scheduleSetTime.php?id=&apo ...

The file link in Laravel on localhost at http://127.0.0.1:8000 is not functioning properly

Currently, I am utilizing php artisan serve to host on my local machine at . Despite successfully uploading files to the storage folder, when I attempt to create links like: public function getFeaturedImageLinkAttribute() { $file = $this- ...

How can a nullable variable be converted into an interface in TypeScript?

Encountered an issue while working on a vue3.x typescript project. The vue file structure is as follows: <template> <Comp ref="compRef" /> </template> <script lang="ts" setup> import {ref} from "vue& ...

default folder location for core modules adjustment

While experimenting with module imports in TypeScript, I encountered an issue when trying to import a module using import { Component, OnInit } from '@angular/core';. The compiler was successfully finding the module in the node_modules folder. I ...

Implementing real-time updates in React-Big-Calendar by dynamically adding events from Firebase without the need for manual refreshing

I'm currently facing a challenge with React-Big-Calendar as I strive to achieve real-time population of newly added events. The code snippet below helps me achieve this goal, as events are promptly displayed on the calendar upon creation/modification/ ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

The PHP script functions as expected when run locally, but encounters a 500 Internal Server Error when called through an

Currently, I have a PHP script in place that utilizes SendGrid to send emails. Interestingly, when I remove the $_POST commands and manually set values while running it locally from cmd, everything works smoothly. However, upon attempting to submit the for ...

Transferring PHP session data to another PHP script using an AJAX request

My primary goal is to assist users in recovering their forgotten passwords by using security questions. COMPLETED: I am validating the email entered on the forgot password page with an Ajax post request against the database. If a match is found, I retriev ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

Is there a way for me to utilize WordPress functions within my PHP script that is being called via AJAX?

Is there a way to make the 'POST' side branch of my PHP script 'WordPress-aware' so that I can call native WP functions from within it? The situation is as follows: I am trying to call a WordPress function (get_avatar($id)) from a PHP s ...

When adding a character before and after each character, make sure to skip spaces between two characters

Is there a way to add characters before and after a character, while ignoring whitespace between two or more characters? I attempted using this regular expression but it's not producing the desired outcome. $str = " echo '<pre> ...

The flynsarmy-sociallogin plugin for octoberCMS is experiencing an authentication issue with the Facebook API. The error message states that Facebook has returned an

I'm currently utilizing octoberCMS which is built on the Laravel framework. One of the plugins I have installed is the social plugin, as I want to enable users to sign in with their Facebook accounts on my website. Following the instructions provide ...

Preserving chosen options in a dropdown menu using PHP and HTML

I'm facing an issue with my code where the selected values in a dropdown menu revert back to default every time the page refreshes. How can I ensure that the selected values remain unchanged? Unfortunately, I am unable to utilize AJAX as per the user ...

What is the best way to pass multiple variables to a PHP file with AJAX using a GET request?

Can you help me figure out how to send both an I.D. value and a name value to a php file using ajax? Currently, I am successfully sending just the I.D. variable, however, when I attempt to add the name variable, the function stops working. The code that w ...

Tips for organizing an array of objects that contain null properties

Here is an array that I need help with: "data": { "risks": [ { "id": "22", "name": true, "surname": 0.5, "age": 0.75, "heigth" ...