How to use a callback in Ajax

How to use a callback in Ajax

Been struggling to understand the docs for this for 24 hours. Unable to resolve it. Posted elsewhere with no luck. In fact the code I got provided caused the alert to loop continuously (maybe because the function is called when the page loads?).

I am trying to find out if a text file (note) exists on the server. I want to return "yes" if it does, "no" if it does not. I am able to get this into an alert successfully (for each of the 7 occurrences) but I want to return it back into the originating html doc so I can use it in future code. I am reading about callbacks, but not sure how to implement it.

I tried adding some callback code to the success function, that I saw in an example elsewhere but am unsure how to edit my function call:

tmpNoteFileSun is a text string that matches the format of the text files stored on the server.

The function call is loaded from: $(document).ready(function().

The function call (there are 7 of these in separate places, 1 for each day of the week):
  1. CheckNoteExist(tmpNoteFileSun);
  2. var DoesTheNoteExist = ""; //code needs to go here that returns noteexists (as in the alert below).

The Ajax Function:

  1. function CheckNoteExist(ThisNoteName, callback) {

  2. var NoteFileName = ThisNoteName;

  3.     // Ajax to call an external php file, pass the notes filename to it and check if the file
  4.     // exists. If it does, change noteexists variable to Yes", else it is "no".
  5.     $.ajax({
  6.         url: 'ajaxfile_note_exists.php',
  7.         type: 'GET',
  8.         data: {NoteFileName: NoteFileName},
  9.         success: function(noteexists) {
  10.           alert("Does the note exist: " + noteexists);
  11.           callback && callback(noteexists);
  12.         }
  13.     });

  14. }

The external PHP file:

  1. $filename = "upload/" . $_GET['NoteFileName'];

  2. if (file_exists($filename)) {
  3.   $noteexists = "yes";
  4. }
  5. else {
  6.   $noteexists = "no";
  7. }

  8. echo $noteexists;


This is the code I got elsewhere that created the alert loops:

  1. CheckNoteExist(ThisNoteName, val => console.log("Does Not Exist " + val));


Can anyone help me to get this to work please?