Define URL in JS and Load Ajax in Magento 2

jquerymagento2.2url

I have get all the form data after the form submit, I have submitted the form data, but it is failed to load as ajax, after submitted it reloads the page. Ajax is not working, How to overcome this issue

  return function (config) {
                $('#review-form').on("click", "#review-submit", function () {

                    var form_data = $("#review-form").serialize();
                    var reviewurl = config.url;
                    $.ajax({
                        url: reviewurl,
                        type: 'POST',
                        // Pass the submitted form data to Controller
                        data: form_data,
                        success: function (response) {
                            alert(form_data);
                            var returnedData = JSON.parse(response);
                            if (returnedData.status == 'success')
                                $("#success").html(returnedData.messages);
                            else
                                $("#error").html(returnedData.messages);
                        },
                        error: function (response) {
                            alert("failed");
                            var returnedData = JSON.parse(response);
                            $("#error").html(returnedData.messages);
                        }
                    });
                });
            };

Contoller

public function execute()
    {

        $message = null;
        $status = null;
        if (!$this->formKeyValidator->validate($this->getRequest())) {
            $message = "Invalid form key";
            $status = 'failed';
        } else {
            //get the form data
            $data = $this->reviewSession->getFormData(true);
            if ($data) {
                $rating = [];
                if (isset($data['ratings']) && is_array($data['ratings'])) {
                    $rating = $data['ratings'];
                }
            } else {
                $data = $this->getRequest()->getPostValue();
                $rating = $this->getRequest()->getParam('ratings', []);
            }
            if (($product = $this->initProduct()) && !empty($data)) {
                /** @var \Magento\Review\Model\Review $review */
                $review = $this->reviewFactory->create()->setData($data);

                $review->unsetData('review_id');

                $validate = $review->validate();
                if ($validate === true) {
                    try {
                        $review->setEntityId($review->getEntityIdByCode(Review::ENTITY_PRODUCT_CODE))
                                ->setEntityPkValue($product->getId())
                                ->setStatusId(Review::STATUS_PENDING)
                                ->setCustomerId($this->customerSession->getCustomerId())
                                ->setStoreId($this->storeManager->getStore()->getId())
                                ->setStores([$this->storeManager->getStore()->getId()])
                                ->save();
                        foreach ($rating as $ratingId => $optionId) {
                            $this->ratingFactory->create()
                                    ->setRatingId($ratingId)
                                    ->setReviewId($review->getId())
                                    ->setCustomerId($this->customerSession->getCustomerId())
                                    ->addOptionVote($optionId, $product->getId());
                        }
                        $review->aggregate();
                        $message = __('You submitted your review for moderation.');
                        $status = 'success';
                    } catch (\Exception $e) {
                        $this->reviewSession->setFormData($data);
                        $message = __('We can\'t post your review right now.');
                        $status = 'failed';
                    }
                } else {
                    $this->reviewSession->setFormData($data);
                    if (is_array($validate)) {
                        foreach ($validate as $errorMessage) {
                            $message = $errorMessage;
                        }
                    } else {
                        $message = __('We can\'t post your review right now.');
                    }
                    $status = 'failed';
                }
            }
        }
        $result['messages'] = $message;
        $result['status'] = $status;
        echo json_encode($result);
    }

Best Answer

That might be because you forgot to return false which is equivalent to e.preventDefault. Try this code.

  return function (config) {
                $('#review-form').on("click", "#review-submit", function () {

                    var form_data = $("#review-form").serialize();
                    var reviewurl = config.url;
                    $.ajax({
                        url: reviewurl,
                        type: 'POST',
                        // Pass the submitted form data to Controller
                        data: form_data,
                        success: function (response) {
                            alert(form_data);
                            var returnedData = JSON.parse(response);
                            if (returnedData.status == 'success')
                                $("#success").html(returnedData.messages);
                            else
                                $("#error").html(returnedData.messages);
                        },
                        error: function (response) {
                            alert("failed");
                            var returnedData = JSON.parse(response);
                            $("#error").html(returnedData.messages);
                        }
                    });
                    return false;
                });
            };

I hope this works.

Related Topic