1

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);
    }
  • which url want to declare? – Rakesh Jesadiya Dec 26 '17 at 5:46
  • Do you want to do this by ajax? – Purushotam Sangroula Dec 26 '17 at 6:13
  • Thank you for your response, I have get the url using config – Jaisa Dec 26 '17 at 6:24
  • Please see the updated post – Jaisa Dec 26 '17 at 6:27
  • @Sri don't change the questions completely after someone has added the answer. You can add a new question instead of changing the whole question. – Dinesh Yadav Dec 26 '17 at 7:24
1

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.

| improve this answer | |
  • Thank you it works, but it is popup form after submitted form it is not reloading,, but failed to show response message inside popup – Jaisa Dec 26 '17 at 6:49
  • And after the ajax function i need to close popup modal – Jaisa Dec 26 '17 at 6:50
  • Okay, dont you see the alert(form_data)? Try to use network debugger to see the ajax requests and response. Make sure correct controller is being hit. Before you try to alert the response just simply alert some random string. – Purushotam Sangroula Dec 26 '17 at 6:57
  • Hi Anime, Thank you, after showing the response mesg I need to close the popup modal – Jaisa Dec 26 '17 at 8:55
  • But How do i close the popup after form submitted – Jaisa Dec 26 '17 at 8:57
5

You can use php in javascript variable.

<script>
var url = "<?php echo $block->getBaseUrl().'frontname/controller/action' ?>"; // use php in js variable.
</script>

OR you can add 'mage/url' in your script as given below

define([
   'jquery',
   'mage/url'
], function ($,url) { 

  var linkUrl = url.build('frontname/controller/action');
  console.log(linkUrl);
});

Reference

| improve this answer | |
  • Hello @Dinesh, for me second solution logged frontname/controller/action. I have seen this solution many times but never worked for me. I thought that it would prepend the baseurl with above string. – Purushotam Sangroula Dec 26 '17 at 6:45
  • you have to change these names as per your module. frontname=> your frontname defined in etc/frontend/routes.xml file. controller=> your controller name. action=> your controller's action name. – Dinesh Yadav Dec 26 '17 at 7:20
  • I know that, but I'm confused by the output linkUrl is it not supposed to be baseurl/frontname/controller/action?? – Purushotam Sangroula Dec 26 '17 at 7:23
  • @Sri don't change the questions completely after someone has added the answer. You can add a new question instead of changing the whole question. – Dinesh Yadav Dec 26 '17 at 7:24
-2

try this:

define([
   'jquery',
   'mage/url'
], function ($,url) { 
  var moduleURL = url.build('ar/controller-name/action-name');
  console.log(moduleURL);
});

OR

Use direct in phtml file

<script>
    var url = "<?php echo $block->getUrl('frontname/controller/action')?>";
</script>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.