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):
- CheckNoteExist(tmpNoteFileSun);
- var DoesTheNoteExist = ""; //code needs to go here that returns noteexists (as in the alert below).
The Ajax Function:
- function CheckNoteExist(ThisNoteName, callback) {
- var NoteFileName = ThisNoteName;
- // Ajax to call an external php file, pass the notes filename to it and check if the file
- // exists. If it does, change noteexists variable to Yes", else it is "no".
- $.ajax({
- url: 'ajaxfile_note_exists.php',
- type: 'GET',
- data: {NoteFileName: NoteFileName},
- success: function(noteexists) {
- alert("Does the note exist: " + noteexists);
- callback && callback(noteexists);
- }
- });
- }
The external PHP file:
- $filename = "upload/" . $_GET['NoteFileName'];
- if (file_exists($filename)) {
- $noteexists = "yes";
- }
- else {
- $noteexists = "no";
- }
- echo $noteexists;
This is the code I got elsewhere that created the alert loops:
- CheckNoteExist(ThisNoteName, val => console.log("Does Not Exist " + val));
Can anyone help me to get this to work please?