Why ReqRes response to my POST request doesn’t return the values I included?

I’m learning about API etc, and I was trying to do a simple POST request to ReqRes.in. Although the POST response suggests that the request was successful, it doesn’t include the data I’m sending, which is not the behavior expected according to the documentation…

My code:

<script>
function startAPI() {
  let xhttp;
  xhttp = new XMLHttpRequest;
  xhttp.onreadystatechange = () => {
    if (xhttp.readyState == 4) {
      if (xhttp.status == 201) {
        let reqresponse = JSON.parse(xhttp.responseText);
        console.log(reqresponse)
      };
    };
  };
  let newUser = {
    name: document.querySelector("#userName").value,
    email: document.querySelector("#userEmail").value,
  };
  xhttp.open('POST', 'https://reqres.in/api/users', true);
  xhttp.send(JSON.stringify(newUser));
};
</script>
<body>
<form onsubmit="startAPI(); return false">
  <p>
    <label for="userName">Nome: </label>
    <input type="text" name="userName" id="userName">
  </p>
  <p>
    <label for="userEmail">Email: </label>
    <input type="email" name="userEmail" id="userEmail">
  </p>
  <p>
    <input type="submit" value="Create User">
  </p>
</form>
</body>

On submitting, I was expecting this response:

Object { name: "User Input Value", email: "Email Input Value", id: "848", createdAt: "2024-05-09T01:17:49.098Z" }

But what I receive is:

Object { id: "848", createdAt: "2024-05-09T01:17:49.098Z" }

I tested several combinations of ID, values capturing, methods of form submit, variables and function names, removal of If’s in the function etc, nothing worked.
What am I doing wrong?

Thanks everyone, peace.

Extracting page metadata when converting DOCX to HTML (javascript)

I’m working on a Vue page where I need to convert DOCX files to HTML while preserving page metadata (e.g., page numbers, section breaks).

I’ve explored libraries like Mammoth.js, but it seems they don’t handle page metadata extraction. Other libraries I found primarily focus on DOCX to HTML conversion without retaining pagination information. The issue is still open here.

vue-document-editor offers functionalities for creating page breaks using arrays, but this doesn’t support docx conversion to html.

Is there a way to achieve DOCX to HTML conversion with page metadata extraction (preferably in JS/Vue application)?

How to execute a function if a loop is taking a long time?

I have an AJAX call, and the result is processed by a callback. This may be real quick, or take some time. If the callback lasts more than 3 seconds, I want to display an image (or a text) that tell the user “please wait!”.

This is what I have:

var process_timer, is_processing = false;
var request = createCORSRequest();
if (request) {
    // This SETTIMEOUT function should execute 3 seconds after REQUEST.SEND()
    process_timer = setTimeout(function(){
        if (is_processing) {
            // It's still processing, so we show the message
            show_please_wait();
        }
    },3000);
    request.onload = function() {
        process(JSON.parse(request.responseText));
        // OK, processing is done, so we reset everything
        is_processing = false;
        // If SETTIMEOUT didn't fire yet, we cancel it so no image will ever show
        clearTimeout(process_timer);
        // We hide the message anyway, just in case it was displayed
        hide_please_wait();
    };
    is_processing = true;
    request.send();
}

What is happening:

  • REQUEST.SEND() works fine
  • REQUEST.ONLOAD() works fine
  • … but the SHOW_PLEASE_WAIT() function never gets executed, no matter how long the process lasts.
    What am I doing wrong?

Can we make a button stay still when you move your screen around or scroll up/down on a tablet?

This code work well on a traditional computer with non-touch screen.

`<style>
    #stayFixedDiv{
      background-color: #FBD603;
      position: fixed;
      left: 40px;
    }
    </style>

    <body>
    <div id ="stayFixedDiv">
     <a   style="font-size: 35px; text-decoration: none" > Pause Video</a>
    </div>

    </body>
`

But that code does not work on a tablet. When I move the screen on my tablet around, the button doesn’t stay still as on my desktop.

How can we achieve that?

Can you recommend a good LAMP working environment ( i.e. Frameworks, Libraries)?

I am getting back into programming again after a long hiatus.

I am working on a personal website that will sell music.

Previously I was making websites from scratch using LAMP stack and maybe occasional use of JQuery. I am basically a beginner.

The most ambitious website I created was a shopping website selling limited items, only a few pages and every page was written from scratch copying code from other pages and repeating them on every page (all the design elements and formatting).

Can anyone recommend a good group of libraries or Framework, without a long learning curve, to aid me in my development. I just want to avoid having to repeat elements on multiple pages and be able to modify the look/’theme’ of my website from a central place.

This is not for an enterprise, just a small business and I will be the only coder.

I have tried development without the use of Frameworks or libraries.

errer when running minecraft mod

Execution failed for task ‘:runClient’.

Process ‘command ‘C:Program FilesJavajdk-17binjava.exe” finished with non-zero exit value 1

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –scan to get full insights.

minecraft to load properly

Automatically editing mod-edited posts?

Does anyone want to write to a bot that automatically edits my answers/questions for me? The mods like M&M and pogman keep reverting my openai protest edits, and I’m gonna have to go to sleep eventually.

The bot should either let you log-in, or maybe use your firefox cookies to pretend to be you.

React Table not Updating Automatically after CRUD Operations

I’m developing a web app using React where I have a table that displays a list of clients. The table should update automatically after performing CRUD operations on the clients. However, I’m encountering a specific issue: after adding or deleting a client, the table doesn’t update automatically. It only works correctly when I edit an existing client. To make the other methods work, I have to leave the page and come back to the section.

As I mentioned, the request reaches the API and returns the expected information, but updating the table fails, even though the method is theoretically implemented.

This is my code:

const loadClients = async () => {
  try {
    const clientsData = await salesApi.getClients();
    const sortedClients = clientsData.sort((a, b) => a.id - b.id);
    setClients(sortedClients);
  } catch (error) {
    console.error('Error fetching clients:', error);
  }
};

const handleEditClick = (client) => {
  setEditingClient(client);
};

const handleCancelEdit = () => {
  setEditingClient(null);
};

const handleClientSubmit = async (formData) => {
  try {
    await salesApi.addClient({
      firstName: formData.firstName,
      secondName: formData.secondName,
      firstLastName: formData.firstLastName,
      secondLastName: formData.secondLastName,
      identificationNumber: formData.identificationNumber,
      isCreditCandidate: formData.isCreditCandidate,
    });
    console.log('Client successfully registered:', formData);
    loadClients();
  } catch (error) {
    console.error('Error adding client:', error.message);
  }
};

const handleSaveEdit = async (editedClient) => {
  try {
    console.log('Data to send to server:', editedClient);

    await salesApi.updateClient(editedClient);

    console.log('Client successfully updated:', editedClient);

    loadClients();
  } catch (error) {
    console.error('Error updating client:', error);
  }
};

const handleDeleteClient = async (clientId) => {
  try {
    console.log('Attempting to delete client with ID:', clientId);
    const response = await salesApi.deleteClient(clientId);

    console.log('Delete response:', response);

    if (response.status === 200) {
      console.log('Client successfully deleted:', clientId);
      loadClients();
    } else {
      console.error('Error deleting client:', response.statusText);
    }
  } catch (error) {
    console.error('Error deleting client:', error);
  }
};

return (
  <MainPageContainer>
    <h1>Clients</h1>
    {(editingClient || !editingClient) && (
      <ClientsRegistration
        onSubmit={(formData) => {
          if (editingClient) {
            handleSaveEdit({ ...editingClient, ...formData });
          } else {
            handleClientSubmit(formData);
          }
        }}
        onCancel={handleCancelEdit}
      />
    )}
    <ClientsTable
      clients={clients}
      onEditClick={handleEditClick}
      onDeleteClick={handleDeleteClient}
      handleSaveEdit={handleSaveEdit}
    />
  </MainPageContainer>
);
};

Any advice or help on how to approach this issue would be greatly appreciated.

Extract a string from a format

I am currently working in javascript and am curious on how to find part of a string in a format. How would I extract the information as a string if its in another string such as
“[AUTOFLIP] (Method): (Item)! (Buy Value) -> (Sell value)”
How would I find everything in parentheses if I know everything out of it will remain the same (the values are both shortened numbers)?

I tried to use indexOf to get the last letter of the words before/after the item I wanted to find and then use substring to find whats betweeen them but that didnt end up working well

React TinyMCE editor state is not updating like a normal input component

I have been at this for a while so any help is appreciated!

I have an rich text editor modal with a input box that contains an existing title, and a TinyMCE editor that contains an existing note entry/body. The input text can be edited, but when changes are made to the text body they are immediately reverted, the state is not being set with the new changes.

export const EditorModalContext = createContext(undefined);

function App() {
    const [openEditor, setOpenEditor] = useState(false);
    const [notes, setNotes] = useState([])
    const [currentNote, setCurrentNote] = useState({
        _id: "",
        title: "",
        entry: "",
    });

    const handleOpenEditor = () => setOpenEditor(!openEditor);

    const editorRef = useRef(null);

    const getNotes = useCallback(async () => {
        try {
            const res = await axios.get("/notes");
            setNotes(res.data);
        } catch (err) {
            console.error(err);
        }
    }, []);

    useEffect(() => {
        getNotes();
    }, [getNotes]);

    const onChange = (e) => {
        setCurrentNote((prev) => {
            let currentNote = { ...prev };
            currentNote[`${e.target.id}`] = e.target.value;
            return currentNote;
        });
    };

    return (
        <div className="flex flex-col gap-4 p-4">
            <Dialog>
                <Input
                    variant="outlined"
                    placeholder="Title"
                    value={currentNote.title}
                    id="title"
                    onChange={onChange}
                />
                <Editor
                    tinymceScriptSrc="/tinymce/tinymce.min.js"
                    onInit={(evt, editor) => (editorRef.current = editor)}
                    disableEnforceFocus={true}
                    value={currentNote.entry}
                    id="entry"
                    onChange={onChange}
                />
            </Dialog>
            <EditorModalContext.Provider value={{ setOpenEditor, setCurrentNote }}>
                <Header />
                <NoteCards notes={notes} />
            </EditorModalContext.Provider>
        </div>
    );
}

export default App;

This is more or less the code with some unecessary bits removed. The currentNote is first set in another component and is passed as context when the editor modal is opened using a button in that component.

Does this have something to do with how TinyMCE designed its editor or do I have a runtime error somewhere in my code?

VueJS User cant alter checkbox state

I have the following script which use to work perfectly fine.

<div id="inspectionList" class="row m-0 p-0" v-if="app.getOption('InspectionChecklists')">
<div v-for="(checklist, index) in (JSON.parse(app.getOption('InspectionChecklists')))[app.store.AddAsset_Module][1]">
     <div class="col-12 m-2 p-1 mb-2" v-for="(inspection, index) in checklist">

          <input
          type="checkbox"
          v-bind:name="index"
          v-bind:class="'form-check-input'"
          v-bind:id="index"
          v-bind:value="index"
          v-model="app.store.AddAsset_Type_inspections"
          style="height:30px; width:30px; accent-color: #5873fe;">
           <label v-bind:for="index" style="position:relative; top:-5px">{{inspection.n}}</label>
     </div>
</div>

</div>
<div id="debugInfo"  v-if="app.store.debug">
Debug: {{ app.store.debug }}
<span>Checked names: {{ app.store.AddAsset_Type_inspections }}</span>
</div>

The script generates a list of checkboxes, and automatically checks any of them that are in the array store in app.store.AddAsset_Type_inspections

app.store.AddAsset_Type_inspections has the following data for example:

Checked names: [
259,
9,
68,
45,
41,
264,
55,
13,
262,
271,
270,
1,
23,
260,
3,
44,
63,
24,
56,
261,
19,
30,
18,
31,
17,
2,
14,
29,
46,
36,
26,
8,
25,
33,
35,
28,
282,
52,
50,
51,
49,
53
]

For some reason, after updating VueJS core library to 3.4.27, the checkboxes automatically check as needed – however users cant manually check or uncheck any of the check boxes.

Things i’ve tried:

  • I added a standard <input type="checkbox" name="test"> checkbox, and it is possible to check and uncheck this without an issue.

  • If I remove v-model="app.store.AddAsset_Type_inspections" so that checkboxes don’t automatically get checked, then it’s possible for a user to check and uncheck any of the boxes without an issue.

  • I’ve looked for any console errors, and no errors are generated

Heres a screenshot of the checkboxes which shows the auto-checked ones, and additionally, the highlight after clicking a checkbox that shows the checkbox isn’t disabled.

enter image description here

How to have both popups and side panels for a chrome extension?

I’d like to have a popup that allows the extension to be turn on/off for specific sites, as well as a side panel to display more information.

My current manifest.json is below. At the moment, clicking on the extension icon in the toolbar (top right of chrome) always opens the side panel. I have to disable the side panel before I can see the popup.

"action": {
    "default_title": "Click to open extension",
    "default_popup": "popup.html"
  },
  "host_permissions": [
    "https://developer.chrome.com/*"
  ],
  "side_panel": {
    "default_path": "sidepanel.html"
  },

Angular17 hosting project presents this error: ReferenceError: caches is not defined

I made a project using the MapTiler library. And when putting the project on the hosting service, the error appears:

ReferenceError: caches is not defined
    at main-FAGKM46X.js:584:229302
    at Generator.next (<anonymous>)
    at main-FAGKM46X.js:584:228898
    at new t (polyfills-RT5I6R6G.js:2:2236)
    at xp (main-FAGKM46X.js:584:228718)
    at UT (main-FAGKM46X.js:584:229256)
    at main-FAGKM46X.js:584:230307
    at Generator.next (<anonymous>)
    at main-FAGKM46X.js:584:228898
    at new t (polyfills-RT5I6R6G.js:2:2236)

With this error, the map style does not load either.

The program accesses an API that takes the current location of the ISS and shows it on the map

Component HTML

<div class="map-container">
    <div class="info-container" >
        <span>Latitude: {{locateISS?.iss_position?.latitude}}</span>
        <span>Longitude: {{locateISS?.iss_position?.longitude}}</span>
        <span>Velocidade: {{speed}}km/h</span>
    </div>

    <div class="map-wrap">
        <div class="map" #map></div>
    </div>
    <div class="icon" #icon></div>
</div>

Component TS

    import {AfterViewInit, Component, ElementRef, NgZone, OnDestroy, OnInit, PLATFORM_ID, ViewChild, inject, signal } from '@angular/core';    
    import { IssService } from '../../../services/iss.service';
    import { Map, MapStyle, config, Marker, Popup} from '@maptiler/sdk';
    import '@maptiler/sdk/dist/maptiler-sdk.css';
    import { isPlatformBrowser } from '@angular/common';
    import { LocateISS } from '../models/locate.model';

    @Component({
      selector: 'app-iss-map',
      standalone: true,
      imports: [],
      templateUrl: './iss-map.component.html',
      styleUrl: './iss-map.component.scss' 
    })
    export class IssMapComponent  implements OnInit, AfterViewInit, OnDestroy{

      map?:Map
      private issService = inject(IssService)
      locateISS?:LocateISS
      issIcon:any
      speed:Number = 0
      marker:any
      isBrowser = signal(false);
      platformId = inject(PLATFORM_ID)

      @ViewChild('map')
      private mapContainer!: ElementRef<HTMLElement>;

      @ViewChild('icon')
      private elementIcon!: ElementRef<HTMLElement>;
  
      constructor(){
        this.isBrowser.set(isPlatformBrowser(this.platformId))
        if(this.isBrowser())
          inject(NgZone).runOutsideAngular(() => {
            setInterval(() => this.updateMarker(), 1000);
          })
      }
  
      ngOnInit(): void {
        config.apiKey = 'wGRvHdO3WKYFTWYfoxL5'
        this.issService.getLocate().subscribe(locate => this.locateISS = locate)  
    
      }
  
      ngAfterViewInit(): void {
        this.map = new Map({
          container: this.mapContainer.nativeElement,
          style: MapStyle.STREETS,
          center: [ Number(this.locateISS?.iss_position.longitude), Number(this.locateISS?.iss_position.latitude)],
          zoom: 2
        });
        this.issIcon = new Marker({element : this.elementIcon.nativeElement})
        .setLngLat([Number(this.locateISS?.iss_position.longitude!), Number(this.locateISS?.iss_position.latitude!)])
        .setPopup(new Popup().setHTML("<span style='color:black; padding:20px;'>ISS</span>"))
        .addTo(this.map!); 
      }
  
      ngOnDestroy(): void {
        this.map?.remove();
      }
  
      updateMarker(){
       const oldLat = this.locateISS?.iss_position.latitude
        const oldLong = this.locateISS?.iss_position.longitude
        this.issService.getLocate().subscribe(locate => this.locateISS = locate)
        let distance = 60 * 1.1515 * (180/Math.PI) * Math.acos(
          Math.sin(Number(oldLat) * (Math.PI/180)) * Math.sin(Number(this.locateISS?.iss_position.latitude) * (Math.PI/180)) + 
          Math.cos(Number(oldLat) * (Math.PI/180)) * Math.cos(Number(this.locateISS?.iss_position.latitude) * (Math.PI/180)) * 
          Math.cos(Number(oldLong) - Number(this.locateISS?.iss_position.longitude) * (Math.PI/180))
        );
        this.speed = Math.round(distance * 1.609344)
        this.issIcon.setLngLat([Number(this.locateISS?.iss_position.long`), Number(this.locateISS?.iss_position.latitude)])    
      }
    }

I thought it might be something when building the project, I built it again and it didn’t work