1

Hello i got a question about jQuery ajax post request in ZendFramework here is my jquery:

$("input[type=image].addToCartButton").click(function() {
    var productId = $(this).attr("id");

    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: "http://localhost/ZendProjects/essence/essenceZP/public/order",
        data: {
            id: productId
        },
        success: function(data){
            alert(data);
        }
    });

});

and here is my code in ZendFramework Order Controller:

    $request = $this->getRequest();
    if($request->isXmlHttpRequest()) {
        $this->_helper->layout()->disableLayout();
        $test = 'testing ajax content';
        $this->view->test = $test;
    } else {
        $test = 'testing non-ajax content';
        $this->view->test = $test;
    }

in firebug console i get an error but cant see where is the error because it shows for 0.5 sec and hide.. any ideas? The idea is when you click the button to send productId to the order controller and put it in session array, but for now only testing the ajax request..

markup:

    <form action="" method="post">
        <label for=".productQuantity" style="float: left;margin-top:7px;margin-left: 5px">Количество</label>
        <input class="productQuantity" name="productQuantity" type="number" value="1" min="1" max="1000" style="width: 50px;float: left;margin-left: 7px" />
        <input type="image" id="<?php echo $product->id; ?>" name="<?php echo $this->url(array('controller' => 'order', 'action' => 'add-to-cart'), 'default', true) ?>" src="<?php echo $this->baseUrl('images/cartPut.png'); ?>" style="margin-left: 13px;" />
    </form>
fre2ak
  • 329
  • 2
  • 8
  • 18

1 Answers1

1

What's happening is that when you click on the submit button the ajax call is triggered at the same time the form is submitted.

You may be wondering why the form is being submitted if there's no action="".

The thing is, when the action attribute is blank it assumes that it's on the same page. I mean, if you're on localhost/index.php than action="" = action="localhost/index.php"

So, you must disable the form submit by adding action="javascript:void(0)".

You can also use jQuery for this:

cancel a submit in jquery?

Or even plain javascript (return false to the submit event)

Community
  • 1
  • 1
Keyne Viana
  • 6,194
  • 2
  • 24
  • 55