最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I get my Wordpress plugin to receive data and relay it in an ajaxphp request to a remote server that requires authentica

programmeradmin1浏览0评论

I have written a Wordpress plugin which places several buttons inside a metabox on the post-edit page. I'd go to example/wp-admin/post.php?post=number1&action=edit. I want my Wordpress hook to receive an AJAX call, and in turn makes a request to a remote server (one which requires authentication that the WP user shouldn't have to enter), then returns the result to the Wordpress user.

My code for the form with the data I want to send is two custom HTML elements' entered data. They are:

class MyFormData extends HTMLElement{
    
    constructor() {
      super();      
    }

    connectedCallback(){
      const li = document.createElement('li');

      const newDat = document.createElement('input');
      newDat.setAttribute('type','text');
      newDat.setAttribute('name',`title box`);
      newDat.setAttribute('placeholder',`Test Data`);

      const deleteButton = document.createElement('button');
      deleteButton.setAttribute('type','button');
      deleteButton.innerHTML = "-";
      deleteButton.addEventListener("click",function(){
        li.parentNode.remove();
      });

      li.appendChild(newDat);
      li.appendChild(deleteButton);

      this.appendChild(li);
    }
  }
customElements.define('form-data',MyFormData);

and

class DurationMenu extends HTMLElement{
    
    constructor(){
        super();
    }

    connectedCallback(){
        const amount = document.createElement('input');
        amount.setAttribute('id','selectedTime');
        amount.setAttribute('type','number');
        amount.setAttribute('step',5)
        amount.setAttribute('name','duration');
        amount.setAttribute('min',5);
        amount.setAttribute('max',60);
        amount.setAttribute('value',15);
        this.appendChild(amount)
    }


}
customElements.define('duration-choice', DurationMenu);

Both of these custom elements show up in the metabox. I have a custom element for the submit button:

import ModelObject from './model/modelobject.js'

var theJson;
var data;

import {CO} from './Controller/controllerobject.js';

export var c = new ModelObject();
import {grabDataForSending} from './Controller/wordpressrelay.js';

export class SubmitAndCreate extends HTMLElement{
    
    constructor(){
        super();            
    }

    connectedCallback(){
        var data;
        const submitbutton = document.createElement('button');
        submitbutton.setAttribute('type','submit');
        submitbutton.setAttribute('id','submitButton');
        submitbutton.innerHTML = "Begin ";

        submitbutton.addEventListener('click',this.myFunc.bind(this));

        submitbutton.addEventListener('click',()=>{
            document.getElementById('selectedTime').value = 15;
            var dataset = document.getElementById("dataset").children;
            for(var i = 0; i < dataset.length; i++){
                document.getElementById("dataset").children[i].children[0].childNodes[0].value = '';    
            }

        });
        submitbutton.addEventListener('click',(event)=>{
            CO.updateModelData();
            event.preventDefault();
        })

        submitbutton.addEventListener('click',(event)=>{
            grabExperimentForSending();
        })


        this.appendChild(submitbutton);
    }

    gatherData(){
        
        //var enteredURL = document.getElementsByName('URL box')[0].value;
        var dataAmount = document.getElementById('dataset').children.length;
        var experTime = document.getElementById('selectedTime').value;

        var dataObject = {
            experimentDuration : experTime,
            myData: {}
        }

        var individualDatum = [];

        for (var i = 0; i < dataAmount; i++){
            individualDatum[i] = {
                dataset: document.getElementById("dataset").children[i].children[0].childNodes[0].value
            }
        }

        dataObject.myData = individualDatum;
        var dataObjectJSON = JSON.stringify(dataObject,null,2);
        theJson = dataObjectJSON;

        

        return theJson;
    }

}
export {theJson, CO};
customElements.define('submit-button', SubmitAndCreate)

I want to grab the data one enters in both, and submit it to an external site that normally requires a password and username to login to from outside Wordpress. I want to submit it as JSon. How can I do this with Ajax and php?

My php so far is:

//for admin-ajax
    add_action( 'admin_enqueue_scripts', 'my_enqueue' );
    function my_enqueue($hook) {
        if( 'index.php' != $hook ) {
            return;
        }
            
        wp_enqueue_script( 'ajax-script', plugins_url( '/wp-content/plugins/my-plugin/js/Controller/ajaxdata.js', __FILE__ ), array('jquery') );
        wp_localize_script( 'ajax-script', 'ajax_object',
                array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'c' => c ) ); //c has the data that I need to send to the remote site's server
    }


    //relevant to admin-ajax
    add_action( 'wp_ajax_CBAjax', 'CBAjax' ); 
    
    //relevant to admin-ajax
    function CBAjax() {

        error_log(print_r($_REQUEST));
         
         if ( isset($_REQUEST) ) {

             $exper = $_REQUEST['experdata'];

             error_log(print_r($exper,true));

             
             echo "The exper is " . $exper;

         }

         
         $body = array(
             'dur'    => $exper['experimentDuration'],
             'buckets'=> $experdata['myData']
         );


         $response = wp_remote_post( $url = ":8080/api/v1/data", array(
             'body'    => $body,
             'headers' => array(
                 'Authorization' => 'Basic ' . base64_encode( "[email protected]" . ':' . "password!" ),
             ),
         ) );

         if($response){
            error_log(print_r($response,true));
            error_log("PING");

         }

         $respcode = wp_remote_retrieve_response_code($response);
         error_log(print_r($respcode,true));
         $ajax['remote_code'] = $response['response']['code'];
         echo json_encode( $ajax );
         error_log(print_r($ajax,true));

        wp_die();

        }

in the creation of the metabox, I have:

add_action( 'admin_enqueue_scripts', 'my_enqueue' ); add_action( 'wp_ajax_CBAjax', 'CBAjax' );

This is how I proxy the data from the button to the admin-ajax.php page:

import {c} from '../submitbutton.js';


function grabExperimentForSending(){
    

    $.ajax({
           url: "admin-ajax.php",
           type: "POST",
           data: c ,
           success: function (response, statusCode) {
                console.log(c.exps[0]);
                console.log(`statusCode is ${statusCode}`);
                console.log(`data is ${data}`);
           },
           error: function(jqXHR, textStatus, errorThrown) {
              console.log(`jqXHR is ${jqXHR}, textStatus is ${textStatus}, errorThrown is ${errorThrown}`);
              console.log(c.exps[0]);
           }
       });
}

and from there, it goes to ajaxdata.js

import {c} from './wordpressrelay.js';

function my_action_javascript(){
    
    $('#submitButton').click( function(){
    var data = { //model
        'action': 'CBAjax',

        'experdata': ajax_object.c
    }



    jQuery.post(ajax_object.ajax_url, data, function(response) { 
        console.log('Got this from the server: ' + response);
        console.log(data.experdata);
        console.log(`data[experdata] is ${data['experdata']}`);
    });
});

}

export {my_action_javascript,c};

export {grabExperimentForSending,c};

I want to send that data, exp (a Json) to the remote site. Right now, I get only 'bad request' and the response was 0. I'm not getting either javascript from communicating with the remote server or error logs from the php either

I have written a Wordpress plugin which places several buttons inside a metabox on the post-edit page. I'd go to example/wp-admin/post.php?post=number1&action=edit. I want my Wordpress hook to receive an AJAX call, and in turn makes a request to a remote server (one which requires authentication that the WP user shouldn't have to enter), then returns the result to the Wordpress user.

My code for the form with the data I want to send is two custom HTML elements' entered data. They are:

class MyFormData extends HTMLElement{
    
    constructor() {
      super();      
    }

    connectedCallback(){
      const li = document.createElement('li');

      const newDat = document.createElement('input');
      newDat.setAttribute('type','text');
      newDat.setAttribute('name',`title box`);
      newDat.setAttribute('placeholder',`Test Data`);

      const deleteButton = document.createElement('button');
      deleteButton.setAttribute('type','button');
      deleteButton.innerHTML = "-";
      deleteButton.addEventListener("click",function(){
        li.parentNode.remove();
      });

      li.appendChild(newDat);
      li.appendChild(deleteButton);

      this.appendChild(li);
    }
  }
customElements.define('form-data',MyFormData);

and

class DurationMenu extends HTMLElement{
    
    constructor(){
        super();
    }

    connectedCallback(){
        const amount = document.createElement('input');
        amount.setAttribute('id','selectedTime');
        amount.setAttribute('type','number');
        amount.setAttribute('step',5)
        amount.setAttribute('name','duration');
        amount.setAttribute('min',5);
        amount.setAttribute('max',60);
        amount.setAttribute('value',15);
        this.appendChild(amount)
    }


}
customElements.define('duration-choice', DurationMenu);

Both of these custom elements show up in the metabox. I have a custom element for the submit button:

import ModelObject from './model/modelobject.js'

var theJson;
var data;

import {CO} from './Controller/controllerobject.js';

export var c = new ModelObject();
import {grabDataForSending} from './Controller/wordpressrelay.js';

export class SubmitAndCreate extends HTMLElement{
    
    constructor(){
        super();            
    }

    connectedCallback(){
        var data;
        const submitbutton = document.createElement('button');
        submitbutton.setAttribute('type','submit');
        submitbutton.setAttribute('id','submitButton');
        submitbutton.innerHTML = "Begin ";

        submitbutton.addEventListener('click',this.myFunc.bind(this));

        submitbutton.addEventListener('click',()=>{
            document.getElementById('selectedTime').value = 15;
            var dataset = document.getElementById("dataset").children;
            for(var i = 0; i < dataset.length; i++){
                document.getElementById("dataset").children[i].children[0].childNodes[0].value = '';    
            }

        });
        submitbutton.addEventListener('click',(event)=>{
            CO.updateModelData();
            event.preventDefault();
        })

        submitbutton.addEventListener('click',(event)=>{
            grabExperimentForSending();
        })


        this.appendChild(submitbutton);
    }

    gatherData(){
        
        //var enteredURL = document.getElementsByName('URL box')[0].value;
        var dataAmount = document.getElementById('dataset').children.length;
        var experTime = document.getElementById('selectedTime').value;

        var dataObject = {
            experimentDuration : experTime,
            myData: {}
        }

        var individualDatum = [];

        for (var i = 0; i < dataAmount; i++){
            individualDatum[i] = {
                dataset: document.getElementById("dataset").children[i].children[0].childNodes[0].value
            }
        }

        dataObject.myData = individualDatum;
        var dataObjectJSON = JSON.stringify(dataObject,null,2);
        theJson = dataObjectJSON;

        

        return theJson;
    }

}
export {theJson, CO};
customElements.define('submit-button', SubmitAndCreate)

I want to grab the data one enters in both, and submit it to an external site that normally requires a password and username to login to from outside Wordpress. I want to submit it as JSon. How can I do this with Ajax and php?

My php so far is:

//for admin-ajax
    add_action( 'admin_enqueue_scripts', 'my_enqueue' );
    function my_enqueue($hook) {
        if( 'index.php' != $hook ) {
            return;
        }
            
        wp_enqueue_script( 'ajax-script', plugins_url( '/wp-content/plugins/my-plugin/js/Controller/ajaxdata.js', __FILE__ ), array('jquery') );
        wp_localize_script( 'ajax-script', 'ajax_object',
                array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'c' => c ) ); //c has the data that I need to send to the remote site's server
    }


    //relevant to admin-ajax
    add_action( 'wp_ajax_CBAjax', 'CBAjax' ); 
    
    //relevant to admin-ajax
    function CBAjax() {

        error_log(print_r($_REQUEST));
         
         if ( isset($_REQUEST) ) {

             $exper = $_REQUEST['experdata'];

             error_log(print_r($exper,true));

             
             echo "The exper is " . $exper;

         }

         
         $body = array(
             'dur'    => $exper['experimentDuration'],
             'buckets'=> $experdata['myData']
         );


         $response = wp_remote_post( $url = "https://subdomain.example:8080/api/v1/data", array(
             'body'    => $body,
             'headers' => array(
                 'Authorization' => 'Basic ' . base64_encode( "[email protected]" . ':' . "password!" ),
             ),
         ) );

         if($response){
            error_log(print_r($response,true));
            error_log("PING");

         }

         $respcode = wp_remote_retrieve_response_code($response);
         error_log(print_r($respcode,true));
         $ajax['remote_code'] = $response['response']['code'];
         echo json_encode( $ajax );
         error_log(print_r($ajax,true));

        wp_die();

        }

in the creation of the metabox, I have:

add_action( 'admin_enqueue_scripts', 'my_enqueue' ); add_action( 'wp_ajax_CBAjax', 'CBAjax' );

This is how I proxy the data from the button to the admin-ajax.php page:

import {c} from '../submitbutton.js';


function grabExperimentForSending(){
    

    $.ajax({
           url: "admin-ajax.php",
           type: "POST",
           data: c ,
           success: function (response, statusCode) {
                console.log(c.exps[0]);
                console.log(`statusCode is ${statusCode}`);
                console.log(`data is ${data}`);
           },
           error: function(jqXHR, textStatus, errorThrown) {
              console.log(`jqXHR is ${jqXHR}, textStatus is ${textStatus}, errorThrown is ${errorThrown}`);
              console.log(c.exps[0]);
           }
       });
}

and from there, it goes to ajaxdata.js

import {c} from './wordpressrelay.js';

function my_action_javascript(){
    
    $('#submitButton').click( function(){
    var data = { //model
        'action': 'CBAjax',

        'experdata': ajax_object.c
    }



    jQuery.post(ajax_object.ajax_url, data, function(response) { 
        console.log('Got this from the server: ' + response);
        console.log(data.experdata);
        console.log(`data[experdata] is ${data['experdata']}`);
    });
});

}

export {my_action_javascript,c};

export {grabExperimentForSending,c};

I want to send that data, exp (a Json) to the remote site. Right now, I get only 'bad request' and the response was 0. I'm not getting either javascript from communicating with the remote server or error logs from the php either

Share Improve this question edited Jun 25, 2020 at 19:57 AviG asked Jun 15, 2020 at 21:21 AviGAviG 1033 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

In your PHP to call the remote server you may want to look at the http and API functions availalble in Wordpress here: https://developer.wordpress/plugins/http-api/

For example, here's a much easier way to get data from a remote server:

$response = wp_remote_get( 'https://api.github/users/blobaugh' );
$http_code = wp_remote_retrieve_response_code( $response );

And here's a way to post like you were submitting a form:

$body = array(
    'sendThisValue'    => 'value',
);

$args = array(
    'body'        => $body,
// see docs for rest of parameters here
);

$response = wp_remote_post( 'http://your-contact-form', $args );

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论