简体   繁体   中英

Ajax Error: Unexpected token < in JSON at position 0 on WordPress Contact Form 7 submit

I have a weird issue when posting an contact form.

The loading icon keeps loading and the form does not submit.

The emails are sended and my before_send_mail functions also works. The weird thing is when i uncomment the before_send_mail function, it shows no errors. So it's probably something from my code.

However the frontpage is not changing status and keeps showing the loading icon.

The error message sais:

<div class="ajax-error">Unexpected token &lt; in JSON at position 0</div>

Can you guys help me out? Below you'll find the before_send function.

add_action( 'wpcf7_before_send_mail', 'form_to_crm' );
function form_to_crm( $cf7 ) {
    $wpcf7 = WPCF7_ContactForm::get_current();

    /* Uw naam   => first_name    */ $first_name            = $_POST["your-name"];
    /* Bedrijf   => company_name  */ $company               = $_POST["bedrijf"];
    /* Email     => email         */ $email                 = $_POST["email"];
    /* Adres     => address       */ $address               = $_POST["adres"];
    /* Nummer*   => number        */ $number                = $_POST["huisnummer"];
    /* Postcode  => postcode      */ $postcode              = $_POST["postcode"];
    /* Woonplts* => city          */ $city                  = $_POST["woonplaats"];
    /* Tel       => telephone     */ $telephone             = $_POST["telefoonnummer"]; 

    if(!empty( $first_name )){          $post_items['first_name']           =  $first_name; }
    if(!empty( $company )){             $post_items['company_name']         =  $company; }
    if(!empty( $email )){               $post_items['email']                =  $email; }
    if(!empty( $address )){             $post_items['address']              =  $address; }
    if(!empty( $number )){              $post_items['number']               =  $number; }
    if(!empty( $postcode )){            $post_items['postcode']             =  $postcode; }
    if(!empty( $city )){                $post_items['city']                 =  $city; }
    if(!empty( $telephone )){           $post_items['telephone']            =  $telephone; }

    if(!empty($postcode) && !empty($number))
    {
        $ch             = curl_init();

        if ( curl_error($ch) != "" ) 
        {
            return;
        }

        $post_string    = json_encode($post_items);

        $con_url        = 'valid api url';

        curl_setopt($ch, CURLOPT_URL, $con_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "Authorization: Token XXX (censored)"
        ));
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

        $output = curl_exec($ch);

        file_put_contents("curlerror.txt", $output);
        curl_close($ch);
    }
    return $output;
}

@Senta 's answer helped me find the cause of the error for me. It turned out that the response being received by CF7's AJAX call wasn't just the JSON response from CF7, but another plugin was adding stuff into it, causing the AJAX to fail because it was expecting a json format, and was now horrendously invalid (what was only supposed to be 1 line of JSON turned into 300+ lines of other stuff prepended to it).

I don't like editing plugins, but I did this to help resolve this issue and allow CF7 to play well with others and it now looks like this:

contact-form-7/includes/js/scripts.js OR if you're using the jQuery validation plugin for Contact Form 7, you'll want jquery-validation-for-contact-form-7/js/jquery.jvcf7_validation.js

$.ajax({
    type: 'POST',
    url: wpcf7.apiSettings.root + wpcf7.apiSettings.namespace +
        '/contact-forms/' + wpcf7.getId($form) + '/feedback',
    data: formData,
    dataType: 'text',//Changed from 'json' to 'text'
    processData: false,
    contentType: false
    }).done(function(data, status, xhr) {
        var f = data.indexOf('{'); //First opening curly-brace
        var l = data.lastIndexOf('{'); //Last opening curly-brace
        if (f !== l && data.indexOf("{") !== 0 && l !== 0) {
            //If the first and last indices are not the same, and neither the first nor the last are equal to 0,
            //then get the data that starts from the last index
            data = data.substring(l);
        } else if (f === l && f !== 0) {
            //If the first and last indices are the same, but are not the first character,
            //then get the data that starts from the first index
            data = data.substring(f);
        }
        $('.ajax-loader', $form).removeClass('is-active');
        try {
            //Try parsing the data as JSON now and submitting it
            data = JSON.parse(data);
            ajaxSuccess(data, status, xhr, $form);
        } catch (err) {
            //Do the same error stuff as the fail() call if it still fails
            var $e = $('<div class="ajax-error"</div>').text(err);
            $form.after($e);
        }
    }).fail(function(xhr, status, error) {
        $('.ajax-loader', $form).removeClass('is-active');
        var $e = $('<div class="ajax-error"></div>').text(error.message);
        $form.after($e);
});

I do not condone editing other developer's plugins, and this may not work for everyone who has this issue. This is just a temporary fix until we can find a different plugin that will play nice with CF7.

Edit:

Today, I came across this error again. Turns out that setting WP_DEBUG to false in your wp-config.php settings also resolves this error, as the stuff that gets prepended to the AJAX response is a bunch of debugging logs. Helpful if you're actually debugging it, but otherwise I'd keep it off on your production environments.

In the browser console the ajax call was not listed as an error. However there was an error inside the call. Thanks for @JAAulde for pointing me to that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM