-1

I am working on a website using JQuery to display HTML returned from an AJAX call. Upon clicking a button, the following JS function is called:

function example(...) {
    get_ajax_and_display(...);
    show_hidden_div(...);
}

The first function get_ajax_and_display() makes an ajax call, and on success, calls $("#ex_div").html(ajax_response) to set the innerHTML of ex_div to whatever was returned from the ajax call. In particular, that returned html contains a <span id='ex_span' style="display: none">.

The second function show_hidden_div() calls $("#ex_span").show() in order to display that span.

However, the second function call fails, as $("#ex_span") seems to be undefined, even though the first function already created it.

Does the .html(ajax_response) not actually get set until the example(...) function returns?

I call the 2 inner functions separately in other parts of my code and they work fine on their own.

Why can't I call them like this?

2
  • use 'on' method to display the div which is added by ajax response Commented Sep 14, 2016 at 4:06
  • As an update, I have much better code using Deferred objects from the $.post() function. Required a bit of a refactor, but the result is much better than using the deprecated async parameter. Commented Jul 3, 2017 at 3:37

2 Answers 2

2

Trigger show_hidden_div(); in the success function of your ajax call, ajax is asynchronous so show_hidden_div() triggers first and then when ajax is complete the div is appended to the page

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

2 Comments

Ahhh, that makes a lot of sense, thanks for pointing that out! However, these 2 functions are used on their own separately in other parts of the site, so I can't do what you suggested unfortunately
you know javascript is executed globally on the page don't you?,is it that difficult to just trigger show_hidden_div in the success function?
1

Add async to your ajax call as follows

url: "url.php?" + params,
async: false,
dataType: "html",

2 Comments

I will a bool parameter to the JS function to have the AJAX be async true/false, then I could have it by sync when I need it to
Yep, with a parameter I can set in the function call whether or not the AJAX is async. Thanks a lot!

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.