4

I have a link, which I want to make a DELETE request with JQuery with AJAX.

if(confirm("Are you sure?")) {
   $.ajax({
    url: $(this).attr("href"),
    type: 'DELETE',
    success: function(result) {
            // Do something with the result
        }
    });
}

result is a wad of Javascript I would like to run. How do I get it to run my returned script?

4
  • 2
    Please don't do that. Don't return Javascript code, don't eval, just return some kind of identifier and let your Javascript decide what to do. Commented Jun 10, 2011 at 16:10
  • @bazmegakapa Are you saying this for a separation of concerns purpose or is there a technical reason why this is a bad idea? Commented Jun 10, 2011 at 16:12
  • eval should be avoided whenever possible. I don't think there is a real reason for returning a piece of code. You could return some kind of JSON, and define in your Javascript what should happen to it. Commented Jun 10, 2011 at 16:14
  • Mainly security reasons. a Hacker may be able to inject malicious code into your site. Commented Jun 10, 2011 at 16:15

3 Answers 3

14
success: function(result) {
    eval(result);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Don't feel dumb - it's easy to forget built in functions if you don't use them often.
Are there any risks attached to using eval() in this use case?
5

Use the dataType: 'script' option

$.ajax({
    url: $(this).attr("href"),
    type: 'DELETE',
    dataType: 'script'
});

Or simply,

$.getScript($(this).attr("href")); // Won't use 'DELETE' http type

1 Comment

Nice. This fits better with the rest of my Javascript. :)
2

Check the javascript Eval method. It allows you to execute js code which is represented as a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.