0

I am getting an error on my ajax request but only if I call it from document.ready.

If I run the below script all works OK but username has been manually entered and not coming from the DOM

getProfile("steve8428");

function getProfile(userName) {
  var data = { username: userName };
  var dataSend = JSON.stringify(data);
  console.log(dataSend);
  $.ajax({
    url: "fetchProfile.php",
    type: "POST",
    data: dataSend,
    dataType: "json",
    success: function(data) {
      console.log(data);
    }
  });
}

This would indicate AjaX and jQuery including my php are all working ok.

But I want to get the username variable from a HTML element which is created on my main page using php. So I tried the following and here is where I get the error "jquery-3.2.1.min.js:2 Uncaught TypeError: $.ajax is not a function"

$(document).ready(function() {
  var userName = $("#username").html();
  getProfile(userName);
});

function getProfile(userName) {
  var data = { username: userName };
  var dataSend = JSON.stringify(data);
  console.log(dataSend);
  $.ajax({
    url: "fetchProfile.php",
    type: "POST",
    data: dataSend,
    dataType: "json",
    success: function(data) {
      console.log(data);
    }
  });
}

To give some back ground the variable username is coming from a php file which is generated from a php database request which is why I am doing the document.ready to ensure the username s available before making the Ajax request.

Am i missing something or do I need to look at a better way to do this

  • You need to either declare function inside document.ready callback or pass in $ – Alex Hart Jul 21 '19 at 03:07
  • if you mean move the whole function into document.ready and call it within document.ready, I tried this and still the same. Not sure what you mean by pass in $ –  Jul 21 '19 at 03:13
  • 1
    Actually, this might be due to using the minified version. Check out https://stackoverflow.com/questions/18271251/typeerror-ajax-is-not-a-function#40712438 – Alex Hart Jul 21 '19 at 03:19
  • Cheers Alex. I did look at this and I was using the wright javascript link but realised I had another link at the bottom of the php age, so must have been conflicting as now I have removed this link it is working. Annoying been pulling my hair out all night on this. May need to give up for night. Thanks for help –  Jul 21 '19 at 03:23

0 Answers0