Using Javascript insert instead of WPDB insert (PHP)

Does anyone know how to insert an associative array generated by JS into a specific WordPress database table?

Here is a pen from @rpg_digital who’s been helping out a ton with the JS! The pen is currently using local storage, so basically, instead of using local storage, the elements array needs to be stored in the database in JSON format.

WordPress has a built-in function called WPDB insert which accomplishes this, but I’m not sure how to use WPDB insert when the array is being created by JS and the WPDB function is PHP.

In general, the way this works is that you make a PHP script which runs on your server (aka an endpoint) and you can call this script from the browser by making an Ajax request. That is to say, you would take whatever values the user has provided and then send them to the server when the user (for example) submits a form or clicks a button.

The PHP script running on the server would receive the data, perform some validation checks (you should never trust anything supplied by the client) and then either perform an action and return a response, or just return a response.

In your scenario, if the values are ok, this would be a database insert and a status code representing a successful operation (normally 200). If the values are not ok (maybe something is missing) then no insert is performed and a status code representing an error is returned (normally 400). You could also optionally return one or more error messages.

Back in the client, you would catch this response and depending on what it is, display a success or error message to the user.

In your case, things get a tad more complicated, as you are working with WordPress. I haven’t done any WordPress for a while, so am not sure of the correct way to do this. Assuming that only logged in users may insert data, you might want to look at the wp_ajax hook.

Either way, you will want to look into Ajax requests. There are plenty of libraries to help you with this (Axios is a good one), but the native FetchAPI is probably equal to the task (assuming you don’t need to support IE11).

Hope that gives you something to go on.

1 Like

I’m aware of both fetch and Ajax. The problem is that I’m wanting to save the data to a specific table with javascript. (Not jquery and the data needs to be saved before I can access it with php).

Wp Ajax is a PHP function. So I’m not sure how I’m supposed to use the PHP function when the data is in javascript. Unless I’m not aware of how javascript and PHP can communicate.

Fetch seems like it might do the trick except I can’t find any articles explaining how to use fetch to insert data into a specific table.

James has described the correct way. Use Javascript AJAX (or even fetch which is nothing else then a AJAX replacement for newer browsers) to call a PHP script which is saving the data to the database.

You cannot save data from javascript (which is on the client side) directly to the database because normally this should not be allowed by CORS. And even if you would be able, you need to have the credentials of the database in the browser. What means, everyone can read them in the browsers development tool. I do not need to tell you what this means or?

1 Like

Fetch won’t do that. Fetch is there to send data to a file only, not directly to a database.

Just thought it worth adding that the codepen code was taken a step further from localStorage, in that I set it up to send a JSON string to a php file, which is hopefully where you guys come in :slight_smile:

// amended to send rather than set - makes more sense
const sendData = async (url, data) => {

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)

        if (response.ok) return await response.json()

        throw Error(`${response.url}: ${response.status} ${response.statusText}`)

    } catch (err) { console.log(err) }

    return {}

and just a simple file I tested with

$element = json_decode(file_get_contents('php://input'), true);
$element['textContent'] = 'From Server: ' . $element['textContent'];

header('Content-Type: application/json');
echo json_encode($element);

Post is here

1 Like

If the data is saved as a javascript variable how can you use PHP to save the data?

I’ve watched a ton of videos and read blogs. I wouldn’t have asked for hands in help but it’s a last resort.

Can you help provide some additional details because I’m not sure how to implement what you or James are suggesting is the correct way.

An example would help a lot.

To correct a former post it is possible to save data directly to a database with cloud solutions that implement zero trust signed urls. However, Wordpress does not support this. Therefore, you must have server in the middle to communicate with the database. I would provide links about to how direct communication with a cloud database can be achieved securely but last time I did so was reprimanded. I also have demos online that clearly demonstrate this model. So it is entirely possible to achieve without a server. At a high level it could be achieved with Wordpress by moving the database to aws cloud and using app sync graph query. You would also need to federate Wordpress users through aws cognito to assign the roles with permissions to access app sync and specific operations like inserts updates on a specific table. Once that is all achieved the JavaScript in the browser can use the aws s3 v3 api to sign outgoing request before using fetch api directly to aws service endpoints like the ones provided by app sync for graph queries. Probably out of most people league asking these types of questions but not impossible. The key piece is zero trust communication with an api which I don’t think any vendor besides aws supports but I could be wrong on that and would be happy to be corrected. The major advantage of setting something up like I described is moving all the load off the slow Wordpress app server. Also a model that be applied not just to Wordpress but any predominate front-end browser driven application or page. Ultimately eliminating the need for a server in the first place. No more worry about slow pages, long load times, caching, traffic bringing down a site. All that becomes a thing of the past with a serverless model. However, traditional php applications are not suitable for this model since they live on server. Therefore, it takes a complete change in mind set to build these types of serverless applications. I’m in the process of creating a complete ecosystem to rapidly build applications like I just described. I won’t post a link but like I said it is all to real to achieve these things with modern tools and change in mind set. I also have long term planes to clone sites into this model using a combination of ml and ai but that is far off. You could in theory create a JavaScript Wordpress framework that runs in the browser instead of server. That would consume the graph api. Now you could be talking taking all existing Wordpress websites and easily migrating them to a serverless model. That would be pretty cool. I don’t see the php oligarchs doing that though considering their unwavering loyalty to php.

Someone has partially done this with react.

Wordpress is just a headless cms just being used for the rest api. You could take this a step further and completely remove Wordpress using the model above I just described. That project even supports pre rendering Wordpress pages. That means you host a Wordpress site as static assets without a server like from a cdn or as a GitHub pages site for free. Doing that will significantly impact the performance and decrease load on the server even with using Wordpress api.

The wp Ajax hook looks like it might work. Fortunately, there are a few videos regarding this hook.

Still not entirely sure how I could save a json created with javascript and use wp ajax. All of the videos and articles use jquery when using wp ajax. perhaps there’s a way to use native javascript instead of jquery just haven’t found it yet.

Thanks for sharing.

You live and learn :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.