0

Please help me understand why my ajax code runs only on the first loop. I have an array of JSON. Each JSON needs to be processed to get the response from the server. What happens is that "Processing..." were logged in console number of times as the length of arrayJSON, then the first loop will run ajax. After that I'm getting timeout errors. Below is my code. Many thanks!

        $.each(arrayJSON, function(i, arrayJSONInstance) {

            jsonString = JSON.stringify(arrayJSONInstance);

            $.ajax({
                url: "php/phpcode.php",
                data: {
                    data: jsonString
                },
                dataType: "json",
                type: "POST",
                timeout: 0,
                beforeSend: function (response) {
                    console.log("Processing...");
                },
                success: function (response) {
                    console.log(response);
                    console.log("Success!");
                },
                error: function(response) {
                    console.log("ERROR:\n");
                    console.log(response);
                }
            });
        });

1 Answer 1

2

As we know, ajax calls are asynchronous, your code is sending multiple ajax calls (depending on the length of the array).

Try making ajax call synchronous using:

async: false

Tell me if it solves the problem.

Sign up to request clarification or add additional context in comments.

3 Comments

It worked thank you very much! But I think that setting async to false hangs the UI. Am I right about that? How can we avoid that?
Yes. Using async: false is a bad practice especially when the data is large. In your case, rather than making multiple ajax calls, make a single ajax call and pass the json array in it. Process the json array in your php (backend).
That is what I actually did in my first attempt. But I am expecting the backend to return response after 15-20 minutes. That is why I divided the data into portions so I can immediately prompt the users of the errors encountered backend if there's any, because I think that browsers have ajax timeout.I will also consider sending the data in only one request. I'll just think of how can I return response to the users. Thank you so much for your time and help!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.