2

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?

For example:

        function save(id) {
            $.ajax({
                type: "POST",
                url: "/post/",
                dataType: "json",
                contentType: 'application/json',
                data: JSON.stringify({
                    id: id,
                }),
                success: function (data) {
                 return data;
                },
                error: function (error) {
                return data;
                }
            });
        }

Usage:

$('.btn-create').click(function () {
  var id = 123;
  data = saveArea(id); //get data from ajax request or error data?
  if (data) { 
     window.location = "/post/" + data.something
  }
}
4
  • 1
    Why don't you put the redirect inside the succes callback? Commented Jul 6, 2017 at 14:15
  • 2
    You can make your AJAX call synchronous, but be mindful that any slowdowns in the data retrieval will lock up your page. Commented Jul 6, 2017 at 14:15
  • 1
    add window.location=.. inside success field Commented Jul 6, 2017 at 14:15
  • 1
    @Ionut that was a quick usage example. The reason why I didnt put redirect inside the success callback because in some in cases I don't need to redirect it for other action. Some places I need to use saveArea() and then redirect it, and other places I just need to saveArea() only without redirect. Commented Jul 6, 2017 at 14:30

2 Answers 2

4

You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks

Synchronous

As @Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.

function save(id) {
    return $.ajax({
        type: "POST",
        url: "/post/",
        dataType: "json",
        contentType: 'application/json',
        async: false,
        data: JSON.stringify({
            id: id,
        })
    }).responseText;
}

$('.btn-create').click(function () {
  var id = 123;
  // now this will work
  data = save(id);
  if (data) { 
     window.location = "/post/" + data.something
  }
}

Asynchronous (recommended)

This will run in the background, and allow for normal user interaction on the page.

function save(id, cb, err) {
    $.ajax({
        type: "POST",
        url: "/post/",
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify({
            id: id,
        }),
        success: function (data) {
            cb(data);
        },
        error: err // you can do the same for success/cb: "success: cb"
    });
}

$('.btn-create').click(function () {
  var id = 123;
  save(id, 
    // what to do on success
    function(data) { 
      // data is available here in the callback
      if (data) { 
          window.location = "/post/" + data.something
      }
    },
    // what to do on failure
    function(data) {
      alert(data);
    }
  });
}
Sign up to request clarification or add additional context in comments.

5 Comments

doesnt save function require a call for error ? shouldnt it be saveArea(id, function(data){....} , function(data){alert'fail');}
It's optional, JavaScript won't complain if you don't specify it until the AJAX call actually fails. I'll add it though for clarity, thanks!
no problem, it's a new information, thank you though !
Is save = saveArea() ?
@shotor..you write async: false which make it synchronous request.. but you said it is Asynchronous (recommended) ..?
0

Just make things a bit simpler.

For starters just add window.location = "/post/" + data.something to the success callback. Like this:

function save(id) {
    return $.ajax({
        type: "POST",
        url: "/post/",
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify({
            id: id,
        }),
        success:function(data){
            window.location = "/post/" + data.something
        }
    }).responseText;
} 

Or by adding all your Ajax code within the click event.

$('.btn-create').click(function () {
   var id = "123";

   $.ajax({
    type: "POST",
    url: "/post/",
    dataType: "json",
    contentType: 'application/json',
    data: JSON.stringify({
        id: id,
    }),
    success: function (data) {
     window.location = "/post/" + data.something
    },
    error: function (error) {
      console.log(error)
    }
  });

}

Comments

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.