How to Retrieve JavaScript Array Data Using Ajax in a Wordpress Plugin and Store it in a PHP

function my_custom_js_action($value1, $value2) { 
  ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
        var newData = {
            'email': '<?php echo $value1?>',
            'password': '<?php echo $value2?>'
    };

    jQuery.ajax({
      url: 'dummyurl',
      method: "POST",
      data: newData,
      success: function (response) {
        console.log(response);
      }
    })
  });
    </script>
<?php
}

This particular function is within my custom WordPress Plugin. I pass in some information to the function and then perform an AJAX request in JavaScript. Everything runs smoothly and I receive the response data array.

Now, the question arises - how can I retrieve this data from the array in JavaScript and store it in a PHP variable, so that I may incorporate the data into my WordPress Options?

Answer №1

Give this a try.

Make sure to properly handle the response.

function process_javascript_action($val1, $val2) { 
  ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
    var data = {
        'email': '<?php echo $val1?>',
        'password': '<?php echo $val2?>'
    };

    jQuery.post({
      url: 'dummyurl',
      method: "POST",
      data: data,
      success: function (data) {
    console.log(data);
    var obj = jQuery.parseJSON( data);

    console.log(obj.somedata);
      }
    })
  });
    </script>
<?php
}

Answer №2

To successfully save data into your options table in Wordpress using AJAX, you must have a PHP script that is called by the AJAX request. The process involves adding an action parameter to your POST data and connecting your PHP callback function to this parameter. At this point, you can use the update_option() function to update the options table.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on leveraging ajax for submitting comments in WordPress

I am currently working on developing a custom WordPress theme that includes a unique contact form. This contact form is designed to store data in a custom post type called "Messages" whenever a user submits the form. Below is the code snippet for the cont ...

Unable to successfully retrieve the output from a function within an AJAX request

Hey, I'm having trouble getting the value from this function. It keeps returning undefined and I can't figure out why. Here's the code snippet: function getData() { axios.get('/task') .then(response => { ...

Obtaining a Timestamp with PHP

Attempting to retrieve the timestamp in php using the code below $date = new DateTime(); echo $date->getTimestamp(); An error occurs stating that getTimestamp() is undefined, despite references from this source http://php.net/manual/en/da ...

What is the correct way to implement include or require_once within an If else statement in PHP?

I have two files named if.php and index.php. I am trying to use if.php to store the if condition for an if statement. However, it does not seem to be working as expected. Is it possible to achieve this? Thank you. if.php <?php if(Three == 3) { //do ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

What's causing the zero to appear after the ajax call?

This is my first time learning Ajax with WordPress and I'm trying to implement Ajax functionality with a widget. However, I am encountering an issue where I get a 0 after the form is submitted. Can someone provide guidance and explain why this is hap ...

Tips for maintaining ajax headers and enabling CORS in Angular resource requests

Within my ng-resource files, I have configured the ajax header as follows: var app = angular.module('custom_resource', ['ngResource']) app.config(['$httpProvider', function($httpProvider) { //enable XMLHttpRequest, indic ...

Can I incorporate FontAwesome font into fpdf?

Is there a way to incorporate fontawesome into PDF files? I currently generate my PDFs using the PHP library FPDF and font embedding, but I am having trouble getting it to work. I found this tool that generates AFM files: Despite trying to use fontawesom ...

How do you link a failing test to a reference when using $this->fail()?

Incorporating my custom assertion into Laravel's base TestCase class is something I'm working on. Here is a snippet of what it looks like: <?php namespace Tests\Mine; use Tests\TestCase; class SomeTest extends TestCase { publi ...

Show results from mySQL that are alike

Is there a way to generate a query that provides similar words if an exact match cannot be found? For example, when the query is attempting to match "mstke" and comes up empty in the database, the results should include related words like "mistake", "misst ...

Handling session expiration in ASP.NET MVC when making an AJAX call by redirecting to the login page

I'm currently learning ASP.NET MVC and I'm a newbie in it, so I'm struggling to find a solution for a specific problem. If anyone has encountered this issue before, I would appreciate any advice. Thank you! In my project, I am using ASP.NET ...

Parsing JSON in PHP to extract individual array values

Recently delving into PHP, I encountered a JSON file that I successfully decoded and stored as shown below: $jsonInput = '[{"b_pag_bo_id":"31","b_pag_user_id":"1","b_pag_id":"1","b_page_mark":"1","b_pag_num":"3","b_pag_note":"","b_page_stop":"1"},{"b ...

How can I populate a <select> tag with options dynamically using C# when the page loads?

I am using jQuery ajax to populate cascaded dropdown elements from a database. The issue I'm facing is that I can't seem to add the default "Select Program" option at the top of my first dropdown dynamically. Even though I tried using the prepend ...

Accessing data from a PHP array using JQuery

I've been struggling with extracting data from a PHP array for quite some time now. Despite examining multiple examples, my code simply refuses to work and I can't figure out where I am going wrong. A Different Approach in PHP function fetchLat ...

Display values in real-time when the text box is modified

Is there a way to update the total value in a text box based on user input using JavaScript and PHP, or just JavaScript? For example, if item "A" costs $25 and the customer orders 5 of "A", the total should automatically display as $125 when the quantity ...

I'm looking for expert tips on creating a killer WordPress theme design. Any suggestions on the best

Currently in the process of creating a custom Wordpress theme and seeking guidance on implementation. You can view the design outline here. Planning to utilize 960.gs for the css layout. My main concern is how to approach the services section (1, 2, 3...) ...

Obtain a numerical output from a selection of numbers

I am facing a simple problem that I can't solve due to my lack of knowledge and have not been able to find any solution online. What I want to achieve is: Create a "value 1" from an array of integers. Generate a random "value 2". Check if the rando ...

The user's input is not being accurately represented when making an AJAX request to the

When attempting to incorporate a user's city input (e.g. Los Angeles) into Ajax URL parameters, there seems to be an issue where the '+' is not being added between "los angels", resulting in a broken URL when console.log(searchURL) is used. ...

Troubleshooting Laravel 5 Routing Problem with CSS Directory

So, I have this route that loads a page, but for some reason, the css on the page doesn't load properly. Route::get('admins', function () { return view('admins/index'); }); Interestingly, when I use a different route with ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...