dongshuo8756 2016-02-01 08:18
浏览 99
已采纳

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

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).

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

<?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

$('#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.

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

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.

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?

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:

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 :)

I guess I needed user_agent and correct query string.

  • 写回答

1条回答 默认 最新

  • dsogx84602 2016-02-01 09:00
    关注

    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,

    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.

    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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料