简体   繁体   中英

Pass a JavaScript function with PHP after AJAX call is done

What I'm doing is checking a users status in the database.

The PHP page echo's the status back to the ajax call and depending on the status a function is being executed.

This works well. I know I could use json, but for now this is fine. What I'd like is not to echo the users status, but to echo the function that should be executed and execute it after ajax is done.

My jQuery/ajax code:

function checkstatus() {
    $.ajax({
    type: "GET",
    url: "./query/checkstatus.php",
    data: {}
    }).done(function(result) {
      if (result == "nieuw") {
        loadHomeNieuw();
      };
      if (result == "actief") {
        loadHome();
      };
    });
}

What I'd like but is not working. jQuery/ajax code:

function checkstatus() {
    $.ajax({
        type: "GET",
        url: "./query/checkstatus.php",
        data: {}
    }).done(function(result) {
    });
}

PHP code (not working):

if ($status == "nieuw") {
    echo "loadHomeNieuw();";
}

if ($status == "actief") {
    echo "loadHome();";
}

Is this even possible? The reason why I'm asking, is that I feel it's safer. It might be possible to hack the status as a user...so he can change it and the wrong function is being called. If I do this on the server side, it's way safer.

Or are there better options?

You can call eval

function checkstatus() {
    $.ajax({
        type: "GET",
        url: "./query/checkstatus.php",
        data: {}
    }).done(function(result) {
        eval(result);
    });
}

but some people say that's evil so you can just return a name and execute a function that have that name:

function checkstatus() {
    $.ajax({
        type: "GET",
        url: "./query/checkstatus.php",
        data: {}
    }).done(function(result) {
        window[result]();
    });
}

and in php just echo name

if ($status == "nieuw") {
    echo "loadHomeNieuw";
} else if ($status == "actief") {
    echo "loadHome";
}

What you're looking for is called GetScript: http://api.jquery.com/jQuery.getScript/

this wil execute the returned code. the code :

$.getScript("./query/checkstatus.php");

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