PHP not getting POST data sent from javascript fetch

I know this question has been asked before, but I haven’t seen an answer that’s worked for me yet.

var response = await fetch('login.php', {
        mode: 'cors',
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });
    
await response.json().then(data => {
    console.log(data);
});
    

Verified ‘data’ wasn’t empty. The login.php script returns a valid json response, which I’ve used successfully when sending data to it using jquery’s ajax. But with plain JS, I get an empty $_POST array.

For reference, this works just fine:

$.ajax({
    dataType: 'json',
    url: 'login.php',
    type: 'post',
    data: data,
}).done(function(data){
    console.log(data)
});

And that’s really all I’m trying to do, change from jquery to vanilla JS. I don’t see what I’m missing here.

What is best way to Sync SQLite Database over Local WIFI connection in React Native App installed in multiple Android devices?

I have a React Native app installed in multiple Android devices.
Those devices are connected to same WIFI (no internet connection).
The app uses SQLite database to store the data.

I want to sync SQLite database so that all devices will have same data.

There is no server (signaling server) available but I know all device IPs.

I am open to use other database if they provide Conflict Free Sync or something that might help.

I’m looking for OPENSOURCE library!

From search and prompts, I came across SyncedStore, RxDB and CR-SQL, etc… but either I don’t know how to to make them work in React Native app or they just don’t work for my requirements. If you think they can be used for my purpose please explain, thank you.

–>

I can use ReactNative TCP Socket to create a local connections between devices where one device works as “server / main”. The data is shared using TCP messages but the database sync requires some more work than just sharing the changes via TCP messages.

The app needs to work separately on its own database if there is not local wifi connection, then when the connection comes back, sync the changes with other devices.
Requires to do LRW conflict resolution or something better.

<–

How to Auto-Grab Email from Outlook Users When Accessing Obfuscated URLs in Flask Application?

I am developing a Flask application that generates obfuscated URLs for legitimate users. The application is designed to:

Redirect users to a protected URL when they click on the obfuscated link.
Automatically grab the user’s email if they are using Outlook (desktop/web) and append it to the URL as a query parameter (?email=[autograbbed_email]).

Logged the complete HTTP headers and found no direct email information.
The current logic checks for “outlook” or “microsoft” in the User-Agent string:
if (userAgent.indexOf(“outlook”) !== -1 || userAgent.indexOf(“microsoft”) !== -1)

Confused on adding

I have a web site which I only have access to a pages and tags where I can insert code, css etc.

I have a script let’s call myScript which I want to add to the page after a specific div element.

So what I need is to be displayed/executed after a certain div is drawn. Also is it better to inject this code in the tag or the tag?

Getting Error code 404 from Phone Pe PG Integration via Web Flow in Express |Node JS

I am integrating Phone Pe Payment Gateway on my Web Application.

Getting response as 404 from Phone Pe API

{"success":false,"code":"404"}

On the Backend I have done the following after reading the docs at https://developer.phonepe.com/v1/reference/pay-api/

Step 1 : Payment Payload for Web Flow

const MERCHANT_BASE_URL = "https://api.phonepe.com/apis/hermes/pg/v1/pay"

app.post('/create-order',async (req,res) => {
    const { name, mobileNumber, amount } = req.body;
    const orderId = uuidv4().replace(/-/g, "").substring(0, 34); 
    const userId = uuidv4().replace(/-/g, "").substring(0, 34); 
    
    const paymentPayload = {
        merchantId: MERCHANT_ID,
        merchantTransactionId: orderId,
        merchantUserId: userId,
        mobileNumber: mobileNumber || "", 
        amount: 2000, 
        redirectUrl: "https://mywebappurl.com/login", 
        redirectMode: "REDIRECT",
        callbackUrl: "http://localhost:8000/callback", 
        paymentInstrument: {
            type: "PAY_PAGE"
        }
    };

}

Step 2 : Encoding the Payload into BASE 64 format

    const payload = Buffer.from(JSON.stringify(paymentPayload)).toString('base64')

Step 3 : Generating the checksum

Checksum = SHA256(base64 encoded payload + “/pg/v1/pay” + salt_key) + ### + salt_index

    const keyIndex = 1
    const string = payload + '/pg/v1/pay' + MERCHANT_KEY
    const sha256 = crypto.createHash('sha256').update(string).digest('hex')
    const checksum = sha256 + "###" + keyIndex
    console.log(checksum,"checksum")

Step 4 : Making the API CALL to Phone Pe Pay API – https://api.phonepe.com/apis/hermes/pg/v1/pay

const options = {
        method : 'POST',
        url : MERCHANT_BASE_URL,
        headers : {
            accept : 'application/json',
            'Content-Type':'application/json',
            'X-VERIFY':checksum
        },
        data : {
            request : payload
        }
    }

    console.log(options,"Options")

    try {
        const response = await axios.request(options);
        console.log(response.data)

        return res.status(200).json({
            success:true,

        })
    } catch (error) {
        console.log(error.response,'Error in payment')
        return res.status(500).json({
            success:false,
            error:error.message
        })
    }

Please help if I am missing something out over here.

WordPress custom email subscription form based on user settings

I have a wordpress website where visitors may be struggling with their grasp on reality and their mental health. other visitors are interested in spirituality and there may be an overlap of the two.

I do not want to shows ads on the website for users who are struggling with their mental health or having less than positive experiences with spirituality as this could cause complications and we just want to direct them to professional help and we do not want to lose contact with them.

  1. I need to setup a user setting “Are you experiencing any negative effects from your spiritual journey, or do you have any mental health concerns, even minor ones?” the choices would be yes, no, not sure. This will be used to display ads if the user selects no, then the website will keep a record of this via a cookie. It also has further functionality.

  2. I need to setup a email subscription form, primarily focused on keeping connected the individuals so that we may send them an email once a week. reminding them that they may be struggling with mental health etc… Support links to professionals and what not.
    further to this I would like two checkboxes “Support” and “inspiration, exclusive content, and special offers”

Further to my earlier point, I do not want to send any confusing emails to someone who may be struggling with their grasp on reality and/or suffering from mental health complications. therefore I would have the “inspiration, exclusive content, and special offers” option grayed out if they choose Yes or Not sure.

  1. Backend, I should be ok with this as there are many options available to me. I will most likely be writing something custom on my linux/ plesk server

I am fairly certain that I am not going to find anything like this out of the box and I am not interested in paying very much for someting.

I know that you would like to see what I have so far, unfortunately that is nothing.

I am a programmer but this will be the first time that I have written any javascript and or php.

Therefore, I hope that you can put this technicality aside.

If anyone can point me in the right direction I would be grateful.

In the mean time, I am going to try and figure this out.
I will update back if I manage to put anything together.

Bootstrap 5 content function only gets called once

I have the following code that creates and initializes a number of Bootstrap popovers.

I need the text to be updated each time it is shown, so I thought being able to set content to a function would be perfect. However, this function only gets called once per popover. So instead of updating each time it is displayed, it just keeps showing its initial value.

// Initialize example conversion popovers
$('img.example-conversion').each(function() {
    new bootstrap.Popover(this, {
        placement: 'right',
        trigger: 'click focus',
        html: true,
        title: 'Quantity Divisor',
        content: getPopoverContent,
    });
})

var count = 1;
function getPopoverContent() {
    return count++;
}

I need to update the text every time it is displayed. Does anyone know how to make that work?

Flickering on Submenu Click in WordPress Admin Menu

I’m working on customizing the WordPress admin menu to have a smooth, expandable/collapsible behavior on click by adding the CSS and JavaScript.

Goal: Implement a click-to-toggle menu where:

  • Clicking a top-level menu item with a submenu expands its submenu.
  • Clicking the same top-level menu item again collapses its submenu.
  • Clicking a different top-level menu item collapses any other open submenus and expands the newly clicked item’s submenu.
  • Clicking a submenu item simply follows the link (without affecting the menu’s expanded/collapsed state).

The current code almost works, but there’s a noticeable flicker (a brief collapse and re-expansion) when clicking a submenu item, and sometimes when repeatedly clicking the same top-level menu item. This appears to be caused by the JavaScript code re-evaluating the entire menu structure on every click within the menu, even when it’s not necessary to change the menu’s open/closed state.

I’ve tried numerous variations of JavaScript/jQuery code to manage the menu’s state and handle clicks.

Here’s the code which if you use on any wordpress menu you will be able to reporduce the issue.

(function($) {
    $(document).ready(function() {

        $('#adminmenu .wp-submenu').hide(); 
        $('#adminmenu > li.wp-has-submenu > a').off();
        $('#adminmenu > li.wp-has-submenu > a').on('click', function(e) {
            e.preventDefault();
            var $menuItem = $(this).parent();
            var $submenu = $menuItem.find('.wp-submenu').first();

            if ($submenu.is(':visible')) {
                $submenu.slideUp(150, function() {
                    $menuItem.removeClass('opensub');
                });
            } else {
                $('#adminmenu .wp-submenu:visible').slideUp(150, function() {
                    $(this).parent().removeClass('opensub');
                });

                $submenu.slideDown(150, function() {
                    $menuItem.addClass('opensub');
                });
            }
        });

        var $currentMenuItem = $('#adminmenu li.current');
        if ($currentMenuItem.length) {
            var $parentMenu = $currentMenuItem.closest('li.wp-has-submenu');
            $parentMenu.addClass('opensub');
            $parentMenu.find('.wp-submenu').show(); 
        }
    });
})(jQuery);
#adminmenu li.wp-has-submenu .wp-submenu {
    position: static !important;
    display: none;
    box-shadow: none !important;
}

#adminmenu .wp-not-current-submenu .wp-submenu,
.folded #adminmenu .wp-has-current-submenu .wp-submenu {
    border-left-width: 0 !important;
    border: 0 !important;
}
#adminmenu .wp-has-current-submenu ul>li>a, .folded #adminmenu li.menu-top .wp-submenu>li>a {
    padding: 5px 14px !important;
}

Get payment response from payment inside iframe in react

I’m integrating standard Amazon Payment Services inside an iframe and need to capture the payment response, such as success or failure. The goal is to detect when the payment is successful and then redirect the user to the transaction details page.

I’ve embedded the payment page inside an iframe but I’m unsure how to properly receive the response and handle it. Docs amazon payment service

<center>
<iframe style=“border:6px dotted green” name=“myframe” src = “” width=“600” height=“500”></iframe></center>
<form action=“https://sbcheckout.payfort.com/FortAPI/paymentPage” method=“post” id=“” target=“ myframe”>
  <INPUT type=“hidden” NAME=“service_command” value=“TOKENIZATION”>
  <INPUT type=“hidden” NAME=“language” value=“ ”>
  <INPUT type=“hidden” NAME=“merchant_identifier” value=“ ”>
  <INPUT type=“hidden” NAME=“access_code” value=“ ”>
  <INPUT type=“hidden” NAME=“signature” value=“ ”>
  <INPUT type=“hidden” NAME=“return_url” value=“ ”>
  <INPUT type=“hidden” NAME=“merchant_reference” value=“ ”>
  <input value=“Show Payment Form” type=“submit” id=“form1”>
</form>

Create and customize Bootstrap 5 popover from code

I have literally tried a dozen code snippets found online to create and customize a Bootstrap 5 popover.

I want to do it from code because there are a few of them on the page. Also, the text needs to change each time it is displayed.

The closest I’ve found is the following.

const popover = new bootstrap.Popover(this, {
    placement: 'right',
    //trigger: 'focus',
    //html: false
});

popover._config.originalTitle = 'My Title';
popover._config.content = 'My Content';
popover.setContent();

popover.show();

This actually does create a popover, and displays it with the specified content.

However,

  • It doesn’t change the popover title.
  • The popover appears but I can’t seem to close it no matter where I click.

I’m not sure why so many versions have failed for me. Can someone show me how to fix my code, or maybe a better approach?

Create and customize Bootstrap 5 popover

I have literally tried a dozen code snippets found online to create and customize a Bootstrap 5 popover.

I want to do it from code because there are a few of them on the page. Also, the text needs to change each time it is displayed.

The closest I’ve found is the following.

const popover = new bootstrap.Popover(this, {
    placement: 'right',
    //trigger: 'focus',
    //html: false
});

popover._config.originalTitle = 'My Title';
popover._config.content = 'My Content';
popover.setContent();

popover.show();

This actually does create a popover, and displays it with the specified content.

However,

  • It ignores the title.
  • The popover appears but I can’t seem to close it no matter where I click.

I’m not sure why so many versions have failed for me. Can someone show me how to fix my code, or maybe a better approach?

How do i change a picture with a chrome extension [duplicate]

So I’m trying to make a chrome extension where every 100 or so pictures you see is a picture of beans (its a inside joke with my friends) and no matter how hard I try i can’t figure out how to change the picture. if I manually change the src in the website I works but i can’t figure it out with the code

here is my code so far

manifest.json

{
"name": "Beanify",
"description": "Makes every picure the same picture of beans",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "popup/popup.html",
"default_icon": "images/beans.png"
},

    "icons": {
      "16": "images/beans16x16.png",
      "32": "images/beans32x32.png",
      "48": "images/beans48x48.png",
      "128": "images/beans128x128.png"
    },
    "content_scripts": [
      {
        "js": ["scripts/content.js"],
        "matches": ["https://www.youtube.com/*"]
      }
    ]

}

and my javascript file is basically empty because i have re-written it so many times now but heres what i have anyway

content.js

var image = document.getElementsByClassName("img");
image.src = "beans.png";

Yup Formik Validation Schema with Reduce Function Not working

I have the following schema I’m generating using a reduce method to build an object including my desired nested keys/values.

  const validationSchema = object().shape({
    units: object().shape(
      supplyUnits.reduce((acc, unit) => {
        acc[unit.upc] = {
          assignNewInventory: boolean(),
          inventoryValue: number()
            .min(0, "Value must be positive or zero")
            .required(`Inventory value is required for UPC ${unit.upc}`),
        };
        return acc;
      }, {})
    ),
  });

This object stores the fields on each UPC.

The problem is that my errors object from Formik is not being populated correctly. When there’s an error, the errors object just looks like

{
    units: []
}

I’m not sure what I’m doing wrong but it seems to be an issue with the validation schema specifically as the values and touched objects are populating correctly. Please advise

How to integrate MUI Toolpad’s PageContainer with a custom Sidebar?

Material UI has a component called PageContainer which provides a title and breadcrumb navigation as shown here:

https://mui.com/toolpad/core/react-page-container/

I want to navigate to the same place as the MUI Breadcrumbs using a SideBar component. I’m having trouble integrating them. When I click on a breadcrumb, I want to navigate to the selected page, and have the sidebar update, and vice versa.

I think the problem is because each component is using a different way of navigating. The SideBar is using React Router:

function App() {
  return (
    <Router>
      <PageContainerBasic />
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/home/about-us" element={<AboutUs />} />
        <Route path="/home/services" element={<Services />} />
        <Route path="/home/events" element={<Events />} />
      </Routes>
    </Router>
  );

whereas the Breadcrumbs is using a React.Memo() with a navigate prop.

    const NAVIGATION: Navigation = [
      { segment: "home", title: "Home" },
      { segment: "home/about-us", title: "About Us" },
      { segment: "home/services", title: "Services" },
      { segment: "home/events", title: "Events" },
    ];
    
    function PageContainerBasic(props: any) {
      const { window } = props;
      const router = useDemoRouter("/home/events");
      const theme = useTheme();
      const demoWindow = window ? window() : undefined;
    
      function useDemoRouter(path: string): Router {
        const [pathname, setPathname] = React.useState(path);
    
        const router = React.useMemo(() => {
          return {
            pathname,
            navigate: (path: string | URL) => setPathname(String(path)),
          };
        }, [pathname]);
    
        return router;
      }

  function DemoPageContent({ pathname }: { pathname: string }) {
    return (
      <Box>
        <Sidebar />
      </Box>
    );
  }

  return (
    <AppProvider
      navigation={NAVIGATION}
      router={router}
      theme={theme}
      window={demoWindow}
    >
      <Paper sx={{ p: 2, width: "100%" }}>
        <PageContainer
          slots={{
            header: CustomPageHeader,
          }}
        >
          <DemoPageContent pathname={router.pathname} />
        </PageContainer>
      </Paper>
    </AppProvider>
  );
}

But I can’t figure out how to integrate them.

I’ve put together a sandbox demo here:

https://codesandbox.io/p/sandbox/sidebar-testing-t2v5zt

VSCode intellisense based off JSDoc “module:Module_Name.Class_Name”

I have been trying to make VSCode’s intellisense work with the following project: https://github.com/cmu-geometry/ddg-exercises-js
without much success.
It’s all good if I open the root folder and add a standard jsconfig.json file there, but I also need to change all @param, @property and so on from module:Module_Name.Class_Name to just Class_Name for things like “Go to Type Definition” to work, but this change also breaks the documentation. Is there some way to modify the jsconfig file such that Intellisense points to the correct thing when I hover over module:Module_Name.Class_Name? It would be even better if I can do this from the separate project folders instead of the root folder.

Minimal example:

module1.js


// module1.js
/**
 * @module module1
 */

/**
 * A simple class representing MyClass.
 * @class
 */
class MyClass {
    constructor(name) {
      this.name = name;
    }
  
    /**
     * Get the name of the class.
     * @returns {string} The name.
     */
    getName() {
      return this.name;
    }
  }
  
  module.exports = { MyClass };

module2.js

// module2.js
/**
 * @module module2
 */

const { MyClass } = require('./module1');

/**
 * Function that works with MyClass from module1.
 * @param {module:module1.MyClass} myClassInstance An instance of MyClass.
 * @returns {string} A greeting message using MyClass.
 */
function greet(myClassInstance) {
  return `Hello, ${myClassInstance.getName()}!`;
}

const instance = new MyClass('John');
console.log(greet(instance));  // Outputs: "Hello, John!"

Intellisense works just fine in the above if I change @param {module:module1.MyClass} to @param {MyClass}. Is there a workaround to make intellisense work with @param {module:module1.MyClass}?

I tested the above with the WebStorm IDE and the latter can resolve the type and “Go to Type Declaration” works fine. I prefer VSCode though, so I was wondering whether there is a way to work around this.