Dennis Dennis - 1 month ago 7
jQuery Question

How to update multiple HTML form fields with a single AJAX call?

I have:

<tr>
<td>Product</td>
<!-- line below generates a select box with id="product" -->
<td id="product"><?=$this->formSelect($form->get('product'));?></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="Description" id="Description" /></td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="Quantity" id="Quantity" /></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="Price" id="Price" /></td>
</tr>


Question

When using
onupdate
feature of jQuery, that is tied to event of changing value of "product" select box, how do I update Description, Quantity and Price fields.

What I have now is this:

$("#product").change(function() {
$.ajax({
type : "POST",
url : "updatedescription.php",
data : 'product_id=' + $(this).val(),
cache : false,
success : function(html) {
$("#Description").html(html);
}
});

return false;
});


But it updates Description only.

PHP Code

function loadDescriptionByProduct()
{
$product = filter_var($_POST['product_id'], FILTER_SANITIZE_STRING);
$description = $this->repository->getDescriptionByProduct($product);
echo $description;
}

function getDescriptionByProduct(string $product)
{
$sql = "SELECT description FROM product where product=?";
$result = db_param_query($sql, $product);
$row = db_fetch_array($result);
$description = $row['description'];
return $description;
}

Answer

You need to call a single resource like getProductDetails.php and get there all the information related to the product you want.

PHP

function getProductDetails(string $product)
{
    $sql = "SELECT price, description FROM product where product=?";
    $result = db_param_query($sql, $product);
    $row = db_fetch_array($result);

    $response = array(
        'price' => $row['price'],
        'desc' => $row['description']
    );

    return json_encode($response); //return a json response.
}

Javascript

$("#product").change(function() {
    $.ajax({
        type : "POST",
        url : "getProductDetails.php",
        data : 'product_id=' + $(this).val(),
        cache : false,
        success : function(response) {
            var parsedResponse = $.parseJSON(response);

            $("#Description").html(parsedResponse.desc);
            // ...
            $("#Price").html(parsedResponse.price);
        }
    });

    return false;
});

Also, you can use Content-Type: application/json response header and indicate to jQuery that this is JSON by using the dataType: 'json' parameter. (and remove $.parseJSON())