wordpress wp_ajax returning 400 bad request

Error returned in browser console: 400 bad request

I traced the error to this part in the admin-ajax.php file by changing the response value from 0 to 1:

if ( is_user_logged_in() ) {
// If no action is registered, return a Bad Request response.
if ( ! has_action( "wp_ajax_{$action}" ) ) {
    wp_die( '0', 400 );
}

I tried everything, but unfortunately I didn’t understand what this login really means and how it works.

I saw some people having a problem with the host, in my case I’m using hostinger. (I don’t think this is relevant but here it is.)

Javascript

function formValidation() {
  event.preventDefault();
  var name = document.forms["contactForm"]["name"].value;
  var email = document.forms["contactForm"]["email"].value;
  var subject = document.forms["contactForm"]["subject"].value;
  var message = document.forms["contactForm"]["message"].value;
  document.getElementById('status').innerHTML = '';
  var errorMessage="<span class='error'>All fields are required.</span>";
  var regEx = /^([A-Za-z0-9_-.])+@([A-Za-z0-9_-.])+.([A-Za-z]{2,4})$/;

     if (name.trim() == "" ||email.trim() == "" || subject.trim() == "" || message.trim() == "") {
         document.getElementById('status').innerHTML = errorMessage;
         return false;
       }
   if (!regEx.test(email)) {
       var errorMessage="<span class='error'>Invalid email.</span>";
        document.getElementById('status').innerHTML = errorMessage;
        return false;
      }
  processContactSubmit();
  return true;
}

function processContactSubmit() {
            var request = new XMLHttpRequest();
            request.open("POST", "/wp-admin/admin-ajax.php?action=process_contact_form");
            request.onreadystatechange = function() {
                if(this.readyState === 4 && this.status === 200) {
                    document.getElementById("status").innerHTML = this.responseText;
                }
            };
            var myForm = document.getElementById("contactForm");
            var formData = new FormData(contactForm);
            request.send(formData);}

functions.php

add_action('wp_ajax_nopriv_process_contact_form', 'process_contact_form');
add_action('wp_ajax_process_contact_form', 'process_contact_form'); //Retirar essa parte para error no console, no contrario ira aparecer no navegador o numero 0.

function process_contact_form() {
    $to = "Recipient Email Address";
    $subject = $_POST["subject"];
    $headers = "Testing";
    $message = $_POST["message"];
    $attachments = "";
    $sent = wp_mail($to, $subject, $message, $headers, $attachments);
    if (! $sent) {
        echo "<span class='error'>Problem in sending mail.</span>";
    } else {
        echo "<span class='success'>Hi, thank you for the message.</span>";
    }
    wp_die();}

Html Form

<form name="contactForm" id="contactForm" method="post" onsubmit="return formValidation()"  action="">

Is it possible to create Try Catch block which will run every single function?

So, my question is generally about some debugging and troubleshooting for people who don’t really understand programming at all.
Is it possible to create a method like:

public foo(method){
try(){
method();
}
catch(error){
console.log(method().name + 'caused an error'); 
throw Error;
}

is it generally okay to do something like that, yes, I know that errors are shown very good even without something similar but if, for example I’m doing testing for a client who wants to know about everything and see what’s exactly goes wrong. I’d like to let him know about problems as much as I can, I already have allure reporter on my project but it is not enough

VSCode Node.js intellisense and linting issues

I have a couple of annoying issues with VSCode for some time. I’m on version 1.68.1 and working in Node.js on MacOS. For the purposes of this test, I created a setup as follows:

projectDir
 - package.json
 - logger.js
 - index.js

The package.json is inconsequential here but the other two files are as follows.

logger.js

const logger = (msg) => {
    console.log(msg);
}

module.exports = { logger };

index.js

const { logger } = require("./logger");

someFunc();
logger("Hello!");

Here are the two things I’m struggling with:

  1. Unimported functions are not flagged. For example, there’s a call to someFunc() in index.js but VSCode has no problems with it. It’s the same with undeclared variables. If I add a = zz; in the file, there are no warnings.
  2. If I close the logger.js file, I can’t autocomplete the import. What I mean is, if the logger.js file is open, then I can just type “logger” and select the import from the suggestions list, but it doesn’t happen if the file is closed. I’m not sure if this is how it’s supposed to be, but it’s very annoying once there are more than 10-15 files in the project as I need to manually open them before VSCode becomes “aware” of their exports.

Sorry if this is all silly, but these two things have been impacting my workflow. Please feel free to ask for more info!

I’m doing the freecodecamp challenges and I got confuse

function sumPrimes(num) { 
    function isPrime(num) {
        for (let i = 2; i < num; i++) {
            if (num % i == 0) return false;
        } 
        return true;
    }

    let sum = 0; 
    for (let i = 2; i <= num; i++) {
        if (isPrime(i) == true) console.log(i);
    }
}

sumPrimes(11);

the console.log returns 2 3 5 7 11. my question is : how can this function know that 11 is in fact a prime number, since the for loop inside the isPrime function can only runs until it reaches 10 since i<num.

extra info being added to image from input file in formData fetch request

Uploading image to S3 from typescript react client side but for some reason appending that file to formData adds extra info to the file (which corrupts it and can’t be opened after downloading from S3). After removing that extra info from a text editor, the image opens fine. Anyone know why this is happening? I’m using fetch API with FormData

const onFileChange = (e: ChangeEvent<HTMLInputElement>) => {

    const formData = new FormData();
    if (e.target.files) {
      formData.append("file", e.target.files[0]);

      fetch(url, {
        method: "PUT",
        body: formData,
        headers: {
          "Content-Type": e.target.files[0].type,
        },
      })
        .then((response) => {
          console.log(response);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  };

<input
    type="file"
    accept="image/*"
    name="photo"
     onChange={(e) => onFileChange(e)}
  />

enter image description here

react: index.js or app.js don’t seem to be importing

after some time, i’m creating a react app, and i’ve just set up a skeleton, but it doesn’t show up.

i’ve done the steps, npx create, npm install and start.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
import React from "react";
import Main from "./components/Main"

const App =()=> {
  return (
    <Main/>
  );
}

export default App;
import React from "react";
import "./Main.scss";

const Main =()=> {
    <div id="main">
        <div className="gameboard">
        </div>
        <div className="console">
        </div>
    </div>
}

export default Main;

using inspector, there are no divs from Main component in the browser. just the root.

React with Recoil, large array is lagging

I have an array of objects, around 400 items.

The component tree looks something like this

App
  -> Page (useRecoilState(ListAtom) for consumption)
    -> List 
      -> Item (useRecoilState(ListAtom) for mutation)
        -> Information
        -> Button

In the <Item> component, I display some <Information> which the user will look at and click the button to trigger something.

When the button is clicked, it makes a call to my backend, and upon success, the button will change its text.

This is all working as expected, but when the button re-renders, it causes a re-render for the entire tree.

I’m following this: https://recoiljs.org/docs/basic-tutorial/atoms/

To update an attribute of an item in the list, you need to replace that item with a new copy and return a completely new state, this will cause everything to re-render again, which takes a few seconds.

I was thinking that because these objects are referenced by memory, it would know not to re-render the non-mutated items, but looks like this isn’t the case.

I might not be structuring my app or using Recoil correctly, but this seems to be what Recoil’s tutorial is teaching devs to do, anyone got any ideas?

How to export class’s of css and put into array with php?

hello guyes I have CSS code and I’m trying to find a way to get only the CSS Class’s name Only and clear coma and open&close tag and value and put it into an array in PHP

Example:

.dungarees {
  content: "ef04";
}
.jacket {
  content: "ef05";
}
.jumpsuit {
  content: "ef06";
}
.shirt {
  content: "ef07";
}

and I want to do a a function with PHP to convert it into an array like this

$my_array('dungarees','jacket','jumpsuit','shirt');

is there any function with php or even jquery to deal with this? thanks

Editing Product Options Using the Shopify API

I am trying to edit a product’s option values in Shopify. Essentially, I want to pass a reordered array for products[0].options[0].values

enter image description here

Using Shopify’s REST API docs, I make a request like so:

import {Product} from '@shopify/shopify-api/dist/rest-resources/2021-10/index.js';

const test_session = await Shopify.Utils.loadCurrentSession(request, response);

const product = new Product({session: test_session});

product.id = 7758005469437;

product.options[0].values = newOptionsOrder;

await product.save({});

I get the following error:

Cannot read properties of undefined (reading '0')

I was successfuly able to edit the title of the target product using product.title = "New Title"; The issue just seems to be targeting more nested elements.

Any idea how to edit the first options.values array?

Importing module alias results in Error [ERR_MODULE_NOT_FOUND]: Cannot find module

I am trying to import a module (exported default) and give it an alias. This has worked perfectly in other projects, I can’t seem to figure out why it’s not working here.

I’ve tried with and without extension (.js). I’ve tried exporting the function below after defining it, and exporting it on the same line.

Here is where I’m attempting and failing to import:

import getAllPeople from './endpoints/getAllPeople.js';

The file path reference is correct, the endpoints folder is on the same level as the importing file.

Here is the file, getAllPeople.js:

export default function testFunction() {
    return { success: true };
}

The whole error is:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/jasonross/Documents/Programming/wts_api/generate/generateEndpoint' imported from /Users/jasonross/Documents/Programming/wts_api/endpoints/getAllPeople.js
    at new NodeError (node:internal/errors:371:5)
    at finalizeResolution (node:internal/modules/esm/resolve:418:11)
    at moduleResolve (node:internal/modules/esm/resolve:983:10)
    at defaultResolve (node:internal/modules/esm/resolve:1080:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:79:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Thank you for any help!

How to hold alert box on the page in case of reloading or changing route?

I need to maintain an alert box on the Registration page indicating the user has registered successfully. However, by redirecting to the Login form this box disappears, because the page refreshes.
I utilize the Alert component to manage this scenario. All of the features work flawlessly but this problem really makes me confused. I shared my code and hope you assist me in getting to the root of this predicament.

alert.component.ts

import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Subscription } from 'rxjs';
import { Alert, AlertType } from 'src/app/_models/alert';
import { AlertService } from 'src/app/_services/alert.service';

@Component({ selector: 'alert', 
templateUrl: 'alert.component.html',
styleUrls: ['./alert.component.scss'] })
export class AlertComponent implements OnInit, OnDestroy {
    @Input() id = 'default-alert';
    @Input() fade = true;

    alerts: Alert[] = [];
    alertSubscription: Subscription;
    routeSubscription: Subscription;

    constructor(private router: Router, private alertService: AlertService) { }

    ngOnInit() {
        // subscribe to new alert notifications
        this.alertSubscription = this.alertService.onAlert(this.id)
            .subscribe(alert => {
                // clear alerts when an empty alert is received
                if (!alert.message) {
                    // filter out alerts without 'keepAfterRouteChange' flag
                    this.alerts = this.alerts.filter(x => x.keepAfterRouteChange);

                    // remove 'keepAfterRouteChange' flag on the rest
                    this.alerts.forEach(x => delete x.keepAfterRouteChange);
                    return;
                }

                // add alert to array
                this.alerts.push(alert);

                setTimeout(() => this.removeAlert(alert), 5000);
           });

        // clear alerts on location change
        this.routeSubscription = this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                this.alertService.clear(this.id);
            }
        });
    }

    ngOnDestroy() {
        // unsubscribe to avoid memory leaks
        this.alertSubscription.unsubscribe();
        this.routeSubscription.unsubscribe();
    }

    removeAlert(alert: Alert) {
        // check if already removed to prevent error on auto close
        if (!this.alerts.includes(alert)) return;

        if (this.fade) {
            // fade out alert
            this.alerts.find(x => x === alert).fade = true;

            // remove alert after faded out
            setTimeout(() => {
                this.alerts = this.alerts.filter(x => x !== alert);
            }, 250);
        } else {
            // remove alert
            this.alerts = this.alerts.filter(x => x !== alert);
        }
    }

    cssClass(alert: Alert) {
        if (!alert) return;

        const classes = ['toast'];
                
        const alertTypeClass = {
            [AlertType.Success]: 'toast-success',
            [AlertType.Error]: 'toast-error',
            [AlertType.Info]: 'toast-info',
            [AlertType.Warning]: 'toast-warning'
        }

        classes.push(alertTypeClass[alert.type]);

        if (alert.fade) {
            classes.push('fade');
        }

        return classes.join(' ');
    }
}

alert.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { Alert, AlertType } from '../_models/alert';


@Injectable({ providedIn: 'root' })
export class AlertService {
    private subject = new Subject<Alert>();
    private defaultId = 'default-alert';

    // enable subscribing to alerts observable
    onAlert(id = this.defaultId): Observable<Alert> {
        return this.subject.asObservable().pipe(filter(x => x && x.id === id));
    }

    // convenience methods
    success(message: string, options?: any) {
        this.alert(new Alert({ ...options, type: AlertType.Success, message }));
    }

    error(message: string, options?: any) {
        this.alert(new Alert({ ...options, type: AlertType.Error, message }));
    }

    info(message: string, options?: any) {
        this.alert(new Alert({ ...options, type: AlertType.Info, message }));
    }

    warn(message: string, options?: any) {
        this.alert(new Alert({ ...options, type: AlertType.Warning, message }));
    }

    // main alert method    
    alert(alert: Alert) {
        alert.id = alert.id || this.defaultId;
        this.subject.next(alert);
    }

    // clear alerts
    clear(id = this.defaultId) {
        this.subject.next(new Alert({ id }));
    }
}

This is a piece of code in which an alert message is called:

onSubmit() {
    this.submitted = true;

    // reset alerts on submit
    this.alertService.clear();

    // stop here if form is invalid
    if (this.form.invalid) {
      return;
    }

    this.loading = true;
    this.accountService
      .register(this.form.value)
      .pipe(first())
      .subscribe((data) => {
        this.loading = false;
        this.submitted = false;
        if (data.hasError) {
          this.alertService.error(data.errorMessage);
        } else {
          this.alertService.success('Registration successfully completed.', {
            keepAfterRouteChange: true,
          });
          localStorage.setItem('regCount',JSON.parse(localStorage.getItem('regCount')) + 1);
          this.router.navigate(['/login']).then(() => {
            window.location.reload();
          });
        }
      },
      () => {
        this.loading = false;
        this.submitted = false;
        this.alertService.error('Something went wrong.');
      });
  }

Javascript function won’t stop running/looping if statement

I’m obviously new to Javascript, so this might be an easy fix but I haven’t found anything in google that fixes this.

Once I click this html element, an input button, this function runs but does not stop running, it loops again and again without being clicked again. How do I make it run once per click?

var TalentPoints = 5;


document.querySelector("#addtalentbutton").addEventListener("click", () => {
            if (TalentPoints > 0) {
                TalentPoints = TalentPoints - 1;
                if (document.getElementById("talent1").hasAttribute("hidden")) {document.getElementById("talent1").removeAttribute("hidden"); return;} 
                else if (document.getElementById("talent2").hasAttribute("hidden")) {document.getElementById("talent2").removeAttribute("hidden");}
            } return;
        })