ajax表单提交到php文件和url?

时间:2021-11-10 09:05:51

I have a subscribe form in wordpress that (currently) only has the ability to add submitted email to a custom post type (subscribers) and show it in backend.I am wondering how to also have this functionality, and send this email to a custom url (concretely to APSIS).

我在wordpress中有一个订阅表单(目前)只能将提交的电子邮件添加到自定义帖子类型(订阅者)并在后端显示。我想知道如何也有这个功能,并将此电子邮件发送到自定义网址(具体到APSIS)。

So I have a form

所以我有一张表格

<form id="subscribe" class="subscribe_form" name="subscribe_form" action="#" method="post">
    <input name="subscriber_email" class="subscriber_email" placeholder="Your mail here">
    <input class="submit" type="submit" value="Submit">
</form>

My save custom post type function that gets executed via AJAX

我的保存自定义帖子类型功能,通过AJAX执行

<?php 

add_action('wp_ajax_save_subscriber', 'save_subscriber');
add_action('wp_ajax_nopriv_save_subscriber', 'save_subscriber');

if (!function_exists('save_subscriber')) {
    function save_subscriber() {

        if (isset($_POST['subscriber_email']) && is_email($_POST['subscriber_email'])) {
            global $wpdb;
            $post_data = array(
                'post_type' => 'subscribers',
                'post_status' => 'publish'
            );
            $published_id = wp_insert_post( $post_data );
            add_post_meta($published_id, 'subscriber_email', $_POST['subscriber_email']);
            $out = 'OK';
        } else{
            $out = 'ERROR';
        }

        die($out);
    }
}

And my AJAX

还有我的AJAX

$('#subscribe').submit(function() {
    'use strict';
    var str = $(this).serialize() + '&action=save_subscriber';
    var $form = $(this);
    var $wrapper = $(this).parent();
    $.ajax({
        type: 'POST',
        url: custom.ajaxurl,
        data: str,
        success: function(msg){
            if( msg === 'OK' ) {
                $form.animate({ height: '0px' }, 800, function() {
                    $form.hide();
                });
                $wrapper.find('.success_message').delay(400).html(custom.success).slideDown(600);
            }else {
                $wrapper.find('.subscriber_email').addClass('field_error').attr('placeholder', custom.error_mail).val('').focus();
            }
        }
    });
    return false;
});

Now I have some more wrappers, and noonce field etc. but that's not important here.

现在我有更多包装器和noonce字段等,但这在这里并不重要。

This works fine when you want to just add a post to the CPT, but I need to submit this to

当你只想向CPT添加帖子时,这可以正常工作,但我需要将其提交给

http://www.anpdm.com/public/process-subscription-form.aspx?formId=xxxxxxxxxxx

I got the id and everything from the client, now I need to implement this.

我从客户端获得了id和所有内容,现在我需要实现它。

I've seen something about curl, but I've never done anything with it, so I don't really know where to start. Since my action is pointing to my save_subscriber() function I recon that in that function I'd also have to add a way to send this form to the required url. But how?

我见过一些关于卷曲的事情,但我从来没有做过任何事情,所以我真的不知道从哪里开始。由于我的操作指向我的save_subscriber()函数,我在该函数中重新调查,我还必须添加一种方法将此表单发送到所需的URL。但是怎么样?

Any info will help, thanks.

任何信息都会有所帮助,谢谢。

ANSWER

So following the answer provided by silver, I managed to get it working.

所以按照白银提供的答案,我设法让它运转起来。

#Run CURL
$url = 'http://www.anpdm.com/public/process-subscription-form.aspx?formId=xxxxxxxxxx';

$request = curl_init();
curl_setopt_array( $request, array (
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
    CURLOPT_POSTFIELDS => $custom_query_string,
));
$response = curl_exec($request);
$response_data = curl_getinfo($request);
curl_close($request);

#END CURL
if ($response_data['http_code'] == 200) {
    $out = 'OK';
}

The formId is the form number specific for this user, and the $custom_query_string conformed to the form provided by APSIS and contained something like this:

formId是特定于此用户的表单编号,$ custom_query_string符合APSIS提供的表单,包含如下内容:

pf_Email=$_POST['email']&
Submit=Prenumerera&
pf_DeliveryFormat=HTML&
pf_MailinglistName1=xxxxx&
pf_FormType=OptInForm&
pf_OptInMethod=SingleOptInMethod&
pf_CounterDemogrFields=0&
pf_CounterMailinglists=1&
pf_AccountId=xxxx&
pf_ListById=1&
pf_Version=2

After that all worked, I get my subscribers in the wordpress backend, and they appear in the APSIS console where the users are :)

在所有工作之后,我在wordpress后端获得订阅者,并且他们出现在用户所在的APSIS控制台中:)

I guess I needed user_agent and correct query string.

我想我需要user_agent和正确的查询字符串。

1 个解决方案

#1


0  

If I were you I'll just duplicate the current form with different ID and action pointing to a different URL then hide it populating it automatically based on firs form, then silently submit it on Success response of first form Ajax request,

如果我是你,我只会复制当前表单,其中不同的ID和操作指向不同的URL,然后隐藏它根据第一个表单自动填充它,然后在第一个表单Ajax请求的成功响应中静默提交,

But yeah, If you need to POST URL using CURL-PHP without any form this example code below will probably do, I hook it on your current function.

但是,如果您需要使用CURL-PHP POST URL而不使用任何形式,下面的示例代码可能会这样做,我将它挂钩到您当前的函数。

function save_subscriber() {
    if (isset($_POST['subscriber_email']) && is_email($_POST['subscriber_email'])) {
        global $wpdb;
        $post_data = array(
            'post_type' => 'subscribers',
            'post_status' => 'publish'
        );
        $published_id = wp_insert_post( $post_data );
        add_post_meta($published_id, 'subscriber_email', $_POST['subscriber_email']);

        #Run CURL
        $url = 'http://www.anpdm.com/public/process-subscription-form.aspx'; // URL to be Posted
        $request = curl_init(); //open connection
        curl_setopt_array( $request, array (
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_URL => $url,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $_REQUEST, /* Since your form is already serialize, you don't need to build query string*/
        ));
        $response = curl_exec($request); // Execute Curl
        $response_data = curl_getinfo($request); // Array of curl response info
        curl_close($request); // Close Connection

        #END CURL

        #$out = $response; // push curl response on Ajax Submit response
        $out = $response_data['http_code']; /* 200 will be the value of this for successfully curl request, you can just replace your Ajax success code with 200 instead of OK or just ignore the response, though its better to know if curl request is successful*/
    } else{
        $out = 'ERROR';
    }
    die($out);
}

Testing

$url = 'http://www.anpdm.com/public/process-subscription-form.aspx'; 
$request = curl_init(); 
curl_setopt_array( $request, array (
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => "id=noID&value=novalue",
));
$response = curl_exec($request); 
$response_data = curl_getinfo($request); 
curl_close($request);
print_r( $response_data );

$response_data OUTPUT

Array
(
    [url] => http://www.anpdm.com/public/process-subscription-form.aspx
    [content_type] => text/html; charset=utf-8
    [http_code] => 200
    [header_size] => 222
    [request_size] => 180
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 1.546
    [namelookup_time] => 0.515
    [connect_time] => 0.843
    [pretransfer_time] => 0.843
    [size_upload] => 21
    [size_download] => 13048
    [speed_download] => 8439
    [speed_upload] => 13
    [download_content_length] => 13048
    [upload_content_length] => 21
    [starttransfer_time] => 1.203
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => 89.234.52.177
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => 192.168.254.8
    [local_port] => 53736
)

#1


0  

If I were you I'll just duplicate the current form with different ID and action pointing to a different URL then hide it populating it automatically based on firs form, then silently submit it on Success response of first form Ajax request,

如果我是你,我只会复制当前表单,其中不同的ID和操作指向不同的URL,然后隐藏它根据第一个表单自动填充它,然后在第一个表单Ajax请求的成功响应中静默提交,

But yeah, If you need to POST URL using CURL-PHP without any form this example code below will probably do, I hook it on your current function.

但是,如果您需要使用CURL-PHP POST URL而不使用任何形式,下面的示例代码可能会这样做,我将它挂钩到您当前的函数。

function save_subscriber() {
    if (isset($_POST['subscriber_email']) && is_email($_POST['subscriber_email'])) {
        global $wpdb;
        $post_data = array(
            'post_type' => 'subscribers',
            'post_status' => 'publish'
        );
        $published_id = wp_insert_post( $post_data );
        add_post_meta($published_id, 'subscriber_email', $_POST['subscriber_email']);

        #Run CURL
        $url = 'http://www.anpdm.com/public/process-subscription-form.aspx'; // URL to be Posted
        $request = curl_init(); //open connection
        curl_setopt_array( $request, array (
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_URL => $url,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $_REQUEST, /* Since your form is already serialize, you don't need to build query string*/
        ));
        $response = curl_exec($request); // Execute Curl
        $response_data = curl_getinfo($request); // Array of curl response info
        curl_close($request); // Close Connection

        #END CURL

        #$out = $response; // push curl response on Ajax Submit response
        $out = $response_data['http_code']; /* 200 will be the value of this for successfully curl request, you can just replace your Ajax success code with 200 instead of OK or just ignore the response, though its better to know if curl request is successful*/
    } else{
        $out = 'ERROR';
    }
    die($out);
}

Testing

$url = 'http://www.anpdm.com/public/process-subscription-form.aspx'; 
$request = curl_init(); 
curl_setopt_array( $request, array (
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => "id=noID&value=novalue",
));
$response = curl_exec($request); 
$response_data = curl_getinfo($request); 
curl_close($request);
print_r( $response_data );

$response_data OUTPUT

Array
(
    [url] => http://www.anpdm.com/public/process-subscription-form.aspx
    [content_type] => text/html; charset=utf-8
    [http_code] => 200
    [header_size] => 222
    [request_size] => 180
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 1.546
    [namelookup_time] => 0.515
    [connect_time] => 0.843
    [pretransfer_time] => 0.843
    [size_upload] => 21
    [size_download] => 13048
    [speed_download] => 8439
    [speed_upload] => 13
    [download_content_length] => 13048
    [upload_content_length] => 21
    [starttransfer_time] => 1.203
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => 89.234.52.177
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => 192.168.254.8
    [local_port] => 53736
)