0

I have a button that I'd like it to create an order :

<button id="" title="Create order" type="button" onclick="setLocation('<?php echo Mage::getUrl('ajax/index/createOrder') ?>')" >Create order</button>

This is the controller method, it's calling a function from the block :

public function createOrderAction()
    {
        $order = $this->getLayout()->getBlockSingleton('recentproducts/recentproducts')->createOrder();
        return $order;
    }

And the block is calling the business method from the model:

public function createOrder() {
    $order = Mage::getModel('recentproducts/recentproducts')->createOrder(); 
    return $order;
  }

All is working fine, the order is created, but I don't like when pressing the button to be redirected to another page. I want to click on the button, it stays on the actual page, it created the order, and it gives me a confirmation message .

1 Answer 1

2

You are looking to do an AJAX request with Javascript. Magento 1.9 still uses the prototype js framework, but if you include jQuery in your theme, you can also use this.

Change your button's onclick action from setLocation(url) to a custom function name, for example createOrder(url), and define this function in javascript:

<script>
function createOrder(url) {
    // Prototype Example
    // see more here http://api.prototypejs.org/ajax/Ajax/Request/
    new Ajax.Request(url, {
        parameters: {
            optionalParam1:optionalValue1,
            optionalParam2:optionalValue2,
            ...
        },
        onSuccess: function(response) {
            console.log(response);
            // do something with the response
        });
    });

    // jQuery example
    jQuery.ajax(url, {
        optionalParam1:optionalValue1,
        optionalParam2:optionalValue2,
        ...
    }, function(response) {
        console.log(response);
        // do something with the response
    });
}
</script>

In your controller file, use this method to send a message back to the user:

<?php
public function createOrderAction() {
    // do some stuff
    $msg = "My msg"
    $this->getResponse()->setBody($msg);
    return $this;
}

I personally prefer to use JSON strings as a response, for example {error:false,msg:"Congrats for your order"}, but that's up to you :)

1
  • I give you an upvote and an accept ! Great simple answer and it's working ! Thanks . Commented Dec 17, 2016 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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