• User

    [ASP] fly to basket con asp

    Ciao a tutti,
    devo modificare questo esempio di carrello della spesa integrandolo in una struttura in ASP.

    Il script originale è questo
    dhtmlgoodies.com/index.html?whichScript=fly-to-basket

    La pagina server-side nativa è in php, ho modificato sostituendo la mia nuova pagina in asp, dove in pratica estrae i dati del prodotto, ma non riesco a capire come richiamare il productID da passare appunto alla select per l'estrazione dei dati corretti.

    nella pagina con l'elenco dei prodotti ho inserito il link che aggiunge appunto il prodotto nel carrello in questo modo:

    <a href="#" onclick="addToBasket(<%=c%> );return false;"> mio prodotto</a>
    ```dove <%=c%> è l'idProdotto recuperato dinamicamente dal database.
    La pagina addProduct.asp (nella versione originale è addProduct.php) l'ho modificata così:
    
    

    if request("productId") <> "" then Set objRS = Server.CreateObject("ADODB.Recordset") strSQL = "SELECT * FROM " &strDbTable& "prodotti WHERE p_status=1 AND idProdotto = "&request("productId")&" ORDER BY p_nome;" objRS.Open strSQL, DFCon, 1, 1 If Not objRS.EOF Then While Not objRS.EOF codProdotto = objRS("p_codice") descProdotto = objRS("p_desc") prezzoProdotto = objRS("p_prezzo") objRS.MoveNext Wend End if strProdotto = codProdotto&"|||"&descProdotto&"|||"&prezzoProdotto end if

    
    Mentre il cuore dello script flytobasket.js è questo, riporto solo la parte di codice che richiama la funzione ajax addToBasket
    
    

    function addToBasket(productId) { if(!shopping_cart_div)shopping_cart_div = document.getElementById('shopping_cart'); if(!flyingDiv){ flyingDiv = document.createElement('DIV'); flyingDiv.style.position = 'absolute'; document.body.appendChild(flyingDiv); } shopping_cart_x = shoppingCart_getLeftPos(shopping_cart_div); shopping_cart_y = shoppingCart_getTopPos(shopping_cart_div); currentProductDiv = document.getElementById('slidingProduct' + productId); currentXPos = shoppingCart_getLeftPos(currentProductDiv); currentYPos = shoppingCart_getTopPos(currentProductDiv); diffX = shopping_cart_x - currentXPos; diffY = shopping_cart_y - currentYPos; var shoppingContentCopy = currentProductDiv.cloneNode(true); shoppingContentCopy.id=''; flyingDiv.innerHTML = ''; flyingDiv.style.left = currentXPos + 'px'; flyingDiv.style.top = currentYPos + 'px'; flyingDiv.appendChild(shoppingContentCopy); flyingDiv.style.display='block'; flyingDiv.style.width = currentProductDiv.offsetWidth + 'px'; flyToBasket(productId); } function flyToBasket(productId) { var maxDiff = Math.max(Math.abs(diffX),Math.abs(diffY)); var moveX = (diffX / maxDiff) * flyingSpeed;; var moveY = (diffY / maxDiff) * flyingSpeed; currentXPos = currentXPos + moveX; currentYPos = currentYPos + moveY; flyingDiv.style.left = Math.round(currentXPos) + 'px'; flyingDiv.style.top = Math.round(currentYPos) + 'px'; if(moveX>0 && currentXPos > shopping_cart_x){ flyingDiv.style.display='none'; } if(moveX<0 && currentXPos < shopping_cart_x){ flyingDiv.style.display='none'; } if(flyingDiv.style.display=='block')setTimeout('flyToBasket("' + productId + '")',10); else ajaxAddProduct(productId); }

    
    

    if(!isset($_POST['productId']))exit;
    switch($_POST['productId']){
    ...
    }

    Qualche consiglio?
    Grazie per l'aiuto :smile5:
    Elisa

  • Super User

    Ciao Elisa, credo che nello script js che hai postato manchi qualche parte importante, in ogni caso sei sicura che richiamando la pagina addProduct.asp con un productId valido questa funzioni? Prova a richiamarla così:

    addProduct.asp?productId=123

    sostituendo a 123 un id valido e vedi che ti dice!


  • User

    @cali1981 said:

    Ciao Elisa, credo che nello script js che hai postato manchi qualche parte importante, in ogni caso sei sicura che richiamando la pagina addProduct.asp con un productId valido questa funzioni? Prova a richiamarla così:

    addProduct.asp?productId=123

    sostituendo a 123 un id valido e vedi che ti dice!

    Ciao,
    innanzitutto grazie per l'aiuto 🙂
    Allora ho fatto la prova e mi sono accorta dei piccoli errori che infatti bloccavano il recupero productId, ho corretto e adesso l'inserimento onthefly avviene correttamente...ma... non effettua, come invece nello script originale, il calcolo del totale :mmm:

    Ho strutturato la pagina principale dove c'è il carrello in questo modo:

    
    <span>I Nostri Prodotti in vetrina</span></h2>
    <%
        RecordsPerPagina = 9
        page = Request("page")
        if page="" then page = 1
    
            Set objRS = Server.CreateObject("ADODB.Recordset")
            strSQL = "SELECT * FROM " &strDbTable& "prodotti WHERE p_promozione = 1 AND p_status = 1 ORDER BY p_codice;" 'estraggo i prodotti in promozione
            objRS.Open strSQL, DFCon, 1, 1
            TotalRecords = objRS.RecordCount
            If TotalRecords = 0 then 'nessun dato inserito
    %>
            <p>Nessun dato inserito</p>
    <%
            Else
                objRS.PageSize = RecordsPerPagina
                objRS.AbsolutePage = page
    '            c = 0
    %>
                <div id="products">
        <%
                For i = 1 to RecordsPerPagina
                    If Not objRS.EOF Then 
                    c=objRS("idProdotto")
    
    %>
    
                    <!-- DIV FOR A PRODUCT -->
                    <div class="product_container">
                      <div id="slidingProduct<%=c%>">
                            <table width="100%" border="0">
                              <tr>
                                <td><img src="images/img_1.jpg" alt="picture" width="182" height="127" class="floated" /></td>
                              </tr>
                              <tr>
                                <td> <p><%=objRS("p_nome")%><br /><span><%=objRS("p_desc")%></span></p></td>
                              </tr>
                            </table>
                      </div>
                        <a href="#" onclick="addToBasket(<%=c%>);return false;"><img src="images/acquista.gif" width="86" height="25" border="0" /></a>
                        <div class="clr"></div>
                    </div>
                    <!-- END DIV FOR A PRODUCT -->
        <%
                    objRS.MoveNext
                    End if 
                Next 
        %>
    
    ```Mentre poco dopo ho il carrello vero e proprio:
    
    
        <h2> Carrello</h2>
         <div id="shopping_cart">
            <table width="90%" border="0" id="shopping_cart_items">
                <tr>
                    <th>Pr.</th>
                    <th>Cod</th>
                    <th>?</th>
                    <th></th>
                </tr>
    

    <%
    if request("productId") <> "" then 'ho dovuto mettere un controllo altrimenti mi va in errore la select
    Set objRS = Server.CreateObject("ADODB.Recordset")
    strSQL = "SELECT * FROM " &strDbTable& "prodotti WHERE p_status=1 AND idProdotto = "&request("productId")&" ORDER BY p_nome;"
    objRS.Open strSQL, DFCon, 1, 1
    If Not objRS.EOF Then

            While Not objRS.EOF
    

    %>
    <tr id="shopping_cart_items_product<%=objRS("idProdotto")%>">
    <th><%=objRS("p_nome")%></th>
    <th><%=objRS("p_codice")%></th>
    <th>?<%=objRS("p_prezzo")%></th>
    <th></th>
    </tr>
    <%
    objRS.MoveNext
    Wend
    End if
    PuliziaRS(objRS)
    end if
    %>

               </table>
            <div id="shopping_cart_totalprice"></div>
        </div>
    

    function showAjaxBasketContent(ajaxIndex)
    {
    // Getting a reference to the shopping cart items table
    var itemBox = document.getElementById('shopping_cart_items');

    var productItems = ajaxObjects[ajaxIndex].response.split('|||');    // Breaking response from Ajax into tokens
    
    if(document.getElementById('shopping_cart_items_product' + productItems[0])){    // A product with this id is allready in the basket - just add number items
        var row = document.getElementById('shopping_cart_items_product' + productItems[0]);
        var items = row.cells[0].innerHTML /1;
        items = items + 1;
        row.cells[0].innerHTML = items;
    }else{    // Product isn't allready in the basket - add a new row
        var tr = itemBox.insertRow(-1);
        tr.id = 'shopping_cart_items_product' + productItems[0]
        
        var td = tr.insertCell(-1);
        td.innerHTML = '1';     // Number of items
        
        var td = tr.insertCell(-1);
        td.innerHTML = productItems[1];     // Description
        
        var td = tr.insertCell(-1);
        td.style.textAlign = 'right';
        td.innerHTML = productItems[2];     // Price    
        
        var td = tr.insertCell(-1);
        var a = document.createElement('A');
        td.appendChild(a);
        a.href = '#';
        a.onclick = function(){ removeProductFromBasket(productItems[0]); };
        var img = document.createElement('IMG');
        img.src = 'images/remove.gif';
        a.appendChild(img);
        //td.innerHTML = '<a href="#" onclick="removeProductFromBasket("' + productItems[0] + '");return false;"><img src="images/remove.gif"></a>';    
    } 
    
    
    updateTotalPrice();
    
    ajaxObjects[ajaxIndex] = false;        
    

    }

    function updateTotalPrice()
    {
    var itemBox = document.getElementById('shopping_cart_items');
    // Calculating total price and showing it below the table with basket items
    var totalPrice = 0;
    if(document.getElementById('shopping_cart_totalprice')){
    for(var no=1;no<itemBox.rows.length;no++){
    totalPrice = totalPrice + (itemBox.rows[no].cells[0].innerHTML.replace(/[^0-9]/g) * itemBox.rows[no].cells[2].innerHTML);

        }        
        document.getElementById('shopping_cart_totalprice').innerHTML = txt_totalPrice + totalPrice.toFixed(2);
        
    }    
    

    }

    
    Ho il dubbio di aver capito male come gestire la parte del carrello..nello script originale lo gestisce in questo modo:
    
    

    <div id="rightColumn">
    <!-- Shopping cart It's important that the id of this div is "shopping_cart" -->
    <div id="shopping_cart">
    <strong>Shopping cart</strong>
    <table id="shopping_cart_items">
    <tr>
    <th>Items</th>
    <th>Description</th>
    <th>Price</th>
    <th></th>
    </tr>
    <!-- Here, you can output existing basket items from your database
    One row for each item. The id of the TR tag should be shopping_cart_items_product + productId,
    example: shopping_cart_items_product1 for the id 1 -->

            </table>
            
            <div id="shopping_cart_totalprice"></div>
        </div>
    </div>
    
    Elisa

  • Super User

    Prova a cambiare th in td qui:

    <tr id="shopping_cart_items_product<%=objRS("idProdotto")%>">
    <th><%=objRS("p_nome")%></th>
    <th><%=objRS("p_codice")%></th>
    <th>€<%=objRS("p_prezzo")%></th>
    <th></th>
    </tr>


  • User

    @cali1981 said:

    Prova a cambiare th in td qui:

    <tr id="shopping_cart_items_product<%=objRS("idProdotto")%>">
    <th><%=objRS("p_nome")%></th>
    <th><%=objRS("p_codice")%></th>
    <th>?<%=objRS("p_prezzo")%></th>
    <th></th>
    </tr>

    no niente...il totale non viene calcolato... :mmm: altro suggerimento?


  • Super User

    Prova a usare un debugger javascript per vedere cosa succede nella funzione updateTotalPrice, oppure se è una pagina pubblica posta l'url che ci guardiamo...


  • User

    @cali1981 said:

    Prova a usare un debugger javascript per vedere cosa succede nella funzione updateTotalPrice, oppure se è una pagina pubblica posta l'url che ci guardiamo...

    ho pulito la pagina dalla grafica e ho messo le pagine su questo indirizzo
    eliven.net/fly-to-basket-asp/ :mmm:


  • Super User

    Ciao, devi fare qualche modifica al codice javascript, in particolare al posto di :

    totalPrice = totalPrice + (itemBox.rows[no].cells[0].innerHTML.replace(/[^0-9]/g) * itemBox.rows[no].cells[2].innerHTML);

    metti

    price = itemBox.rows[1].cells[2].innerHTML;
    price = replace('.','');
    price = replace(',','.');
    totalPrice = totalPrice + parseFloat(price)*itemBox.rows[1].cells[0].innerHTML;

    Considera che il codice va testato, ma il problema dovrebbe essere relativo al calcolo della somma e della molitplicazione nel prezzo.


  • User

    @cali1981 said:

    Ciao, devi fare qualche modifica al codice javascript, in particolare al posto di :

    totalPrice = totalPrice + (itemBox.rows[no].cells[0].innerHTML.replace(/[^0-9]/g) * itemBox.rows[no].cells[2].innerHTML);

    metti

    price = itemBox.rows[1].cells[2].innerHTML;
    price = replace('.','');
    price = replace(',','.');
    totalPrice = totalPrice + parseFloat(price)*itemBox.rows[1].cells[0].innerHTML;

    Considera che il codice va testato, ma il problema dovrebbe essere relativo al calcolo della somma e della molitplicazione nel prezzo.

    Ciao,
    ho provato ad apportare la modifica, ma adesso non mostra il totale e ricevo questo errore:

    replace is not defined

    che corrisponde a questa riga:

    
    price = replace('.','');
    ```:?

  • Super User

    scusa, deve essere price = price.replace....


  • User

    @cali1981 said:

    scusa, deve essere price = price.replace....

    figurati grazie 🙂
    adesso recupera il totale, ma la somma è sbagliata...:? ovvero se provo ad aggiungere altri prodotti uguali o diversi non calcola correttamente :arrabbiato:


  • Super User

    Metti online sullo stesso sito il codice aggiornato e vediamo...


  • User

    @cali1981 said:

    Metti online sullo stesso sito il codice aggiornato e vediamo...

    fatto 🙂
    eliven.net/fly-to-basket-asp/


  • Super User

    Il codice è sbagliato, quello sopra era di prova, quello corretto è:

    price = itemBox.rows[no].cells[2].innerHTML;
    price = price.replace('.','');
    price = price.replace(',','.');
    totalPrice = totalPrice + parseFloat(price)*itemBox.rows[no].cells[0].innerHTML;


  • User

    @cali1981 said:

    Il codice è sbagliato, quello sopra era di prova, quello corretto è:

    price = itemBox.rows[no].cells[2].innerHTML;
    price = price.replace('.','');
    price = price.replace(',','.');
    totalPrice = totalPrice + parseFloat(price)*itemBox.rows[no].cells[0].innerHTML;

    ah..ok adesso calcola correttamente 😄
    ultima cosa..che non ne capisco il motivo..quando clicco sull'icona per la cancellazione del prodotto da carrello la pagina si sposta all'inzio :mmm:
    ho aggiunto del margine in alto per farti vedere l'effetto..come mai fa così?


  • Super User

    Quello è un problema del link con #, cerca in giro si trovano varie soluzioni.


  • User

    @cali1981 said:

    Quello è un problema del link con #, cerca in giro si trovano varie soluzioni.

    ok grazie mille ancora per il tuo aiuto 🙂