1

In JS, I got:

var UserName;
var MyArray = new Array();

//...filling array

var rqst = new XMLHttpRequest();
rqst.open('POST',"Some.php",true);
rqst.setRequestHeader('Content-type', 'application/json');

What should I write to send UserName and MyArray to PHP file, so I can access them separately. Like:

$username = $_POST['JSUserName'];
$array = $_POST['JSArray'];
3
  • You can pass as an object. Commented Jul 25, 2019 at 1:33
  • you can either pass a query string on the send method or a FormData object Commented Jul 25, 2019 at 1:38
  • I know principes, I need the exact syntax. Commented Jul 25, 2019 at 2:10

2 Answers 2

1

As Freddie already stated, you want to define another object with both your UserName and MyArray values within it:

var params = {
  JSUserName: UserName,
  JSArray : myArray
};

Then, you can send the whole lot over to your server like so:

// This will send the request and yes, the object needs to be stringified!
rqst.send(JSON.stringify(params));

If you're interested in knowing whether or not the request was successful, you can add something like this as well:

// Alert if the call was successful
rqst.onreadystatechange = function () { 
    if (rqst.readyState != 4 || rqst.status != 200) return; 
        alert("Success: " + rqst.responseText); 
}; 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to combine them both into a single object and then pass this object in as part of the XHR call.

var params = {
  JSUserName: UserName,
  JSArray : myArray
};

1 Comment

I should then: ` rqst.send(params); ` or ` JSON.stringify(params); rqst.send(params); `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.