Search code examples
jquerysymfonysymfony-2.3

Strange redirect after load successfully


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


Solution

  • 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!!