2013-05-06 4 views
-1

다음 함수는 ajax 호출을 작성하지만 몇 가지 문제가 있습니다. 먼저, 아약스 전화를해야합니까? 유일한 PHP 값은 $ product_id입니다. 응용 프로그램은 이전에 ajax 호출을 수행하여 색상을 선택한 후에 사용할 수있는 제품으로 페이지를 채 웁니다. 두 번째로, 버튼 요소는 계속 잘못된 번호를 할당받습니다! 마지막으로 이와 같은 클릭 기능을 할당해도 효과가 있습니까? 어떤 제안도 감사합니다.Jquery ajax 호출 ID 값이 올바르지 않음

JQuery와 :

function addToCartBlock(value) 
    { 
    console.log ('the function value is ' + value); 
    var product_id = <?= $product_id ?>; 
     $j.ajax({ 
      type: "POST", 
      url: "/ajax_calls/addToCartBlock.php", 
      data: { 'value': value, 'product_id': product_id} 
      }).done(function(data) { 
       $j('.vendorListItem'+value).append('<span class="add-to-cart" id="add-to-cart'+ value+'"></span>'); 
       $j('.vendorListItem'+value).css({'display':'inline'}); 
       $j('#add-to-cart' + value).append('<label for="qty">Qty:</label>'); 
       $j('#add-to-cart' + value).append('<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />'); 
       $j('#add-to-cart' + value).append('<button type="button" title="" class="button btn-cart" id="' + value + '"><span>Add To Cart</span></button>'); 

       $j($j('button').attr('id',value)).on('click',function() 
       { 
        console.log('The onclick value is ' + $j('button').attr('id'));//this logs a random number btwn 1-3, last add to cart button logs once the others multiple times 
        //take value of list item 
        $j('#attribute136 option[value=' + $j('button').attr('id') + ']').attr('selected', 'selected').ready(function() {;//make the applicable selection 
        $j('#attribute136').val($j('button').attr('id')); 

        console.log($j('#attribute136').val()); //this keeps logging '3' 
        //CAITLIN not all buttons have an ID of the correct value though the prior span class seems to... console.log through the program to debug 

        //initiate add to cart function 
        productAddToCartForm.submit(this); 
        }); 
       }); 
      }); 
    } 

PHP 스크립트의 addtocart.php :

<?php 

require_once('/var/www/Staging/public_html/app/Mage.php'); 
umask(0); 
Mage::app(); 

//ensure that the value is legitimate 
if($_POST && is_numeric($_POST['value'])){ 
    $value = $_POST['value']; 
} 

//pass this in your ajax call for the add button 
if($_POST && is_numeric($_POST['product_id'])){ 
    $product_id = $_POST['product_id']; 
} 

$helper = Mage::helper('core'); //for translation 
$block = new Mage_Catalog_Block_Product_View(); // not best practice, but neither are standalones 
$product = Mage::getModel('catalog/product')->load($product_id); // no need to use the _ here, it's not protected/private; additonally Mage::registry won't work because you're technically not on a product detail page 

$buttonTitle = ''; //you are using this, but it isn't set 

$resultsArray= []; 
$resultsArray['Qty'] = $helper->__('Qty:'); 
$resultsArray['Qtyno'] = $helper->__('Qty'); 
$resultsArray['DefaultQty'] = $block->getProductDefaultQty($product); 
$resultsArray['windowLocation'] = Mage::helper('checkout/cart')->getAddUrl($product); 
$resultsArray['value']=$value; 
echo json_encode($resultsArray); 

?> 

편집 !!!! AJAX 호출 대신 아래 함수를 사용합니다. 이 코드를 가지고있는 유일한 문제는 ID가 3 인 버튼이 선택되면 장바구니에만 추가된다는 것입니다. 해당 id 값 제품을 장바구니에 추가하려면 모든 단추가 필요합니다. 당신이 동적으로 추가 버튼 클릭 이벤트 문제를 해결하는 데 도움이 될 것입니다 코드에 따라

function addToCartBlock(value) 
    { 
    console.log ('the addToCartBlock function value is ' + value); 
    //var product_id = <?= $product_id ?>; 

       $j('.vendorListItem'+value).append('<span class="add-to-cart" id="add-to-cart'+ value+'"></span>'); 
       $j('.vendorListItem'+value).css({'display':'inline'}); 
       $j('#add-to-cart' + value).append('<label for="qty">Qty:</label>'); 
       $j('#add-to-cart' + value).append('<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />'); 
       $j('#add-to-cart' + value).append('<button type="button" onclick="selectAndAddToCart('+value+')" title="" class="button btn-cart" id="' + value + '"><span>Add To Cart</span></button>'); 
    } 

function selectAndAddToCart(value) 
{ 
    console.log('The selectAndAddToCart onclick value is ' + value); 
    $j('#attribute136 option[value=' + value + ']').attr('selected', 'selected').ready(function() {;//make the applicable selection 
     $j('#attribute136').val(value); 

     console.log('Selection made.');  
     console.log($j('#attribute136').val()); //this keeps logging '3' 

     //initiate add to cart function 
     productAddToCartForm.submit(this); 
    }); 
} 
+0

그들은 항상 클릭 한 것과 관계없이 * "잘못된 번호"*를 가져 옵니까? –

+0

이것은'$ j ('button'). attr ('id', value)'를 기대하지 않습니다. 전체 페이지의 모든 버튼의 id를'value'로 설정합니다. –

+0

아, 와우 예, 그게 하나의 문제입니다! 감사. 코드를 "편집!"아래로 업데이트 한 내용을 확인하십시오. 굵게. 이제 selectAndAddToCart 함수에 문제가 있습니다. 이 함수를 로깅하면 올바른 값이 기록되지만 console.log ($ j ('# attribute136'). val()); '3'만 기록합니다. – CaitlinHavener

답변

1

, 내가 값을 반환하지 않았기 때문에 AJAX 기능을 사용하지 않았다

$j(document).on("click","#" + value, function() { 
    alert('test'); 
}); 
+0

약 1 분 후에 위 코드를 변경했습니다. – CaitlinHavener

+0

고마워요! \t $ j ('# attribute136 옵션 [값 ='+ 값 + ']'). attr ('selected', 'selected') 적용 가능한 선택 항목을 만드시겠습니까? – CaitlinHavener

+0

예. 선택합니다. 하지만 코드에서 잘못된 방식으로 사용했습니다. 준비 이벤트가 없습니다 –

0

. PHP 변수를 자바 스크립트에서 사용하는 것만으로 일정했습니다. 모든 제안에 감사드립니다. 나는 여전히 selectAndAddToCart 함수로 문제가 있지만 질문을 분리하기 위해 다시 게시 할 것입니다.