简体   繁体   中英

How to send multiple points with ajax to php file

I'm trying to send a few points that the user created and I don't know if to send it as an object or array

I tried to send it like object and it send only [object Object].

This is the function that creates points

function onSvgClick(event) {
  const customSvg = document.getElementById('my-svg');
  const svgInfo = 'http://www.w3.org/2000/svg';

  const circle = document.createElementNS(svgInfo, 'circle');
  circle.setAttribute('cx', event.offsetX);
  circle.setAttribute('cy', event.offsetY);
  circle.setAttribute('stroke', 'red');
  circle.setAttribute('stroke-width', 5);
  circle.setAttribute('r', 5);
  circle.setAttribute('fill', 'green');
  circle.setAttribute('fill-opacity',0);
  circle.setAttribute('id',currentid);

  points[currentid] = {id: currentid, x: event.offsetX, y: event.offsetY};

  alert(points[currentid]);
  currentid++;
  customSvg.appendChild(circle);

  circle.addEventListener('contextmenu', function(event) {
    circle.remove(circle.id);
    event.preventDefault();
  });
}

And here is my ajax

var nah = JSON.stringify(points);
function onBtnClick(event){
      alert(point);
      $.ajax( {
        url:"../php/points.php",
        method:'POST',
        data:{ body:nah},
        success: function(response){
            window.location = "../php/points.php";
        }

    })

    }

you've to send values and not objects. JavaScript objects can't exist outside JavaScript , so are Arrays(who're Objects as well or rather Function who is constructor(mother or parent class in OOP) of all Object) or at least convert them to string PHP can read to convert in a PHP Object. AJAX is meant to use XML earlier, you can use as JSon who is a literal(meaning string) and can be used as meta-datas. You can do the 1st way by a loop on Objects paar key/value or (second way) by using .toString() and for the third idea you've to create a temporary .json file(or XML if you prefer). Another way could be create an HTML form and use it(forcing the submit in code), so you'll get POST/GET global values directly in the PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM