1

for a simple contact form as wordpress plugin, i've created a form as a popup in same page:

<form method="post" id="w_form" enctype="multipart/form-data">

    <label for="first_name" class="text-secondary">First Name</label>
    <input id="first_name" type="text" name="first_name"  form-control" value="" required="">

    <label for="last_name" class="text-secondary">Last Name</label>
    <input id="last_name" type="text" name="last_name" form-control" value="" required="">


    <button class="btn btn-danger" id="submit" type="submit" value="Submit" name="submit">
        Submit
    </button>

</form>

and its data will send to backend by ajax:

$("#w_form").submit( function(event) {

    event.preventDefault();

    $.ajax({

        type: "post",
        data: new FormData(this),
        dataType: 'json',
        contentType: false,
        cache: false,
        processData: false,
        beforeSend: function() {

            $('#submit').attr("disabled", "disabled");

        },
        success: function( response ) {

           alert( response );

           // if ( response.status == 1 ) {

           //    $('#w_form')[0].reset();

           // }


        },
        error: function (xhr, error) {

            console.debug(xhr);

            console.debug(error);

        },

    });

});

that passes to php code in the same page and the top of the form:

if ( isset( $_POST['first_name'] ) ) {

    $uploaded_status;

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];

    $to = '[email protected]';
    $subject = 'test';
    $body = 'body';


    if ( wp_mail( $to, $subject, $body, '') ) {

        $uploaded_status = 1;

    } else {

        $uploaded_status = 0;

    }

    if ( $uploaded_status == 1 ) {

        $response = array();

        $response['status']  = 1;

        $response['message'] = 'Your form submitted successfully!';

        header("Content-Type: application/json; charset=utf-8", true);

        echo json_encode($response);

    }

}

this process works correctly and sends form's data by email to email address, but the response data as :success part of ajax, gets html content instead json and returns parsererror as console.debug(error);

so as i mentioned, the submission and sending data as email, works correctly but i have no correct data for the respond process to control UI after submitted button

2
  • to clarify: You send the ajax request to the same page and receive HTML output as part of the response - thus invalidating json response data? Commented Mar 30, 2020 at 12:45
  • @RamRaider yes, i send form data as ajax to backend and it uses that data to send email, it works correct so far, but after success passing ajax, it couldnt get response as json so hasnt correct data Commented Mar 30, 2020 at 14:08

1 Answer 1

1

If you are receiving invalid JSON data in response to an Ajax request sent to the same page you need to discard any output buffer prior to sending the response and then terminate processing immediately afterwards to prevent any further content being appended to the response stream.

if( $_SERVER['REQUEST_METHOD']=='POST' &&  isset( $_POST['first_name'],$_POST['last_name'] ){

    ob_clean();# discard any previous buffer data

    $uploaded_status;

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];

    $to = '[email protected]';
    $subject = 'test';
    $body = 'body';


    if ( wp_mail( $to, $subject, $body, '') ) {
        $uploaded_status = 1;
    } else {
        $uploaded_status = 0;
    }

    if ( $uploaded_status == 1 ) {
        $response = array();
        $response['status']  = 1;
        $response['message'] = 'Your form submitted successfully!';


        header("Content-Type: application/json; charset=utf-8", true);
        exit( json_encode( $response ) );#terminate
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

what can you observe in the console when you receive the ajax response?
i used ``` error: function (xhr, error) { console.debug(xhr); console.debug(error); }, ``` to check error that fires parsererror
when i remove dataType: 'json', in jquery section, wont have error although we set json_encode( $response ) as php output, the ajax response is an html without $response
i think the main point is pass data from php to jquey. php does main duty correctly (sending email), but to pass $respone we have problem, so in this step there isnt any output
i guess since the first output of php is sending email as html, althought i pass json_encode after that, ajax gets html as responce
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.