Magento 2 - Add to cart not working after products loaded by ajaxTrying to run an AJAX script from the admin area in magentoCreating custom module in magento2 show fatal errorHow to use ajax to call a function in a controller in backend custom module?I created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Error calling model from controller in magento 2AJAX based “add to cart” for AJAX loaded products list?Magento ajax Add to cart Not workingMagento 2: Add a product to the cart programmaticallyMagento 2.3 Can't view module's front end page output?Magento 2.3 email attachment not working while sending custom email

Soft constraints and hard constraints

Linearize or approximate a square root constraint

Is it better to have a 10 year gap or a bad reference?

Find position equal columns of matrix

Why is the forgetful functor representable?

What does Windows' "Tuning up Application Start" do?

Conditional statement in a function for PS1 are not re-evalutated

Why does airflow separate from the wing during stall?

How can electronics on board JWST survive the low operating temperature while it's difficult to survive lunar nights?

Nilpotent elements of Lie algebra and unipotent groups

Do you need to have the original move to take a "Replaces:" move?

Three phase systems - are there any single phase devices that are connected between two phases instead of between one phase and neutral?

Where can I find standards for statistical acronyms and whether they should be capitalized or lower case?

Manager is asking me to eat breakfast from now on

How much did all the space agencies spent on rockets launching and space exploration? What are the benefits for me and you?

A Real World Example for Divide and Conquer Method

Why would word of Princess Leia's capture generate sympathy for the Rebellion in the Senate?

Could Europeans in Europe demand protection under UN Declaration on the Rights of Indigenous Peoples?

How to split the polynomial .

She told me that she HAS / HAD a gun

Is it ethical to tell my teaching assistant that I like him?

What would be the effects of (relatively) widespread precognition on the stock market?

Are there foods that astronauts are explicitly never allowed to eat?

How can I show that the speed of light in vacuum is the same in all reference frames?



Magento 2 - Add to cart not working after products loaded by ajax


Trying to run an AJAX script from the admin area in magentoCreating custom module in magento2 show fatal errorHow to use ajax to call a function in a controller in backend custom module?I created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Error calling model from controller in magento 2AJAX based “add to cart” for AJAX loaded products list?Magento ajax Add to cart Not workingMagento 2: Add a product to the cart programmaticallyMagento 2.3 Can't view module's front end page output?Magento 2.3 email attachment not working while sending custom email






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have loaded products collection using ajax. My controller URL is something like this:



www.example.com/whoboughtthisproduct/index/getproducts


Now products are loading properly, but when user click on add to cart button instead of add product to cart it is redirecting user to www.example.com/whoboughtthisproduct/index/getproducts



My controller code is this:



protected $resultPageFactory;

public function __construct(
Context $context,
MagentoFrameworkViewResultPageFactory $resultPageFactory
)

$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);



public function execute()

$viewBlock = $this->resultPageFactory->create();
$block = $viewBlock->getLayout()
->createBlock('VendorWhoBoughtThisProductBlockProductList')
->setTemplate('Magento_Catalog::product/list.phtml')
->toHtml();

//Setting response
$this->getResponse()->setBody($block);



And the code where I am calling ajax is this:



require([
'jquery'
], function($)
jQuery.ajax(
url: "/whoboughtthisproduct/index/getproducts",
type: "POST",
data: "prod=<?php echo $productId; ?>",
success: function (res)
if(res.indexOf("find products matching the selection") > -1)
//if no products found then do nothing
return;


var result = jQuery('.product-items', res).html();
jQuery(".bought-slider").html(result);

);
);









share|improve this question




























    2















    I have loaded products collection using ajax. My controller URL is something like this:



    www.example.com/whoboughtthisproduct/index/getproducts


    Now products are loading properly, but when user click on add to cart button instead of add product to cart it is redirecting user to www.example.com/whoboughtthisproduct/index/getproducts



    My controller code is this:



    protected $resultPageFactory;

    public function __construct(
    Context $context,
    MagentoFrameworkViewResultPageFactory $resultPageFactory
    )

    $this->resultPageFactory = $resultPageFactory;
    parent::__construct($context);



    public function execute()

    $viewBlock = $this->resultPageFactory->create();
    $block = $viewBlock->getLayout()
    ->createBlock('VendorWhoBoughtThisProductBlockProductList')
    ->setTemplate('Magento_Catalog::product/list.phtml')
    ->toHtml();

    //Setting response
    $this->getResponse()->setBody($block);



    And the code where I am calling ajax is this:



    require([
    'jquery'
    ], function($)
    jQuery.ajax(
    url: "/whoboughtthisproduct/index/getproducts",
    type: "POST",
    data: "prod=<?php echo $productId; ?>",
    success: function (res)
    if(res.indexOf("find products matching the selection") > -1)
    //if no products found then do nothing
    return;


    var result = jQuery('.product-items', res).html();
    jQuery(".bought-slider").html(result);

    );
    );









    share|improve this question
























      2












      2








      2








      I have loaded products collection using ajax. My controller URL is something like this:



      www.example.com/whoboughtthisproduct/index/getproducts


      Now products are loading properly, but when user click on add to cart button instead of add product to cart it is redirecting user to www.example.com/whoboughtthisproduct/index/getproducts



      My controller code is this:



      protected $resultPageFactory;

      public function __construct(
      Context $context,
      MagentoFrameworkViewResultPageFactory $resultPageFactory
      )

      $this->resultPageFactory = $resultPageFactory;
      parent::__construct($context);



      public function execute()

      $viewBlock = $this->resultPageFactory->create();
      $block = $viewBlock->getLayout()
      ->createBlock('VendorWhoBoughtThisProductBlockProductList')
      ->setTemplate('Magento_Catalog::product/list.phtml')
      ->toHtml();

      //Setting response
      $this->getResponse()->setBody($block);



      And the code where I am calling ajax is this:



      require([
      'jquery'
      ], function($)
      jQuery.ajax(
      url: "/whoboughtthisproduct/index/getproducts",
      type: "POST",
      data: "prod=<?php echo $productId; ?>",
      success: function (res)
      if(res.indexOf("find products matching the selection") > -1)
      //if no products found then do nothing
      return;


      var result = jQuery('.product-items', res).html();
      jQuery(".bought-slider").html(result);

      );
      );









      share|improve this question














      I have loaded products collection using ajax. My controller URL is something like this:



      www.example.com/whoboughtthisproduct/index/getproducts


      Now products are loading properly, but when user click on add to cart button instead of add product to cart it is redirecting user to www.example.com/whoboughtthisproduct/index/getproducts



      My controller code is this:



      protected $resultPageFactory;

      public function __construct(
      Context $context,
      MagentoFrameworkViewResultPageFactory $resultPageFactory
      )

      $this->resultPageFactory = $resultPageFactory;
      parent::__construct($context);



      public function execute()

      $viewBlock = $this->resultPageFactory->create();
      $block = $viewBlock->getLayout()
      ->createBlock('VendorWhoBoughtThisProductBlockProductList')
      ->setTemplate('Magento_Catalog::product/list.phtml')
      ->toHtml();

      //Setting response
      $this->getResponse()->setBody($block);



      And the code where I am calling ajax is this:



      require([
      'jquery'
      ], function($)
      jQuery.ajax(
      url: "/whoboughtthisproduct/index/getproducts",
      type: "POST",
      data: "prod=<?php echo $productId; ?>",
      success: function (res)
      if(res.indexOf("find products matching the selection") > -1)
      //if no products found then do nothing
      return;


      var result = jQuery('.product-items', res).html();
      jQuery(".bought-slider").html(result);

      );
      );






      magento2 addtocart ajax






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 12 at 9:59









      Muhammad HashamMuhammad Hasham

      5,53910 gold badges31 silver badges80 bronze badges




      5,53910 gold badges31 silver badges80 bronze badges




















          0






          active

          oldest

          votes














          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f281867%2fmagento-2-add-to-cart-not-working-after-products-loaded-by-ajax%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f281867%2fmagento-2-add-to-cart-not-working-after-products-loaded-by-ajax%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form