Ric
Ric

Reputation: 3478

Pass JavaScript function in ajax response

I'm trying to return a callback from an AJAX submitted form. The user submits a form, the server processes and returns the valid response, i.e. an error message and also a JavaScript function that could perform an action. I'm using Zepto.js faling back to jQuery depending on browser.

My ajax request is:

$.ajax({
    success: function(data, status, xhr) {
        data.callback();
    },
    url: form.attr('action'),
    data: form.serialize(),
    dataType: 'json'
});

On the server I want to return something like:

// PHP code
?>
{
    return: false,
    error: 'Sorry, we couldn’t find an account with that username or password.',
    callback: function() {
        console.log('this is the callback');
    }
}
<?php
// more PHP code

When returned to the browser callback function should fire. I want the server to return the callback so I can use the same JavaScript code and have it respond accordingly to the server response.

Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.

Any help appreciated.

Upvotes: 2

Views: 2222

Answers (2)

Ric
Ric

Reputation: 3478

The general feeling here is I am approaching this in the wrong way. So revised code:

$.ajax({
    success: function(data, status, xhr) {
        var callback = data['callback'];
        callback();
    },
    url: form.attr('action'), // in this example it's badLogin
    data: form.serialize(),
    dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
    console.log('bad login');
}

And my PHP

if (!$valid) {
?>
{
    "return": false,
    "error": "Sorry, we couldn’t find an account with that username or password.",
    "callback": "badLogin"
}
<?php
}

Thanks for pointing me in the right direction.

Upvotes: 1

MMM
MMM

Reputation: 7310

You can always return the code as a string and use eval() if you are absolutely sure that the string will always be correct and no code can be injected.

Upvotes: 0

Related Questions