albanx
albanx

Reputation: 6335

send html text with ajax, problem on '&'?

i use jquery.ajax to save a rich text area .

corr=some.innerHTML(); /* corr='< some text <' */
$.ajax({
    type:"POST", url:"flatplan/save_corr.php",
    data:"corr="+corr+"&IDFS="+IDFILES,
    success: function(msg){

    },
    error:function(x,e){
        ajax_errors(x,e);
    }
});

The problem is that the corr variable can contain '&' chars inside and it send more params giving problems. Is there any way to post with ajax html text?

Upvotes: 1

Views: 1903

Answers (3)

kennytm
kennytm

Reputation: 523304

You can (and should) escape query string components with encodeURIComponent.

data: "corr=" + encodeURIComponent(corr) + "&IDFS=" + encodeURIComponent(IDFILES),

Edit: jQuery can accept an Object in the data field. You should just use

data: ({
  corr: corr,
  IDFS: IDFILES
}),

so that jQuery can automatically encode the query string.

Upvotes: 5

EndangeredMassa
EndangeredMassa

Reputation: 17528

The corr value cannot contain &. If it does, you need to urlencode that value. To do this, use the escape() method.

var corr = escape(some.innerHTML()); //(corr='< some text <')
$.ajax({
    type:"POST", 
    url:"flatplan/save_corr.php",
    data:"corr="+corr+"&IDFS="+IDFILES,
    success: function(msg){
        //success handler
    },
    error:function(x,e){
        ajax_errors(x,e);
    }
});

Upvotes: 1

Gopher
Gopher

Reputation: 1

I would personally escape all html going into before posting it via AJAX that and have the php file unescape the resultant or Sanity Check the input in PHP before processing. I've not been caught with this one but I can see where it might be an issue.

Upvotes: 0

Related Questions