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 cmd批处理参数如果含有双引号,该如何传入?
  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统
  • ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)
  • ¥100 某宝多次访问被拒绝,求解
  • ¥15 (标签-STM32|关键词-智能小车)