¿Cómo puedo actualizar más de un área en una página con una llamada jquery ajax?

Actualmente estoy implementando un carrito de compras usando jQuery, Ajax y PHP y la mayor parte está funcionando. Sin embargo, actualmente estoy atascado en cómo actualizar el contenido de la página principal del carrito de compras cuando actualizo el carrito, ya que en este momento mi html devuelto actualiza el área del carrito de compras en la barra lateral (eso funciona bien).

Entonces, mi pregunta es ¿cómo actualizo también la tabla que muestra todos los elementos del carrito de compras en el área de contenido principal del sitio al mismo tiempo?

Mi jQuery (para actualizar el carrito):

$('.update_cart').submit(function (e) {
    e.preventDefault();

    $.ajax({
        cache: false,
        url: 'inc/shopping_bag.php',
        data: $(this).serialize() + '&action=update',
        type: 'POST',
        success: function(html) {
            $('#shopping-bag p').html(html);
        }
    });
});

Mi PHP para actualizar:

elseif (!empty($action) && $action == 'update') {

if (is_array($_POST['item_qty'])) {
    foreach ($_POST['item_qty'] as $key=>$quantity) {
        $quantity=ceil($quantity);
        if ($quantity==0) {
            unset($_SESSION['basket'][$key]);
        } else {
            $_SESSION['basket'][$key]['item_qty']=$quantity;
        }
    }
}

update_basket();
}
function update_basket() {
foreach ($_SESSION['basket'] as $array)
{
    $totalItems+=$array['item_qty'];

    $cost=$array['item_qty']*$array['unit_price'];
    $total+=$cost;
}
echo 'Shopping Bag<br>'.$totalItems.' Items<br />&pound;'.sprintf("%01.2f", $total);
}

La página de mi carrito de compras (lo siento un poco larga):

<div id="content">
    <section>
        <div class="content-seperator">
            <h1>Shopping Bag</h1>
                </div>
                <div id="inner-content">
                    <section>
                        <?php if (count($_SESSION['basket']) > 0) { ?>
                            <form action="#" class="update_cart">
                                <table id="cart">
                                    <thead>
                                        <tr>
                                            <th width="60">Quantity</th>
                                            <th>Item</th>
                                            <th width="70">Unit Price</th>
                                            <th width="60">Total</th>
                                            <th class="blank" width="90">&nbsp;</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php

                                            $total=0;
                                            $count=0;

                                            foreach ($_SESSION['basket'] as $array)
                                            {

                                                $check_id = substr($array['item_id'], 0, 5);

                                                $cost=sprintf("%01.2f", $array['item_qty']*$array['unit_price']);
                                                $total+=$cost;

                                                if (!empty($array['image'])) {
                                                    if (file_exists($array['image'])) {
                                                        $image_path = $array['image'];
                                                    } else {
                                                        $image_path = '<img src="images/missing.gif" alt="missing image" />';
                                                    }
                                                } else {
                                                    $image_path = '<img src="images/missing.gif" alt="missing image" />';
                                                }
                                                $image =    getImagesize($image_path);
                                                $dimensions = imgResize($image[0], $image[1], 80);

                                                if ($check_id=='parts') {
                                                ?>
                                                <tr>
                                                    <td class="align-centre">
                                                        <input name="item_qty[<?php echo $count; ?>]" type="text" size="1" value="<?php echo $array['item_qty']; ?>" class="formfield align-centre" />
                                                        <input name="unit_price[<?php echo $count; ?>]" type="hidden" value="<?php echo $array['unit_price']; ?>" />
                                                    </td>
                                                  <td>
                                                    <span class="basket_img"><img src="<?php echo $image_path; ?>" <?php echo $dimensions; ?> alt="Diesel Injector Image" /></span>
                                                    <strong><?php echo $array['category']; ?> Injector</strong><br />
                                                    <span class="basketlabel">Part No:</span> <strong><?php echo $array['item_name']; ?></strong>
                                                  </td>
                                                  <td>&pound;<?php echo str_replace("£ ","",$array['unit_price']); ?></td>
                                                  <td><strong>&pound;<?php echo $cost; ?></strong></td>
                                                  <td><a href="?removeItem=<?php echo $array['item_id']; ?>" class="basket_remove">Remove Item</a></td>
                                                 </tr>
                                            <?php 
                                                 } if ($check_id=='prods') { ?>
                                                 <tr>
                                                    <td class="align-centre">
                                                    <input name="item_qty[<?php echo $count; ?>]" type="text" size="1" value="<?php echo $array['item_qty']; ?>" class="formfield align-centre" />
                                                    <input name="unit_price[<?php echo $count; ?>]" type="hidden" value="<?php echo $array['unit_price']; ?>" />
                                                  </td>
                                                  <td>
                                                    <span class="basket_img"><img src="<?php echo $image_path; ?>" <?php echo $dimensions; ?> alt="Diesel Product Image" /></span>
                                                    <strong><?php echo $array['category']; ?></strong><br />
                                                        Product Code: <strong><?php echo $array['item_name']; ?></strong>
                                                    </td>
                                                  <td>&pound;<?php echo sprintf("%01.2f", $array['unit_price']); ?></td>
                                                  <td><strong>&pound;<?php echo $cost; ?></strong></td>
                                                  <td><a href="?removeItem=<?php echo $array['item_id']; ?>" class="basket_remove">Remove Item</a></td>
                                                 </tr>
                                                 <?php } 
                                                    $count++; 
                                                 } ?>   
                                            </tbody>
                                        </table>
                                        <input type="submit" name="update_cart" value="Update Shopping Bag" class="rounded-buttons" />
                                        <input type="button" name="empty_cart" value="Empty Shopping Bag" class="rounded-buttons" />
                                </form>     
                            <?php } else { ?>
                                <p class="no_items">You have no items in your shopping bag</p>
                            <?php } ?>
                    </section>
                </div>

Cualquier ayuda muy apreciada, gracias.

preguntado el 10 de marzo de 12 a las 09:03

¿Qué quieres hacer exactamente en la tabla? ocultar esa fila o marcarla como ya agregada? da mas detalles -

Lo siento, tienes razón, debería haber sido más específico. Lo que quiero hacer es actualizar la cantidad y el precio de cada producto en la pestaña si se cambian las cantidades y se hace clic en 'Actualizar bolsa' o eliminar la fila de la tabla si se elimina el artículo. Mi problema no es hacer esto como tal, sino cómo hacerlo y actualizar el div del carrito de compras en la barra lateral también. -

Use JSON como respuesta en lugar de HTML. Entonces tendrías algo como: response = [{ product: 'a', price: 1 },{ product: 'b', price: 2 },...], para que puedas reutilizarlo. -

2 Respuestas

Solo actualiza tu success función:

success: function(html) {
    $('#shopping-bag p').html(html);
    // update / add to your table here
    $updatehere = $('#tableid #idortd');
    $updatehere.text(parseInt($updatehere.text())++);
}

Arriba hay un ejemplo de cómo incrementar un valor en un ` por uno. podrías reemplazar esto agregando una fila

respondido 10 mar '12, 11:03

Todo bien ahora, finalmente encontré cómo recargar el div que contiene la tabla del carrito de compras. He puesto todo el contenido dentro del div de contenido interno en un archivo separado, lo incluyo normalmente y uso

$("#inner-content").load(location.href + " #inner-content>*", "");

Para recargar en la actualización.

respondido 11 mar '12, 08:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.