• I have written a WordPress plugin which places several buttons inside a metabox on the post-edit page. To see the page where this is done, I’d go to example.com/wp-admin/post.php?post=number1&action=edit When one of the buttons is clicked, I want to use php code to send data to a remote server that requires a password; however, I understand PHP cannot listen for click events. How might I go about doing this? I will be making an Ajax request and sending data thru a proxy.

    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',<code>title box</code>);
              newDat.setAttribute('placeholder',<code>Test Data</code>);
        
              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:
    
        add_action( 'admin_footer', 'my_action_javascript' ); 
    	<script type="text/javascript" >
    	jQuery(document).ready(function($) {
    
    		var data = {
    			'action': 'MytestAjax',
    		};
    
    		jQuery.post(ajaxurl, data, function(response) {
    			alert('Got this from the server: ' + response);
    		});
    	});
    	</script> <?php
    }
    
        add_action( 'wp_ajax_my_action', 'MytestAjax' );
        
        function MytestAjax() {
    	header('Content-type: application/json');
    	$url = 'https://subdomain.example.com:port/api/v1/whereIWantItToGo';
    
    	//I'm not sure how to authenticate into the above site from here
    	if (isset($_POST['username']) && $_POST['username'] && isset($_POST['password']) && $_POST['password']) {
    	    echo json_encode(array('success' => 1));
    	} else {
    	    echo json_encode(array('success' => 0));
    	}
    	$handle = fopen($url, "r");
    	if ($handle) {
    	    while (!feof($handle)) {
    	        $buffer = fgets($handle, 4096);
    	        echo $buffer;
    	    }
    	    fclose($handle); 
    
    	wp_die();
    	}
    
    }

    Once a person hits the submit button, then I need it to go to do ajax and php.

Viewing 15 replies - 1 through 15 (of 22 total)
  • Thank you, I did it.

    Moderator bcworkz

    (@bcworkz)

    Are the access credentials for the remote server provided by the end user or do they belong to you and must remain hidden from end users? If the former, you can submit directly to the server and not go through your WP server. If the latter, make a proper WP Ajax request. Then have your Ajax handler make the remote API request and relay the result back to the client.

    As detailed in the above link, WP Ajax request must go through /wp-admin/admin-ajax.php and must contain an “action” parameter which is used to compose an action hook which fires to execute your PHP Ajax handler.

    Thread Starter bullshark

    (@bullshark)

    @bcworkz the authentication deets should not need to be entered for the remote server. The user has already logged into wordpress at the point of using this plugin. I’m just confused what a proper WP Ajax request might look like at this point, and in relation to the code I’ve provided. Please help me flesh it out. Thanks.

    The AJAX hook I need to make has been described as (tho I don’t know what it truly means) as that receives instructions from the browser, and uses those instructions to make a request to the remote server.

    • This reply was modified 4 years, 8 months ago by bullshark.
    Moderator bcworkz

    (@bcworkz)

    If the remote server needs no credentials, your WP server need not be involved in the transaction (after serving the initial content and script of course). You can have your jQuery code make a request directly to the remote server using .post(). What constitutes a proper request depends on that server’s requirements. How one would make a proper Ajax request to WP would not matter unless the remote server is also running WP. Even if it were, it may be more appropriate to use the REST API than attempt to go through admin-ajax.php.

    Thread Starter bullshark

    (@bullshark)

    the remote server does need a password. Php code needs to interface with that server.

    Thread Starter bullshark

    (@bullshark)

    @bcworkz the remote server than the logged in WP user needs to send data to does need a password. I need the WP user’s browser to make a request to WordPress; the hook I need to write must receive that AJAX call, and in turn makes a request to the remote server, then returns the result to the WordPress user.

    Moderator bcworkz

    (@bcworkz)

    I see, sorry for my confusion. Make an Ajax request to your WP from the current page. Include an “action” parameter which is used to construct an action hook. Add your callback to this action which contacts the remote server from the WP server. Details in the link from my first reply here.

    Thread Starter bullshark

    (@bullshark)

    @bcworkz with the code I’ve provided, what might what I need to do look like?

    Moderator bcworkz

    (@bcworkz)

    I’m not going to rewrite your code for you, but I will point out the ajaxurl in the footer jQuery appears to be undefined. It should be leading to /wp-admin/admin-ajax.php. Use the full URL for this. Your code is running when the page loads. You want it to run when the button is clicked. Your action value is ‘MytestAjax’. Thus your PHP action hook should be ‘wp_ajax_MytestAjax’, not ‘wp_ajax_my_action’.

    Thread Starter bullshark

    (@bullshark)

    @bcworkz where do I write/define the ajaxurl?

    Thread Starter bullshark

    (@bullshark)

    my php code is

    function my_action_javascript() { ?>
            <script type="text/javascript" >
            jQuery(document).ready(function($) {
                
                var data = {
                    'action': 'cbAjax',
                    'experdata': c.exps[0]
                };
                
                
                
                jQuery.post(ajaxurl, data, function(response) {
                    console.log('Got this from the server: ' + response);
                    console.log(data.experdata);
                    console.log(<code>data[experdata] is ${data['experdata']}</code>);
                });
            });
            </script> <?php
            error_log(print_r(serialize($_GET['experdata']),true));
        }
        
    
        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['headlineBuckets']
             );
    
             $response = wp_remote_post( $url = "https://subdomain.example.com:9003/api/v1/experiment", array(
                 'body'    => $body,
                 'headers' => array(
                     'Authorization' => 'Basic ' . base64_encode( "myemail@email.com" . ':' . "mypassword" ),
                 ),
             ) );
    
             if($response){
                error_log(print_r($response,true));
                error_log("PING");
             }
             
            wp_die();
    
        }
    in the creation of the metabox, I have:
    
        add_action( 'wp_ajax_my_action_javascript', 'my_action_javascript' ); // Write our JS below here
        add_action( 'wp_ajax_cbAjax', 'cbAjax' );

    Thing is: how do I get a status code from the server so I can know if any data was transferred at all to the server?

    Moderator bcworkz

    (@bcworkz)

    Pass a value like ajaxurl from PHP to jQuery with wp_localize_script().

    Server status is returned to to the .post() function’s success: callback. You can also use your browser’s network developer tool to examine the transaction. Or check your server’s access log.

    If you need to debug your PHP callback, you can use error_log() to write debugging data to the log file and check it after making a test Ajax request.

    Thread Starter bullshark

    (@bullshark)

    @bcworkz can you show me how I might do this in code, now that I’ve posted code and written, so its not like I’m asking you to write my code for me. It’s just that I’m confused bc I barely have written WordPress and the mini examples online are just that; mini.

    I want a status code from sending the data to https://subdomain.example.com:9003/api/v1/experiment, not from sending it from the browser to admin-ajax.

    Moderator bcworkz

    (@bcworkz)

    The remote site’s status response should be in $response['response']['code']. It can be echoed out back to the Ajax caller as part of the response. There’s no required way to respond to an Ajax request. Anything goes, but client and server side code of course needs to be coordinated. I would generally compile the entire Ajax response into a single array, then JSON encode it. I’d then echo out the JSON string. Basically:

    $ajax['remote_code'] = $response['response']['code'];
    echo json_encode( $ajax );
    Thread Starter bullshark

    (@bullshark)

    @bcworkz I’ve tried putting what you’ve put in my code and nothing new shows up in the error log or anywhere. How can I see the value of the remote code?

Viewing 15 replies - 1 through 15 (of 22 total)
  • The topic ‘How can I write hook that receives AJAX call from button click?’ is closed to new replies.