Post html code for PHP using jQuery

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

I use this code to send HTML code and multiple identifiers 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 use PHP and do this:

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

This works a lot of time when non-HTML fragments are sent, but does not work when something like this is sent in 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 should do in terms of encoding data on the client side and then decoding on the server side? Also not sure if dataType: "json" is best used here?

+3
3

dataType - script. JSON.stringify, json2.js script , JSON .

escape() JavaScript editor1.getData(), .

, PHP , escape.

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'];
+3

PHP stripslashes(). . , , img.

" , dataType:" json ", , . .

+2

, YAHOO.lang.JSON.stringify(html) http://developer.yahoo.com/yui/json/ PHP json_decode (json) , html (, @@$$ ^ ^ & *() + {}: "< > ?) , html. , YUI, -, ... , - html, , .

+1

Source: https://habr.com/ru/post/1777360/


All Articles