简体   繁体   中英

How to get a callback on an Ajax function

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 on this site, but not sure how to implement it.

I tried adding some callback code to the success function, that I saw in an example elsewhere here 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 (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).

I tried changing the above to:

var DoesTheNoteExist = CheckNoteExist(tmpNoteFileSun);
console.log("Does Note Exist " + DoesTheNoteExist);

But get undefined in the console.

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;

?>

You're not using the callback, that's what it's there for.

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

See also How do I return the response from an asynchronous call? and Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM