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

JQuery calling a Custom PHP function (Works in Dev but not in WordPress)

programmeradmin0浏览0评论

My code is working fine on my localhost in my development environment which is outside of the WordPress press environment. I know the PHP function is working. I am able to send test votes to my server from my localhost on my PC.

Problem: I cannot get this to work in WordPress.

My Thoughts I think it's a path issue, but I've tried putting the PHP script in the root and using a full path. I am not getting any errors in the web browser console (f12).

WordPress Version: 5.4.1 I put my custom php code into "/wp-contents/custom-php/votifier.php" My JQuery script is in the header. (yes, I know I should put it in the footer.)

The Button

<div id="voteButton">
<button type="button">Try it</button>
</div>

Localhost Version

<script>
$(document).ready(function(){
  $("#voteButton").click(function(){
    $.post("votifier/votifier.php",
    {
      key: $.trim($("#field_yjr62").val()),
      ip: $('input[name="item_meta[40]"]').val(),
      port: $('input[name="item_meta[42]"]').val(),
      service: "Votifier",
      username: $('input[name="item_meta[59]"]').val()
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>

WordPress Version

<script>
jQuery(document).ready(function( $ ) {
  jQuery("#voteButton").click(function(){
    $.post("/home/xxxxxxxxxxxx/public_html/wp-content/custom-php/votifier.php",
    {
      key: $.trim($("#field_yjr62").val()),
      ip: $('input[name="item_meta[40]"]').val(),
      port: $('input[name="item_meta[42]"]').val(),
      service: "Votifier",
      username: $('input[name="item_meta[59]"]').val()
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>

My Custom PHP Script

<?php

const VOTE_FORMAT = "VOTE\n%s\n%s\n%s\n%d\n";
const PUBLIC_KEY_FORMAT = "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----";

$public_key     = formatPublicKey($_POST['key']);
$server_ip      = $_POST["ip"];
$port           = $_POST["port"];
$service_name   = $_POST["service"];
$username       = $_POST["username"];

sendVote($username, $public_key, $server_ip, $port, $service_name);

function formatPublicKey($public_key) {
    $public_key = wordwrap($public_key, 65, "\n", true);
    $public_key = sprintf(PUBLIC_KEY_FORMAT, $public_key);
    return $public_key;
}

function sendVote($username, $public_key, $server_ip, $port, $service_name) {


    if (php_sapi_name() !== 'cli') {
        //Detect proxy and use correct IP.
        $address = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
    } else {
        //Script is run via CLI, use server name.
        $address = $_SERVER['SERVER_NAME'];
    }

    $data = sprintf(VOTE_FORMAT, $service_name, $username, $address, time());
    openssl_public_encrypt($data, $crypted, $public_key);
    $socket = @fsockopen($server_ip, $port);

    if ($socket) {
        if (fwrite($socket, $crypted)) {
            fclose($socket);
            return true;
        }
    }

    return false;
}
?>

Network Info

Request URL:.php
Request Method:POST
Remote Address:999.999.999.99:443
Status Code:
404
Version:HTTP/2
Referrer Policy:strict-origin-when-cross-origin

My code is working fine on my localhost in my development environment which is outside of the WordPress press environment. I know the PHP function is working. I am able to send test votes to my server from my localhost on my PC.

Problem: I cannot get this to work in WordPress.

My Thoughts I think it's a path issue, but I've tried putting the PHP script in the root and using a full path. I am not getting any errors in the web browser console (f12).

WordPress Version: 5.4.1 I put my custom php code into "/wp-contents/custom-php/votifier.php" My JQuery script is in the header. (yes, I know I should put it in the footer.)

The Button

<div id="voteButton">
<button type="button">Try it</button>
</div>

Localhost Version

<script>
$(document).ready(function(){
  $("#voteButton").click(function(){
    $.post("votifier/votifier.php",
    {
      key: $.trim($("#field_yjr62").val()),
      ip: $('input[name="item_meta[40]"]').val(),
      port: $('input[name="item_meta[42]"]').val(),
      service: "Votifier",
      username: $('input[name="item_meta[59]"]').val()
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>

WordPress Version

<script>
jQuery(document).ready(function( $ ) {
  jQuery("#voteButton").click(function(){
    $.post("/home/xxxxxxxxxxxx/public_html/wp-content/custom-php/votifier.php",
    {
      key: $.trim($("#field_yjr62").val()),
      ip: $('input[name="item_meta[40]"]').val(),
      port: $('input[name="item_meta[42]"]').val(),
      service: "Votifier",
      username: $('input[name="item_meta[59]"]').val()
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>

My Custom PHP Script

<?php

const VOTE_FORMAT = "VOTE\n%s\n%s\n%s\n%d\n";
const PUBLIC_KEY_FORMAT = "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----";

$public_key     = formatPublicKey($_POST['key']);
$server_ip      = $_POST["ip"];
$port           = $_POST["port"];
$service_name   = $_POST["service"];
$username       = $_POST["username"];

sendVote($username, $public_key, $server_ip, $port, $service_name);

function formatPublicKey($public_key) {
    $public_key = wordwrap($public_key, 65, "\n", true);
    $public_key = sprintf(PUBLIC_KEY_FORMAT, $public_key);
    return $public_key;
}

function sendVote($username, $public_key, $server_ip, $port, $service_name) {


    if (php_sapi_name() !== 'cli') {
        //Detect proxy and use correct IP.
        $address = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
    } else {
        //Script is run via CLI, use server name.
        $address = $_SERVER['SERVER_NAME'];
    }

    $data = sprintf(VOTE_FORMAT, $service_name, $username, $address, time());
    openssl_public_encrypt($data, $crypted, $public_key);
    $socket = @fsockopen($server_ip, $port);

    if ($socket) {
        if (fwrite($socket, $crypted)) {
            fclose($socket);
            return true;
        }
    }

    return false;
}
?>

Network Info

Request URL:https://bestlist/home/xxxxxxxxxxxx/public_html/wp-content/custom-php/votifier.php
Request Method:POST
Remote Address:999.999.999.99:443
Status Code:
404
Version:HTTP/2
Referrer Policy:strict-origin-when-cross-origin
Share Improve this question edited May 23, 2020 at 2:17 ScottUSA asked May 23, 2020 at 0:39 ScottUSAScottUSA 193 bronze badges 8
  • That's not the correct way to deal with AJAX requests in WordPress. You should hook to the wp_ajax_ action. Anyway, if you're using chrome, what does the network tab show about that request response? – Himad Commented May 23, 2020 at 0:44
  • regarding the AJAX Thanks. About the network tab: I'm using firefox. The WordPress site doesn't show anything, but the network tab for my localhost looks normal. Stats of 200, Method is post, domain is localhost – ScottUSA Commented May 23, 2020 at 1:12
  • Can you modify the PHP script and add die('Example'); as the first line? If your request is correctly going through you should see the message as the response. – Himad Commented May 23, 2020 at 1:14
  • okay, I added that to the PHP script and nothing. I know the button is working. So, it has to be the JQuery. I checked page source and I can see my JQuery script in the header and it looks good. I guess I have to learn AJAX for WordPress. – ScottUSA Commented May 23, 2020 at 1:30
  • 1 Your url is definitely wrong. You are trying to access a server path instead of an url. $.post("/home/xxxxxxxxxxxx/public_html/wp-content/custom-php/votifier.php",. Can't you just use /wp-contents/custom-php/votifier.php? If you output something in your PHP file you could check whether or not it is reachable by just entering the full url in your address bar bestlist/wp-contents/custom-php/votifier.php – Hannes Commented May 23, 2020 at 12:03
 |  Show 3 more comments

1 Answer 1

Reset to default -1

Function: The user clicks a button on a webpage

Action: The click should connect to an external server using the following params:

1. User Name 2. IP Address 3. Port 4. Public Key 5. Service

The PHP code is still not sending the vote to my external server. So, I tried a slightly different approach. That is, I am trying to use the wp ajax action.

The Server side PHP is the same (see above).

I have Wordpress in debug mode, but I'm not getting any errors.

I'm using Firefox and the form data looks good:

HTML CODE

/* XXXX  HTML BUTTON XXXX  */
<div id="frm_field_61_container">
<button type="button">Test Vote</button>
</div>

JQuery AJAX

/* XXXXX JQuery / AJAX Call XXXX */ 
jQuery(document).ready( function($) {
 $("#frm_field_61_container").click(function(){
      nonce = 'votifier_response_key';

      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {    action: "my_vote_count"
                    ,key: $.trim($("#field_yjr62").val())
                    ,ip: $('input[name="item_meta[40]"]').val()
                    ,port: $('input[name="item_meta[42]"]').val()
                    ,service: "Votifier"
                    ,username: $('input[name="item_meta[59]"]').val()
                    ,nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
               alert("Your vote was counted!")
            }
            else {
               alert("Your vote could not be added")
            }
         }
      });   

   });

});

WordPress - functions dot php file

/* ===== WordPress Java Script Registration  ==== */
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
function my_script_enqueuer() {
   wp_register_script( "my_voter_script", get_stylesheet_directory_uri() . '/js/sendvote.js', array('jquery') );
   wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'my_voter_script' );

}


/* ===== My Votifier Code ==== */
add_action( 'wp_ajax_my_vote_count', 'my_ajax_handler');
add_action( 'wp_ajax_nopriv_my_vote_count', 'my_ajax_handler' );
function my_ajax_handler() {
    check_ajax_referer( 'votifier_response_key' );
    echo "Thank You for your Vote!";
    wp_die(); // All ajax handlers die when finished
}

JQuery is Registered and showing up in the footer

When I click on the link in the footer, I see the JQuery:

发布评论

评论列表(0)

  1. 暂无评论