Home > other >  Use AJAX to send SVG string to server as svg file with specified file name
Use AJAX to send SVG string to server as svg file with specified file name

Time:01-27

I have a string of svg, and want to use AJAX to send it to server as a file: mySVG.svg.

What I am trying to do now is to save the svg string and file name as two properties in an object, and then send the object to the server as json. But I found that the server could not receive the content I sent, and could not create the corresponding .svg file.

May I ask how to achieve it? Here are my codes.

HTML and JavaScript:

let svgData = '<svg width="300px" height="200px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><symbol id="carrot" viewBox="0 0 50 50"><path d="M30 13c-1-3-5-4-7-2h-1l1-11h-3l-1 9-4-7-3 1 5 8-8-4-1 2 9 5h-1c-2 2-3 5-2 7l2 2 5-3 1 2-5 3 8 9 5-3 2 2-5 3 12 14 3-2-8-25-5 3-1-2 5-3-3-8z" /></symbol><pattern id="myPat" patternUnits="userSpaceOnUse" width="88" height="88" ><use xlink:href="#carrot" width="30" height="30" fill="orange" transform="rotate(80 45 25) translate(20 0)"></use><use xlink:href="#carrot" width="60" height="60" fill="blue" transform="rotate(50 65 25) translate(40 0)"></use></pattern><rect x="0px" y="0px" width="300px" height="200px" fill="url(#myPat)"> </rect></svg>'

let filename = "mySVG"

//show svg on the screen
let container = document.getElementById("container");
document.body.appendChild(container)
container.innerHTML = svgData;

//when click the button, send the svg to server
document.getElementById('sendSVG').onclick = function (){
        sendSVG(svgData, filename)
}

//send svg to server
function sendSVG(svgData, filename){
  let obj = {}
  obj.svgData = svgData
  obj.filename = filename
  
  $.ajax({
      url: 'svg_ajax.php',
      type: 'POST',
      data: JSON.stringify(obj),
      contentType: 'application/json',
      dataType: "json",
      success: function () {
          console.log('success')
      }
  })
}
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<button id="sendSVG">Send SVG to Server</button>
<div id="container"></div>

PHP:

//svg_ajax.php
<?php
    $data = json_decode(file_get_contents('php://input'));
    $svgData = $data['svgData'];
    $filename = $data['filename'];
    file_put_contents($filename, $svgData);
?>

CodePudding user response:

Use the code below:

<?php
    $data = json_decode(file_get_contents('php://input'), TRUE);
    $svgData = $data['svgData'];
    $filename = $data['filename'];
    file_put_contents('test.svg', $svgData);

OR:

<?php
    $data = json_decode(file_get_contents('php://input'));
    $svgData = $data->svgData;
    $filename = $data->filename;
    file_put_contents('test.svg', $svgData);

When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects.

  • Related