-1

I'm trying to send back a string equation, for example "3+3", but when PHP receives it, it appears as "3 3" instead. Somewhere along the line, the operators are getting erased.

function sendEquation() {
    let str = document.querySelector(".equation").innerText;
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        document.querySelector(".equation").innerHTML = this.responseText;
        }
    };
    xhr.open("GET", "Scripts/Maths.php?q=" + str, true);
    xhr.send();
  }

I think it might be getting lost in this code. If my assumption is right, how do I stop javascript from interpreting the value I want it to store and just send me the string as it's written?

1
  • You need to encode + or it'll be converted to an space: xhr.open("GET", "Scripts/Maths.php?q=" + encodeURIComponent(str), true); Commented Apr 23, 2020 at 18:21

1 Answer 1

0

The + means something in URL syntax, so you have to encode it:

xhr.open("GET", "Scripts/Maths.php?q=" + encodeURIComponent(str), true);

The encodeURIComponent() function will turn + into %2B. That should be properly decoded at the server.

(Specifically, + stands for a space character, as you've discovered.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! This fixed everything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.