AJAX loading dialog never shows

Greetings,

I'm working on some AJAX where I want a loading dialog window to show to inform the user something is happening while the JavaScript is getting results from the server.

My code is below. Problem is my loading dialog never actually shows.

The JS function loading() is what shows and hides the dialog.

When I call loading() it opens the dialog

When I call loading(true) it closes the dialog.

$('#greenbutton').on('click', function (e) {

	loading();

	var data = ContactForm.serialize();

	if (ContactForm.valid() === true) {

		var AJAXURL = "/user/contact";

		$.post(AJAXURL, data).done(function (result) {

			if (result.Success === true)
			{
				// works
			}
			else
			{
				// fails
			}
		});
	}

	loading(true);
});

Where am I going wrong?


User_69985 Profile Image

User_69985

Rating: 290

Offline


Answers (1)


This is a classic case of not fully understanding exactly how AJAX works. What is happening is that as soon as your code reaches the $.post function it jump straight to the bottom to where your calling loading(true). This is why it never opens because it essentially opens and then immediately closes.

This is because AJAX code loads Asynchronously, i.e. it will continue execution of your code while also loading your AJAX code.

What you need to do is call loading(true) when the AJAX call is complete so move your loading(true) function call inside your $.post call.

try updating your code to this...

$('#greenbutton').on('click', function (e) {

	loading();

	var data = ContactForm.serialize();

	if (ContactForm.valid() === true) {

		var AJAXURL = "/user/contact";

		$.post(AJAXURL, data).done(function (result) {

		/*
		  move this here so it only closes
		  the dialog when the AJAX is loaded
		*/	
		loading(true);

			if (result.Success === true)
			{
				// works
			}
			else
			{
				// fails
			}
		});
	}

});

 

JGilmartin Profile Image

JGilmartin

Technical Architect at Pinewood Technologies

Rating: 2890

C# Expert

Offline



yes this worked, thanks
User_69985
16/4/2017 20:06

Question Statistics
  • Views: 481
  • Answers: 1
  • Comments: 1
  • Asked: User_69985 (290)
  • Date: 16/4/2017 19:59
Tags
JavaScript

© 2016 - 2018 - IntermittentBug