2017-01-19 5 views
2

Je suis en train de remplacer "Hello world!" avec "Bonjour à vous aussi" en utilisant un ajax replaceWith. Cependant, je reçois cette erreur:Impossible de lire la propriété 'replaceWith' de l'appel null-ajax

Cannot read property 'replaceWith' of null

Où est-ce que je prends le mauvais tournant?

REMARQUE: l'appel ajax fonctionne avec alerte (réponse);

index.phtml:

<div id="helloworld">Hello world!</div> 

<script type="text/javascript"> 
    jQuery.ajax({ 
     url: "<?php echo $this->getUrl('topperproductqa/index/ajax') ?>", 
     success: function(response){ 
      $('#helloworld').replaceWith(response); 
      //alert(response); 
     } 
    }); 
</script> 

IndexController.php:

class Topper_ProductQA_IndexController extends Mage_Core_Controller_Front_Action 
{ 
    public function indexAction() 
    { 
     $this->loadLayout(); 
     $this->renderLayout(); 

     return $this; 
    } 

    public function ajaxAction() 
    { 
     $response = "Hello to you too"; 

     $json = json_encode($response); 
     $this->getResponse()->setHeader('Content-type', 'application/json'); 
     $this->getResponse()->setBody($json); 
    } 
} 
+1

Qu'est-ce que vous avez bien fonctionne: https://jsfiddle.net/dn892efr/. Êtes-vous sûr que c'est ce code qui cause le problème? –

+1

essayez ceci pour voir si vous obtenez réellement l'élément ou pas .... il peut être jquery library issues'console.log ($ ('# helloworld')); ' – lakshay

+0

Merci! Cela m'a fait regarder plus loin que le code et j'ai compris que c'était dû au "prototype" de magento qui utilise "$". –

Répondre

1

j'ai compris Magento utilise $ sur prototype.js, je l'ai fixé avec:

(function($) { 

    $.ajax({ 
     url: "<?php echo $this->getUrl('topperproductqa/index/ajax') ?>", 
     dataType: "json", 
     success: function(response){ 
      $("#helloworld").replaceWith(response); 
      //alert(response); 
     } 
    }); 

})(jQuery);