0

I have jquery code that loops based on a counter, and inserts a record to a database and then opens a series of 4 reports for each new record it inserts.

The loop runs based on the number that is supplied by the user in the form dropdown called dropdownSection. For each Section; 1,2, or 3 the same number of records need to be inserted by ajax.

When the loop runs in the browser I get an error that I cannot track down. When I set a breakpoint in FireBug and step through the code it works fine. This leads me to think my loop might be running too fast?

Here is my code for the loop:

function InsertSheeter()
{
    var textDate = $('#textDate').val()
    var Workorder = $('#textWorkorder').val()
    var Material = $('#dropdownMaterial').val()
    var Shift = $('#dropdownShift').val()
    var Sheeter = $('#dropdownSheeter').val()
    var FoilNum1 = $('#textFoilNum1').val()
    var FoilNum2 = $('#textFoilNum2').val()
    var FoilNum3 = $('#textFoilNum3').val()
    var Printline = $('#dropdownPrintline').val()
    var Section = $('#dropdownSection').val()
    var Comments = $('#textComments').val()
    var Employee = $('#dropdownEmployees').val()

    var a = 0

    while (a < Section)
    {


        switch (a)
        {
            case 0:
                blockSection = "1"
                break;
            case 1:
                blockSection = "2"
                break;
            case 2:
                blockSection = "3"
                break;
        }

        var str = "{pDate:'" + textDate + "', pSheeter:'" + Sheeter + "', pShift:'"
            + Shift + "', pEmployee:'" + Employee + "', pWorkorder:'"
            + Workorder + "', pBlockSection:'" + blockSection + "', pComments:'"
            + Comments + "', pFoilNum1:'" + FoilNum1 + "', pFoilNum2:'"
            + FoilNum2 + "',    pFoilNum3:'" + FoilNum3 + "', pPrintline:'"
            + Printline + "', pMaterial:'" + Material + "'}"

        $.ajax(
    {
        type: "POST",
        //contentType: "application/text; charset=utf-8",
        url: "insertsheeter",
        data: str,
        dataType: "html",
        success: function (data) {

            OpenReports(Workorder, data);
        },
        error: function (xhr, errorType, exception)
        {

            var errorMessage = exception || xhr.statusText;
            alert(errorMessage);
        }

    });



        a++;

    }


}

Do I need to put a delay in my loop to allow the other stuff to happen before continuing the loop?

Thx

Ryan
  • 650
  • 3
  • 15
  • 49
  • 1
    It would be useful if you attached the actual JS error you are getting – maurycy Jun 12 '14 at 13:41
  • Looks like Asynchronous Javascript And XML inside a while loop, I would recommend using a recursive function or $.when etc. instead. – adeneo Jun 12 '14 at 13:43
  • your browser cannot handles so much ajax requests in paralell targeting same domain. Throttle it in some way or better make only one ajax request sending all relevant data at once – A. Wolff Jun 12 '14 at 13:43
  • I dont know what it is. I have an alert in the ajax error section but it literally flashes on the screen and goes away. – Ryan Jun 12 '14 at 13:44
  • @A.Wolff The ajax request is dependent on what value a equals. It would be 1,2, or 3 depending on the number of Sections the user has entered. So should I gather all of this data in one ajax call? – Ryan Jun 12 '14 at 13:45
  • @Ryan I'm not sure why are you using a while loop here – A. Wolff Jun 12 '14 at 13:49
  • @A.Wolff I added more detail in my post about why I am using the loop – Ryan Jun 12 '14 at 13:53

3 Answers3

2

In your case, I suspect you need the loop to wait for one AJAX insertion and set of reports to complete before starting the next one. You can do this with a recursive function instead of your while loop:

function myFunc() {
    $.ajax({
        /* ...options... */,
        success: function(data) {
             OpenReports(Workorder, data);
             if (some_Boolean_test) {
                 myFunc();
             };
        }
    });       
}

myFunc();
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • So, would I wrap this around my code that is contained in InsertSheeter function? – Ryan Jun 12 '14 at 13:47
  • @Bergi Updated with an AJAX recursive function that might help. – Blazemonger Jun 12 '14 at 14:00
  • @Ryan The recursive call basically replaces your `while` loop. However, since we're nesting new functions, you may need to pass some variables into `myFunc` from the outside. I don't think I have enough information from your code sample to tell you exactly how to do it. – Blazemonger Jun 12 '14 at 14:21
0

Adding a fixed delay isn't going to be a consistent solution--that is if timing is even your problem. You should try setting async: false as Dave suggested. If that fixes your issue then timing might be part of your problem. The problem with fixed time delays is that they work under current conditions, but if for some reason the "slow" part takes even longer, your delay might not be enough--that's an antipattern.

As an aside, the one thing that sticks out to me is that you made a string that looks like a JSON object for your HTTP-POST data instead of just making a JSON object--was there a particular reason you did so? I would have done this:

var postData = { pDate: textDate, pSheeter: Sheeter, pShift: Shift, pEmployee: Employee, pWorkorder: Workorder, pBlockSection: blockSection, pComments: Comments, pFoilNum1: FoilNum1, pFoilNum2: FoilNum2, pFoilNum3: FoilNum3, pPrintline: Printline, pMaterial: Material }

and then set data: postData in the $.ajax() call. Maybe your server code expects such an odd string though?

Hope this helps.

Joe
  • 86
  • 5
  • this works great for what I need it to do. async will work for me – Ryan Jun 12 '14 at 14:09
  • 1
    [Switching from asynchronous code to synchronous is almost always the wrong solution for these problems](http://stackoverflow.com/a/14220323/901048). The `success` and `error` callbacks are there for a reason, and should be used instead. – Blazemonger Jun 12 '14 at 14:23
  • The weird part here though is he is already using them. And I agree, it's more just a troubleshooting strategy to pinpoint timing issues. – Joe Jun 12 '14 at 14:23
  • Right, but you're down-voting people for offering ways of finding the problem. We all get that it's not the end-all-be-all. – Joe Jun 12 '14 at 14:29
-1

AJAX calls are by default Asynchronous, it looks like you might be looking for some synchronous behaviour here.

You can make an AJAX synchronous by setting

async: false
Dave Briand
  • 1,684
  • 1
  • 16
  • 16