1

I'm loading a dynamic header with a dynamic hidden input from php by doing an ajax request. The input gets created fine. The problem is not there. Below the same page I'm using plain javascript to get the value of that dynamic input. The Ajax and the javascript are two different codes. If they were not, I would simply load from ajax success but I can't do this here.

Problem is, in the console I get this error :

TypeError: document.getElementById(...) is null

How can I fix this?

hidden input

<input id="appStatus" type="hidden" value="0">

javascript

window.onload = function() {

 var app_mode = document.getElementById('appStatus').value;

    if (app_mode === 0) {//dev

        var stripe = Stripe('pk_test_xxxx');

    } else {//live prod

        var stripe = Stripe('pk_live_xxxx');
    }

};
5
  • use promise, or do this on ajax success Commented Feb 9, 2020 at 4:44
  • @MisterJojo : I know how to do this on ajax success. The Javascript is a different script. It's for stripe. What is promise? Can you show me please? Thank you Commented Feb 9, 2020 at 4:48
  • there is no other way Commented Feb 9, 2020 at 4:51
  • @MisterJojo : Sir can you show me promise? I'm unfamiliar with this. Commented Feb 9, 2020 at 4:53
  • This might help. [stackoverflow.com/questions/8249641/… Commented Feb 9, 2020 at 4:53

2 Answers 2

1

You are calling document.getElementById('appStatus').value before your input field is generated by ajax request.

Use Promise for this



  function getInput() {
      return new Promise((resolve, reject) => {
        $.ajax({
            ...,
            success: function(response) {
                resolve(response);
            },
            error: function() {
                reject();
            }
        });  
      });
    }

window.onload = function() {
getInput().then(response => {
  var app_mode = document.getElementById('appStatus').value;

  if (app_mode === 0) {//dev
     var stripe = Stripe('pk_test_xxxx');
  } else {//live prod
     var stripe = Stripe('pk_live_xxxx');
  })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I do know this. I'm looking for a soluton :-)
1

Consider setTimeout function as success function

Add event DOMNodeInserted

When new element is inserted in document then function is automatically called

document.body.addEventListener("DOMNodeInserted",function() {
 var app_mode = document.getElementById('appStatus');
 if(!app_mode) return;
 console.log(app_mode.value);
});
setTimeout(()=>{
 document.querySelector("div").innerHTML = '<input id="appStatus" type="text" value="0">';
},3000);
<div></div>

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.