Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest Post Data not being sent

This is the javascript:

function eAC(emailData) {
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    }

    if (!httpRequest) {
        return false;
    }

    console.log(emailData);

    var fd = new FormData();
    fd.append("email", emailData);

    httpRequest.onreadystatechange = eAC_callback; 
    httpRequest.open('POST', "http://website.com/file.php");
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send(fd);
}

function eAC_callback() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var response = JSON.parse(httpRequest.responseText);
                console.log(response);
        } else {
            return false;
        }
    }
};

This is the php:

$pec_result = array();

if(isset($_POST['email']) && strlen($_POST['email']) > 0){
    $pec_result['error'] = 'Its good';
    echo json_encode($pec_result);
    die();
} else {
    $pec_result['error'] = $_POST['email'];
    echo json_encode($pec_result);
    die();
}

The problem here is that $_POST['email'] has a value of NULL. Why is $_POST['email'] null when console.log() for emailData returns a value. Can anyone help? I think the prob is in the appending part. (Not sure)

Please no jQuery. I know how to do this in jQuery but I want to learn how to do this in javascript. So yeah thanks

like image 451
Jo E. Avatar asked Jan 17 '14 08:01

Jo E.


1 Answers

Your problem is that with FormData the request is sent as multipart/form-data not application/x-www-form-urlencoded. Remove the line where you set the content type. The correct content type will be set automatically when you pass a FormData object to XMLHttpRequest.send.

like image 94
Musa Avatar answered Oct 13 '22 09:10

Musa