user2189190
user2189190

Reputation: 179

Send $_POST array using ajax with PHP?

I have multiple input fields with the name Change[xxx]. The original way is when an update button is clicked, it normally sends the data and updates the database. But how do I pass this Change[xxx] data if I use Ajax? I want to do this without jQuery.

The HTML:

<input type='text' name='Change[name]' value='Bob' onblur='updateField($id)'></input>

Retrieving the info in PHP:

foreach($_POST['Change'] as $field => $value) {
    if($field == 'name') {
        // update database
    }
}

The JavaScript:

Using request.send(...), this is where I'm not sure how to send the data.

function updateField(id) {
    …
    var url = 'orders.php?id='+ id;
    request.open('POST', url, true);
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    var val = document.getElementsByName("Change[name]")[0].value;
    request.send("id=" + id + "&Change[" + val + "]"); 
    …
}

Upvotes: 0

Views: 76

Answers (1)

Ry-
Ry-

Reputation: 224857

Exactly the same as you usually would:

request.send("id=" + id + "&Change[name]=" + encodeURIComponent(val));

The brackets aren’t special to HTTP, only to PHP.

Upvotes: 1

Related Questions