0

I have a page(parent.php) from where i am calling a another page(result.php) through jquery ajax that is returning a response in html format. This response is showed on the parent.php page in a div. How can i secure my ajax response from xss attack. Here is the code snippet of parent.php page

$.ajax({
        type: "POST",
        url: "getResult.php",
        data:{search_in:search_in},  
        beforeSend:function(){  
        $("#search_result").html('Loading..');

    },   
    success: function(result)
    {
        $("#search_result").html(result);
        $("#search_result").show();

    }
});

in the getResult.php page i am quering database based on the parameter and returning some result in html form like table. How can i prevent cross site attack

  • What makes you say that there is a XSS attack ? I'm not saying that there is not, but I think you may be confused about this attack. – John Kravicz Feb 1 at 9:08
  • $("#search_result").text(result); would be immune – dandavis Feb 2 at 3:08
1

An XSS attack here means that the attacker somehow must be able to compromise the HTML in the Ajax result. Assuming that the connection itself can be trusted (i.e. HTTPS) there are basically two options: sanitize the HTML in the client and/or make sure that there is no XSS in it in the first place in the server.

The latter option is preferred if you have control of the server, i.e. the server should not generate compromised HTML in the first place. How this exactly is done depends on your unknown web application. But the basic idea that you need to be clear what kind of inputs can be trusted and what not (i.e. can be influenced by the attacker) and then make sure to properly sanitize/restrict the untrusted parts, for example by not allowing HTML input from untrusted sources in the first place.

If you have no control of the server you can only sanitize the HTML inside your client side application. This can of course be done additionally to server side protection (i.e. where you have control of the server) too in case you don't really trust your own server and better want to have a second line of defense. But in general it is easier and more secure to make sure to not include unverified/unsanitized user input in the first place instead of trying to remove it later from the constructed HTML. There are many libraries which help you to sanitize the HTML on the client side using Javascript, see this google search and pick the one which fits your purpose best.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.