The Wanderer The Wanderer - 7 months ago 16
HTML Question

show() overwritten multiple ajax calls

I have one html element (

elem1
) and 2 JS functions (
func1
,
func2
) that hides and shows
elem1
respectively. These JS functions make individual ajax calls and
func2
is calling
func1
internally.

Problem: I need to call
func2
, which internally calls
func1
. Calling
func1
hides
elem1
. After calling
func1
, I want to
show
elem1
. But this
show
is not working.

JSFiddle: https://jsfiddle.net/46o93od2/21/

HTML:

<div id="elem">
Save ME
</div>
<br/>

<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>


JS:

function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}


function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}

Answer

Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.

function func1(callback) {
  $.ajax({
    url: '/echo/json/', //use the correct processing url here
    type: "POST",
    data: {
      json: ''
    }, // send in your data
    success: function(data) {
      if (callback) {
        callback();
      } else {
        $('#elem').hide();
      }
    },
    error: function(xhr, errmsg, err) {
      alert('error');
    }
  });
}


function func2() {
  $.ajax({
    url: '/echo/json/', //use the correct processing url here
    type: "POST",
    data: {
      json: ''
    }, // send in your data
    success: function(data) {
      func1(function() {
        $('#elem').show();
      });
    },
    error: function(xhr, errmsg, err) {
      alert('error');
    }
  });
}

DEMO