WordPress Ajax function returns 400 Bad Request Error for admin-ajax.php

I’m using a WordPress code pattern that’s worked for me many times before on client sites, but now that I’m using it my own site, it just won’t work. I’ve been looking at this problem, on and off, for weeks, and I’ve now separated it from my dev site and reconstructed it as a very simplified set of test pages and code in the WordPress twentytwentythree theme. There’s no plugins to mess things up.

Here’s the parent page:

<?php
/*
Template Name: Ajx Test
*/

$tid = 1234;

get_header(); ?>

<div class="content">

        <header>
            <h1 class="page-title">Ajax Test</h1>
        </header>
        
        <div class="ajax-test-target"></div>
</div> <!-- end .content -->

<script>load_test_content(id=<?php echo $tid; ?>);</script>

<?php get_footer(); ?>

The content function (functions/ajax-test-content.php):

<?php
/* Loop Archive Portfolio Ajax */

add_action( 'lr_ajax_test_content', 'test_content' );
add_action( 'lr_ajax_nopriv_test_content', 'test_content' );

function test_content() {

  //extract vars incomming from js load_test_content fn
    if (!empty($_POST)) {
        $windoww = $_POST["win_w"];
        echo '$windoww: '.$windoww.'<br>';
        $tid = $_POST["t_id"];
        echo '$tid: '.$tid.'<br>';
    } ?>

<div><p>Hello World</p></div>

<?php
wp_die();
}

Enqueue the script (functions/enqueue-scripts.php):

<?php
function site_scripts() {
  global $wp_styles;

    // Adding scripts file in the header
    wp_enqueue_script( 'lrcustom-js', get_template_directory_uri() . '/assets/scripts/lr-custom.js', array( 'jquery'), $ver = false, $in_footer = false );
    wp_localize_script( 'lrcustom-js', 'lr_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'site_scripts', 999);

Require the above content and scripts functions (functions.php)

// Register scripts and stylesheets
require_once(get_template_directory().'/functions/enqueue-scripts.php');

// Adds ajax-test-content Ajax Return
require_once(get_template_directory().'/functions/ajax-test-content.php');

The JS:

<script>
var window_w=jQuery(window).width();

// Ajax Test
function load_test_content(id) {
  console.log('test_content fires. id='+id);
  console.log('Ajax URL:', lr_ajax_object.ajax_url);
  console.log('Window Width:', window_w);
  console.log('Term ID:', id);
  jQuery.ajax({
    url: lr_ajax_object.ajax_url,
    data: {
        'action' : 'test_content',
        'win_w' : window_w,
        't_id' : id
    },
    type: 'POST',
    success: function(data) {
      jQuery(".ajax-test-target").html(data);
      console.log("test_content Ajax success");
    },
  });
}
</script>

Console.log returns: 
[Log] test_content fires. id=1234 (lr-custom.js, line 41)
[Log] Ajax URL: – "https://lenrooney.com/wp/wp-admin/admin-ajax.php" (lr-custom.js, line 42)
[Log] Window Width: – 1789 (lr-custom.js, line 43)
[Log] Term ID: – 1234 (lr-custom.js, line 44)

[Error] Failed to load resource: the server responded with a status of 400 (Bad Request) (admin-ajax.php, line 0)

I hope someone out there can help me figure out what’s gone wrong. Thanks!

Is there a way to orderby using a value from a different array

Hey so i have one array with data like this

arr1 = [
{mood: "good", name: "Jake"},
{mood: "good", name: "Jill"},
{mood: "good", name: "Jack"}
]

and another array

arr2 = [
{number: 2, name: "Jake"},
{number: 1, name: "Jill"},
{number: 3, name: "Jack"}
]

I was looking to sort array one using the number from array 2. So, basically I would need to use a filter to match the name from arr1 to arr2 and then get the number from the resulting array and sort.

How can I get this done ?

arr1.sort((a: any, b: any) => arr1.filter((item: { name: string; }) => item.name == arr2[i].name));

I am totally lost, so much so, I may not have asked a proper question !

Issues with uploading file to google drive via google apps script

I’m in the process of writing a program in google apps script that will allow users to upload files onto google drive. However, when I run the program, google.script.run does not run the function to upload a file (secFunc(formObject)). Because the program is run asynchronous, I’m having difficulties debugging or troubleshooting my issue. I believe the issue is a typo or bad method within secFunc, but given that I was able to run this function with no issue a week ago, I’m struggling to understand what the issue is.
JS-

function uploadFiles(){
  const htmlDlg = HtmlService.createHtmlOutputFromFile('Index').setWidth(350).setHeight(425);
  SpreadsheetApp.getUi().showModelessDialog(htmlDlg, 'Email Attachments')
}

function secFunc(formObject){
  const blob = getBlob(formObject.myFile)
  DriveApp.createFile(blob)
}

Index.html-

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>

    <form id="myForm" onsubmit="submitFunc(this)">
           <div class="form-group">
            <label for="myFile">Upload File</label> 
            <input name="myFile" class="myFile" type="file" id="myFile" />
           </div>
          <br>
          <button type="submit">Submit</button>
        </form>
        <br>
        <div id="output"></div>
  </body>
  <script>
    function submitFunc(formObject){
      google.script.run.withSuccessHandler(onSuccess).secFunc(formObject)
    }
    function onSuccess() {
      var Output = 'Input Succesfully Translated';
      alert(Output)
      google.script.host.close()
    }
  </script> 
</html>

Expecting that, once uploadFiles() is triggered, an html popup will appear allowing user to input a file. Upon clicking the Submit button, the dialogue would close and the file would be uploaded to Drive. Currently, clicking the submit button gives no response.

graphql nested queries error leak into each other

I writing the error handling of a query that looks like this:

query {
        topQuery(argA: "A", argB: "B") {
            nestedQueryA(argA: "varA") {
                fieldA 
            }
            nestedQueryB(argB: "varB") {
                fieldA 
            }
        }
    }

and if there are no errors then I get expected response without errors.

But when ONE of the nestedQueries result in an error I get the following response where BOTH gets nestedQueries the same error:

    {
        "errors": [
            {
                "message": "nestedQueryA is throwing this error",
                "extensions": {
                //All custom information of the error
                }
            },
            {
                "message": "nestedQueryB is throwing this error",
                "extensions": {
                //All custom information of the error
                }
            }
        ],
        "data": {
            "topQuery": {
                "nestedQueryA": {
                    "fieldA": null
                },
                "nestedQueryB": {
                    "fieldA ": null
                }
            }
        }
    }

Both nestedQueryA and nestedQueryB use the same resolving function for fieldA. Debugging shows that both queries are being resolved i parallell. But as soon as one of queries throws an error both stops executing.

How do I ensure the error of one nestedQueryA doesn’t interfere with the execution of nestedQueryB? I feel there is something about how GraphQL executes the querie that I should take into account to avoid this.

Any ideas?

Javascript – replace multiple characters and spaces in a string

There are multiple solutions on StackOverflow to repace multiple characters in a string and from that I have this code:

var replaceChars = { ' ':'-', 'ń':'n', 'ó':'o', 'ż':'z', 'ą':'a' };
var answerStrUrl = answerStr.replace(/ń|ó|ż|ą/g,function(match) {return replaceChars[match];}).toLowerCase(); 

(answerStrUrl is defined earlier in the code)

This works for all the characters but what should I add in the second line so that spaces are replaced with ‘-‘

How can I create an overlay which closes with the help of a button and not with oneclick?

I’m currently in the process of creating a website with a gallery and I want to crate an Overlay which I can close with a button. I started a month ago and I am still a bit new using Java.script. My problem is that when I click on an image the overlay comes up and then when I click again it immediately closes, but I want to be able to click through the overlay through images.

I created an overlay which comes up when you click on an image but i have no idea how i can close the
overlay with a button. Thanks for the help

function on() {
  document.getElementById("overlay").style.display = "block";
}

function off() {
  document.getElementById("overlay").style.display = "none";
}

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");
  var imgText = document.getElementById("imgtext");
  expandImg.src = imgs.src;
  imgText.innerHTML = imgs.alt;
  expandImg.parentElement.style.display = "block";
}
<div class="Galerie">
   <div class="column">
      <div style="padding:10px">
         <img src="img/A1.jpg" onclick="on()" alt="Snow" style="width: 100%;">
      </div>
   </div>
   <div class="column">
      <div style="padding:10px">
         <img src="img/B3.jpg" onclick="on()" alt="Forest" style="width:100%">
      </div>
   </div>
   <div class="column">
      <div style="padding:10px">
         <img src="img/C1.JPG" onclick="on()" alt="Mountains" style="width:100%">
      </div>
   </div>
</div>
<div id="overlay" onclick="off()">
   <div id="text" img data-src="" >
      <!-- The four columns -->
      <div class="row">
         <div class="Reiheeins">
            <img src="img/A1.jpg" alt="Nature" style="width:100%" onclick="myFunction(this);">
         </div>
         <div class="Reiheeins">
            <img src="img/A2.jpg" alt="Snow" style="width:100%" onclick="myFunction(this);">
         </div>
         <div class="Reiheeins">
            <img src="img/A3.jpg" alt="Mountains" style="width:100%" onclick="myFunction(this);">
         </div>
         <div class="Reiheeins">
            <img src="img/A4.jpg" alt="Lights" style="width:100%" onclick="myFunction(this);">
         </div>
      </div>
      <div class="container">
         <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
         <img id="expandedImg" style="width:100%">
         <div id="imgtext"></div>
      </div>
   </div>
</div>

Array.prototype.reduce implementation [duplicate]

I am learning how Array.reduce works in JS. In the following code I am trying to imitate the behavior of Array.prototype.reduce. How can I define Array.prototype.myReduce so that it doesn’t require the array parameter just as Array.prototype.reduce.

Array.prototype.myReduce = (array, callback, initialVal) => {
    for (let el of array) {
        initialVal = callback(el, initialVal);
    }
    return initialVal;
};

console.log([].myReduce([1, 2, 3], (a, b) => a + b, 10));

Why does the animation watcher not work when I scroll?

I want the scroll watcher to go from left to right but it does nothing right now which is weird.

<div class="scroll-watcher"></div>
.scroll-watcher{
    height: 10px;
    position: fixed;
    top: 0;
    z-index: 1200;
    background-color: blue;
    width: 100%;
    scale: 0.8 l;
    transform-origin: left;
    animation: scroll-watcher linear;
    animation-timeline: scroll();
    
  }
  @keyframes scroll-watcher {
    to { scale: 1 1; };
  }

i was expecting the scroll watcher to move when i scroll, i know that i need to use transform-origin: left; for it to start on the left side.

Bootstrap Over React bootstrap

I am using simple bootstrap in my react projects.
I want to ask experts that it is good technique or not? because sometimes I found react-bootstrap difficult to understand. IN simple words I want to ask that can we use simple bootstrap in react-js instead of react-bootstrap?

I want the answers that is this okay or not?

Mail outdate in mutt

I’m so tired with Gmail and i switch to mutt for faster track mail, i complete set up mutt and successfully run it, but all mail in it is out of date, its mail from several year ago, i don’t really understand what happend, this is my .muttrc

set imap_user = "[email protected]"
set imap_pass = "my_app_password"
set smtp_url = "smtp://[email protected]@smtp.gmail.com:587/"
set smtp_pass = "my_app_password"
set from = "[email protected]"
set realname = "My Name"
set folder = "imaps://imap.gmail.com:993"
set spoolfile = "+INBOX"
set ssl_force_tls = yes
# Optionally configure where sent mail is stored
set record="+[Gmail]/Sent Mail"
set postponed="+[Gmail]/Drafts"
set trash="+[Gmail]/Trash"

i configure password is app password i already setting in 2 Step Verification on Google account, i’m sure IMAP is enable in my Gmail, shift 2 ($) to force mutt refresh is not use, nothing change.

How to Parse data into multiple columns by having length it self [closed]

I am getting data like 0003USA0102EN0605CANCL in this case 00 is ID and 03 is length and USA is the record.

ID LENGTH Column1 COLUMN2 COLUMN3
00   03     USA
01   02     null     EN    null
06   05     null    null   CANCEL

this is the example output i am expecting. But here the issue is we are not getting the same length of each and every record.
0003USA0102EN0605CANCL, 110403000801Y091N1006CANCEL.
Here we should load the data based on length which is in the record it self.

I tried substring in SQL but the problem is we are not getting the same columns in each and every record.

for example i am getting 4 columns from a record and sometimes i am getting 10 or 5 columns.

Lamejs exports mp3 compressed audio file with no sound

I have to export an AudioBuffer object to mp3 compressed file, in javascript, but the output has no sound.

lamejs is not outputting any audible sound:
this is a duplicate, but no answer and I can’t add a comment for ask if it’s solved (need 50 reputation).

I use the same library, but I found a new maintained version, that fixes some bugs:
https://github.com/shijinyu/lamejs

I can export the AudioBuffer in wav file. It works very well.

https://github.com/zhuker/lamejs/issues/68:
here he says that encoder accepts PCM audio only.
So I call getChannelData function (Web Audio API) from the AudioBuffer source.

// 2 channels
async encodeAudioBufferLame(audioBuffer) {

    var mp3encoder = new Mp3Encoder(2, 44100, 128);

    var mp3Data = [];

    const [left, right] =  [audioBuffer.getChannelData(0), audioBuffer.getChannelData(1)];

    const sampleBlockSize = 1152; //can be anything but make it a multiple of 576 to make encoders life easier

    for (var i = 0; i < left.length; i += sampleBlockSize) {
        const leftChunk = left.subarray(i, i + sampleBlockSize);
        const rightChunk = right.subarray(i, i + sampleBlockSize);

        var mp3buf = mp3encoder.encodeBuffer(leftChunk, rightChunk);

        if (mp3buf.length > 0) {
            mp3Data.push(mp3buf);
        }
    }
    var mp3buf = mp3encoder.flush();   //finish writing mp3

    if (mp3buf.length > 0) {
            mp3Data.push(mp3buf);
    }

    return mp3Data;

}

And then:

const mp3Data = await encodeAudioBufferLame(audioBuffer);
const blob = new Blob(mp3Data, {type: 'audio/mp3'});
const url = window.URL.createObjectURL(blob);


const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.setAttribute('download', `myAudio.mp3`);
downloadLink.click();

The output result has same original duration/length, but no sound.
My sound card is good and the audio desktop is on.

I tried other libraries too, but I encountered other bugs.

All help is really appreciated!!

how to make day.js format a date in non-system timezone?

I need to format a date represented in seconds as an ISO formatted string in my time zone ‘Europe/Berlin’. So I can’t use .toISOString().

everything is working fine on my machine, but our build pipeline is running on a server in a different time zone. And this causes an error in our tests. Which also means that I can’t debug it.

here is the method I want to test:

public secondsToString(seconds: number) {
    dayjs.tz.setDefault('Europe/Berlin');
    return dayjs(seconds * 1000, 'Europe/Berlin').format();
}

I know this is a bad place to set the default time zone, but I tried narrowing down the error.
And here is the test:

describe('secondsToString', () => {
    it('works', () => {
        const seconds = 1704067200;
        const expected = '2024-01-01T01:00:00+01:00';
        const actual = component.secondsToString(seconds);
        expect(actual).toEqual(expected);
    });
});

as I said, it works on my local machine. But in our test pipeline, I get the error:

Chrome Headless 120.0.6099.224 (Linux x86_64) ComparisonGraphComponent secondsToString works FAILED
Expected '2024-01-01T00:00:00+00:00' to equal '2024-01-01T01:00:00+01:00'.
    at <Jasmine>
    at UserContext.apply (src/app/intra-day-quotes/comparison-graph/comparison-graph.component.spec.ts:210:28)
    at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:368:26)
    at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:273:39)
    at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:367:52)

Why does day.js convert the date to UTC before formatting? And how can I prevent that?

How to start stopwatch again after restarting its time?

So I’m just starting to learn JavaScript, like its syntax and logic, therefore I’m still not implementing anything on a web page, just playing with the console before doing any web development with JS.

There’s this function I’d like to implement, a restart function where you can start the stopwatch again after having restarted it, which I quite haven’t figured out how to do so

Here’s the run() function with the logic of all necessary inputs to control the stopwatch (such as a start key, a pause/resume key, a stop and finally a restart key:

function run() {
    const rl = readline.createInterface({
        input: process.stdin
    });

    rl.on('line', (input) => {
        if (input.toLowerCase() === 'i') {
            if (!running) {
                if (restarted && paused) { 
                    seconds = 0;
                    minutes = 0;
                    hours = 0;
                    hundredths = 0;
                    laps = [];
                    restarted = false;
                    // restartTime = Date.now(); not sure if this even works as I expect it to.
                }
                startStopwatch();
            }
        } else if (input.toLowerCase() === 'p' && running) {
            paused = !paused;
            console.log('Stopwatch is paused.');
        } else if (input.toLowerCase() === 'd' && running) {
            running = false;
            rl.close();
            console.log('Stopwatch has been stopped.');
        } else if (input.toLowerCase() === 'l' && running && !paused) {
            recordLaps();
        } else if (input.toLowerCase() === 'v' && paused) {
            showLaps();
        } else if (input.toLowerCase() === 'r' && paused) {
            restarted = true;
            console.log('Stopwatch has been restarted.');
        } else if (input.toLowerCase() === 'i' && restarted && paused) {
            startStopwatch();
        }
    });
}