0

I write php function to delete some content in my project but I want to do different things depending on content.

so my jQuery code :

    $(document).on("click",".delete-action",function(e) {
    var data = $(this).data("delete");
    $.ajax({
        url : "../ajax/ajax_service.php",
        type : "POST",
        data : {"method" : "delete_ajax",data},
        success : function(response) {
            // response
        },
        error : function() {

        }
    });
    e.preventDefault();
});

PHP code

<?php
if(!function_exists("delete_ajax")) {

function delete_ajax() {
    global $db;
    $js_code = '';
    $c_type = $_POST["data"]["c_type"];
    $c_id = $_POST["data"]["c_id"];
    $c_dom_selector = $_POST["data"]["c_dom_selector"];
    if(empty($c_type) || empty($c_id)) {
        return false;
    }

    if($c_type == "page") {
        //$delete = $db->delete("pages",$c_id);
        if(!empty($c_dom_selector)) {
            $js_code .= ' $("'.$c_dom_selector.'").remove(); ';  
        }
    }

    $js_e = ' $(function() { '.$js_code.' }); ';

    echo $js_e;
}

}

So I want a secure solution to run jQuery code returned from response

joowmss
  • 13
  • 4
  • 2
    Why don't you just do `$(data.c_dom_selector).remove()` in the success callback? – Karl-André Gagnon May 29 '18 at 19:40
  • dont do this, but https://stackoverflow.com/questions/939326/execute-javascript-code-stored-as-a-string – Andrew May 29 '18 at 19:41
  • Possible duplicate of [Execute JavaScript code stored as a string](https://stackoverflow.com/questions/939326/execute-javascript-code-stored-as-a-string) – Andrew May 29 '18 at 19:42
  • @Karl-AndréGagnon yes I know that. but I need do differents things (mostly I need to write many lines of jQuery). – joowmss May 29 '18 at 19:42
  • Return json and do the business logic based on response in your main javascript – charlietfl May 29 '18 at 19:42
  • Please don't sent me solution using `eval` because in know that. I want a secure solution if exists – joowmss May 29 '18 at 19:43
  • 1
    Javascript should be done and wrote in JavaScript, not some server-side language. Do as charlietfl said, return a JSON and work the logic in the success callback. Also, that might be a base PHP code or a work in progress, but if security is a concern, you really need to change how you handle the request! – Karl-André Gagnon May 29 '18 at 19:46
  • Why is security a concern here? The server is just returning the code that the client sent it. The client can just as easily execute that code itself directly. – Barmar May 29 '18 at 20:15
  • @Barmar yes I'm agree with you all the js codes already known there is no security mistake – joowmss May 29 '18 at 20:24
  • @Barmar best way to do that I think is to append js code to body. what you think ? – joowmss May 29 '18 at 20:42
  • @joowmss You could do that, or just use `eval()`. They're essentially the same thing. – Barmar May 29 '18 at 20:48

0 Answers0