0

I am trying to do an ajax 'post' call only once when a page loads. My code looks like this :

<script type='text/javascript'>
    $.post("amazon/apicalls/ConfirmAndAuthorize.php",{}).done(function(data) {
        var obj = jQuery.parseJSON(data);
        $.each(obj, function(key, value) {
            if (key == 'confirm') {
                var str = JSON.stringify(value, null, 2);
                $("#confirm").html(str);
            } else if (key == 'authorize') {
                var str = JSON.stringify(value, null, 2);
                alert(str);
                $("#authorize").html(str);
            }
        });
    });
</script>

I don't see anything wrong with the way I'm doing it however I am getting an error when the page loads : Cannot read property 'post' of undefined.

What am i forgetting here ?

EDIT:

The answer was a mix between Artem Gorlachev's and Milan Chheda's comments. It appears JQuery was only included in the page footer. So all that was needed was to wait for the page to load completely.

I achieve that without using JQuery with the methods presented in this answer to an other question.

Here is what it looks like :

<script type='text/javascript'>
    document.addEventListener("DOMContentLoaded", function(event) {
        $.post("amazon/apicalls/ConfirmAndAuthorize.php",{}).done(function(data) {
           ...
        });
    });
</script>
Community
  • 1
  • 1
  • or use document ready or insert link to jquery lib before your code – Artem Gorlachev May 18 '17 at 07:14
  • The error implies `$` is undefined, which means you haven't included jQuery, but then you'd normally see a `$ is undefined` error instead. Is the `$` variable being overridden by another library? – Rory McCrossan May 18 '17 at 07:14
  • Have you included JQuery? Seems that is missing. If added, seems its getting overridden. – Milan Chheda May 18 '17 at 07:14
  • Jquery is included. I used a similar code on some other pages with the same `includes`. The only difference being that those other Ajax call where done on some action by the user. – Joulin Nicolas May 18 '17 at 07:17

2 Answers2

0

Run in document ready for running only once when a page loads or refresh page

<script type='text/javascript'>
$(document).ready(function(){
  $.post("/amazon/apicalls/ConfirmAndAuthorize.php",{}).done(function(data) {.....
     ......
  });
);
.......
</script>
Gangga
  • 16
  • 1
  • 2
0

The answer was a mix between Artem Gorlachev's and Milan Chheda's answers. It appears JQuery was only included in the page footer. So all that was needed is to wait for the page to load completely.

I achieve that without using JQuery with the methods presented in this answers to an other question. See edit in OP.

Community
  • 1
  • 1