Hama Bohel
Hama Bohel

Reputation: 105

php json_encode response sends back html to ajax jquery request instead json

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

Upvotes: 1

Views: 1758

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

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

Upvotes: 1

Related Questions