Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post html code to PHP using jQuery

I allow users to edit webpages using CKEditor and then save their modified HTML snippets to the server so that I can show them on subsequent page deliveries.

I'm using this code to send the HTML and a few IDs to the server:

var datatosend = JSON.stringify( { page: 1, block: 22, content: editor1.getData() } );

$.ajax({
  url: "/ajax/fragment/",
  type: "POST",
  dataType: 'json',                     
  data: "data=" + datatosend,
  success: function (html) {  },
  error: function (xhr, status, msg) { 
     alert( status + " " + msg );
  }
});      

And on the server side I am using PHP and am doing this:

    $json = stripslashes( $_POST[ "data" ] );
    $values = json_decode( $json, true );       

This works a lot of the time when non-HTML snippets are sent but does not work when something like this is sent in the content:

<img alt="" src="http://one.localbiz.net/uploads/1/Dido-3_2.JPG" style="width: 173px; height: 130px;" />

I'm really not sure what I am supposed to be doing in terms of encoding the data client-side and then decoding server-side? Also not sure if dataType: 'json' is the best thing to use here?

like image 844
Steve Claridge Avatar asked Feb 26 '26 18:02

Steve Claridge


1 Answers

The dataType attribute is the expected return data type from the server-side script. Since you're using JSON.stringify call I'll assume the use of the json2.js script or similar that allows serialization of the JSON objects on the client side.

You may want to use the JavaScript escape() function on the editor1.getData() call, so it will properly escape the problem characters.

I used the following as a test and the PHP program returned the exact copy of the string literal passed to the escape function.

so.html*

<!DOCTYPE html>
<html><head><title>SO Example</title>
<script 
  type="text/javascript" 
  src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js">
</script>  
</head>
<body>

<script type="text/javascript">
  var $data = 'd=' + escape(
    '<img alt="" src="http://one.localbiz.net/uploads/1/Dido-3_2.JPG" style="width: 173px; height: 130px;" />'
  );

  $.ajax({
    url:"/so.php",
    type:"post",
    dataType:"html",
    data:$data,
    success:function(obj){
      alert(obj);
    }
  });
</script>
</body>
</html>

so.php*

<?php
  echo $_POST['d'];
like image 97
T.P. Avatar answered Feb 28 '26 07:02

T.P.