GrumpyCrouton
GrumpyCrouton

Reputation: 8621

Ajax request is not sending data over POST

I've got the following Javascript function

http_post = function (url, data, success) {
    var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: success,
        fail: function(sender, message, details) {
            console.log(sender, message, details);
        }
    });
}

Which I am calling like this

$('#teammate_search_input').keyup(delay(function (e) {
    var value = $(this).val();

    http_post("{{ \Path::href('roster', 'search_name') }}", {name: value}, function(data) {
        console.log(data);
    });

}, 500));

Which is hitting this PHP script

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $download = $this->model('download');
    $results = $download->search_teammate($_POST['name']);
    echo json_encode(['term' => $_POST['name'], 'results' => $results]);
}   

Which is supposed to simply pull a list of users with a name that matches the input. This is all working fine (I get the response I am expecting), except the term is always set to null, so it returns a list of all users.

Result:

{term: null, results: Array(5)}

It appears as though the data is not being sent over the request.

Things I've tried:

Why is my data not being sent over the request?

Upvotes: 1

Views: 41

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Is your PHP endpoint configured to accept JSON? I don't believe this is the case by default (assuming you're not using a server-side library or framework).

You can instead send form-urlencoded data. To do that remove contentType: "application/json;charset=utf-8", and use data: data without calling JSON.stringify() on it, like this:

let http_post = function(url, data, success) {
  return $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "json",
    success: success,
    fail: function(sender, message, details) {
      console.log(sender, message, details);
    }
  });
}

Note that this makes your function almost entirely redundant, but I left it in anyway.

Upvotes: 1

Related Questions