0

I am getting a strange redirection after content load successful and I can't find what is causing this behavior so I ask for some help or tips around this problem. See this is the jQuery code I'm using:

$(".sell-product").click(function() {
    var request = $.ajax({
        type: 'GET',
        url: Routing.generate('stock_exists', {company_id: company_id, product_upc: $(this).attr("data-id")}),
        success: function(data) {
            $("#layout-center").html();
            if (data.response === false) {
                $.prompt(data.msg, {
                    title: "Este producto ya posee stock, quiere actualizarlo?",
                    buttons: {"Sí": true, "No": false},
                    submit: function(e, v, m, f) {
                        if (v === true) {
                            // redireccionamos a otro lado
                        }
                    }
                });
            } else {
                $("#product-search, #product_create").hide();
                $("#sell-existent-product").load(Routing.generate('create_from_product', {company_id: company_id, product_upc: $(this).attr("data-id")}));
                $("#sell-existent-product").show();
            }
        },
        error: function() {
            request.abort();
        }
    });
});

The code is invoked when I click this HTML piece of code:

<button data-id="00000000000" class="btn sell-product">Sell</button> 

And this is the code from Symfony controller:

/**
 * Check if the current company has a stock created for the product
 * @Route("/stock_exists/{company_id}/{product_upc}", name="stock_exists", requirements={"company_id" = "\d+", "product_upc" = "\d+"})
 * @Method("GET")
 */
public function StockExistsAction($company_id, $product_upc) {
    $em = $this->getDoctrine()->getManager();

    $result = array();
    $result['response'] = true;

    if (!$company_id || !$product_upc) {
        $result['response'] = false;
        $result['msg'] = 'Wrong parameters';
    }

    $product = $em->getRepository('ProductBundle:Product')->find($product_upc);
    $company = $em->getRepository('CompanyBundle:Company')->find($company_id);

    if (!$product || !$company) {
        $result['response'] = false;
        $result['msg'] = 'Error not found product or company';
    }

    $stock = $em->getRepository('StockBundle:KStock')->findBy(array('company' => $company_id, 'product' => $product_upc));
    if ($stock) {
        $result['response'] = false;
        $result['msg'] = 'This company has a stock created for this product. Only one stock per product is allowed.';
    }

    return new JsonResponse($result);
}

/**
 * Display a form to create new stock
 * 
 * @Route("/existent/{company_id}/{product_upc}", name="create_from_product", requirements={"company_id" = "\d+", "product_upc" = "\d+"})
 * @Method("GET")
 */
public function newExistsAction($company_id, $product_upc) {
    $em = $this->getDoctrine()->getManager();
    $entity = new KStock();

    $product = $em->getRepository('ProductBundle:Product')->find($product_upc);
    $company = $em->getRepository('CompanyBundle:Company')->find($company_id);

    $form = $this->createForm(new KStockType($company->getId(), $product->getUpc()));
    return $this->render('StockBundle:Stock:stock_existent_product.html.twig', array('entity' => $entity, 'form' => $form->createView(), 'company' => $company_id, 'product' => $product_upc));
}

Product with UPC="00000000000" exists but not for the logged in company so it renders the view and send the output as you can see in the image above:

enter image description here

This is the view I'm loading:

<div>
    <div id="stock_container_form">        
        <link href="{{ asset('/bundles/stock/css/foundation-datepicker.css') }}" rel="stylesheet" />
        {% if edit %}
            <input type="hidden" name="_method" value="PUT" />
        {% endif%}

        <div class="large-12 columns">
            <label>{{ form_label(form.sku) }}</label>
            {{ form_errors(form.sku) }}
            {{ form_widget(form.sku) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.price) }}</label>
            {{ form_errors(form.price) }}
            {{ form_widget(form.price) }} {{ form_widget(form.unit) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.amount) }}</label>
            {{ form_errors(form.amount) }}
            {{ form_widget(form.amount) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.status) }}</label>
            {{ form_errors(form.status) }}
            {{ form_widget(form.status) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.condition) }}</label>
            {{ form_errors(form.condition) }}
            {{ form_widget(form.condition) }}
        </div>
        <div class="large-12 columns">
            {{ form_label(form.width) }} {{ form_widget(form.width) }}
            {{ form_label(form.height) }} {{ form_widget(form.height) }}
            {{ form_label(form.length) }} {{ form_widget(form.length) }}
            {{ form_widget(form.nlength) }}
        </div>
        <div class="large-12 columns">
            {{ form_label(form.weight) }} {{ form_widget(form.weight) }}
            {{ form_widget(form.nweight) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.description) }}</label>
            {{ form_errors(form.description) }}
            {{ form_widget(form.description) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.start_date) }}</label>
            {{ form_errors(form.start_date) }}
            {{ form_widget(form.start_date) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.warranty) }}</label>
            {{ form_errors(form.warranty) }}
            {{ form_widget(form.warranty) }}
        </div>
        <div class="large-12 columns">
            <label>{{ form_label(form.valid_time) }}</label>
            {{ form_errors(form.valid_time) }}
            {{ form_widget(form.valid_time) }}
        </div>

        {{ form_rest(form) }}   
    </div>
    <div class="record_actions">
        <button type="button" id="create_stock">{{'Crear'|trans}}</button>
    </div>
</div> 

<script src="{{ asset('/bundles/stock/js/foundation-datepicker.js') }}" type="text/javascript"></script>
<script src="{{ asset('/bundles/stock/js/common.js') }}" type="text/javascript"></script>

Any ideas what's wrong here? I'm stucked and can't find where the issue/problem is

UPDATE

Here is a image showing the generated code after I make the call (note: I fixed the button type already)

enter image description here

Reynier
  • 2,420
  • 11
  • 51
  • 91
  • Is the button inside of a `form`? – t.niese Sep 01 '13 at 21:57
  • @t.niese nop (see the main post I added the loaded view), it's not inside a form – Reynier Sep 01 '13 at 21:59
  • Try setting the type of that button to `button`, the default type would be `submit`, and it's hard to read markup in a templating language. Also, you seem to have a `$.prompt` method, where does that come from ? – adeneo Sep 01 '13 at 22:03
  • @adeneo the `$.prompt` come from [here](http://trentrichardson.com/Impromptu/) which is a library for display prompt dialogs! And if you notice the button have the type set to `button` already – Reynier Sep 01 '13 at 22:06
  • @Reynier the code you talk about attaches the `click` event to `.sell-product` the button snippet for this button is `` so it's type is not `button` and in your provided source there is no such button with the class `sell-product` are you really sure it is not in a `form` (You should check this in the generated source). – t.niese Sep 01 '13 at 22:10
  • @t.niese yes I'm pretty sure isn't a form, see my edit at main post there you will see the generated code before I click the `button.sell-product` – Reynier Sep 01 '13 at 22:16
  • @t.niese I found the error, should I answer my own question or should I edit the main post and leave the answer to others in case they run in the same error? – Reynier Sep 01 '13 at 22:24
  • @Reynier [Can I answer my own question?](http://stackoverflow.com/help/self-answer) – t.niese Sep 01 '13 at 22:26

1 Answers1

0

After read my code once and once again I found where my mistake was. See this code:

$(".sell-product").click(function() {
    var request = $.ajax({
        type: 'GET',
        url: Routing.generate('stock_exists', {company_id: company_id, product_upc: $(this).attr("data-id")}),
        success: function(data) {
            $("#layout-center").html();
            if (data.response === false) {
                $.prompt(data.msg, {
                    title: "Este producto ya posee stock, quiere actualizarlo?",
                    buttons: {"Sí": true, "No": false},
                    submit: function(e, v, m, f) {
                        if (v === true) {
                            // redireccionamos a otro lado
                        }
                    }
                });
            } else {
                $("#product-search, #product_create").hide();
                $("#sell-existent-product").load(Routing.generate('create_from_product', {company_id: company_id, product_upc: $(this).attr("data-id")}));
                $("#sell-existent-product").show();
            }
        },
        error: function() {
            request.abort();
        }
    });
});

If yours notice in this line exactly:

$("#sell-existent-product").load(Routing.generate('create_from_product', {company_id: company_id, product_upc: $(this).attr("data-id")}));

I'm using $(this) which doesn't exists on that context so I create a var outside and then access that var inside. See the code with fixes:

$(".sell-product").click(function() {
    var current = $(this);
    var request = $.ajax({
        type: 'GET',
        url: Routing.generate('stock_exists', {company_id: company_id, product_upc: current.attr("data-id")}),
        success: function(data) {
            $("#layout-center").html();
            if (data.response === false) {
                $.prompt(data.msg, {
                    title: "Este producto ya posee stock, quiere actualizarlo?",
                    buttons: {"Sí": true, "No": false},
                    submit: function(e, v, m, f) {
                        if (v === true) {
                            // redireccionamos a otro lado
                        }
                    }
                });
            } else {
                $("#product-search, #product_create").hide();
                $("#sell-existent-product").load(Routing.generate('create_from_product', {company_id: company_id, product_upc: current.attr("data-id")}));
                $("#sell-existent-product").show();
            }
        },
        error: function() {
            request.abort();
        }
    });
});

Note this part var current = $(this);, hope this help another ones!!

Reynier
  • 2,420
  • 11
  • 51
  • 91
  • So it was not an actual redirect of the page but just another request that was only in the network tab and not an actual redirect of the page itself? I'm just asking because if so then you should have been clear about this in the question and you would have got the answer faster. (At least I was scanning your code for a page redirect problem and not for another AJAX request that was failing) – t.niese Sep 01 '13 at 22:44