How to get JQuery-Steps to call an ajax service when clicking 'next' on step 1

Jamie picture Jamie · Oct 18, 2016 · Viewed 8.8k times · Source

I'm using jquery steps although I need to call a c# service via ajax when the first 'next' is clicked, is this possible to be called and returned before the step 2 is displayed? The following code works although the ajax event returns after step 2 is loaded.

Many thanks, any help appreciated.

Jquery steps

http://www.jquery-steps.com/Examples#basic

I've noticed these methods? Maybe these are what I need

onStepChanging: function (event, currentIndex, newIndex)
onFinishing: function (event, currentIndex)
onFinished: function (event, currentIndex) 

My ajax event

    $(function () {
        $('a[href="#next"]').click(function () {
            var url = "...";

            $.ajax({
                url: url,
                success: function (response) {
                    // Form fields on second step
                    $("#EmailAddress").val(response.Email);
                    $("#FirstName").val(response.Firstname);
                    $("#LastName").val(response.Lastname);
                },
                error: function () {
                    alert("something went wrong");
                }
            });
        });

    });

Answer

sandrina-p picture sandrina-p · Oct 18, 2016

If i'm not wrong, placing the ajax call inside onStepChanging method should work.

Note that you have 3 parameters available, one of them - event - should be the button clicked. Use that to better define your url var, if you need to. Also with currentIndex you can detect if you are on the first step or not.

form.steps({
    onStepChanging: function (event, currentIndex, newIndex)
    {

       if (currentIndex == 0) { //I suppose 0 is the first step
           var url = "..."; 

           $.ajax({
               url: url,
               success: function (response) {
                   // Form fields on second step
                   $("#EmailAddress").val(response.Email);
                   $("#FirstName").val(response.Firstname);
                   $("#LastName").val(response.Lastname);
                   return true;
               },
               error: function () {
                   alert("something went wrong");
                   return false; //this will prevent to go to next step
               }
           });
       }
    },
});