0

My current project is passing multiple values to php via ajax and I want to add an array together but I failed to do so.

current JS file:

var name= 'John';
var age= 21;
var gender = 'm';

var postData = 'name='+name+'&age='+age+'&gender=gender';

$.ajax({
      type:'POST',
      dataType:'json',
      url:baseUrl+'/student',
      data:postData,
    }).done(function (data){
        alert('success');
      }
   });

What I want to add:

var subject = ["math","geograph"];
JSON.stringify(subject ); //to encode the array

I have tried:

var postData = 'name='+name+'&age='+age+'&gender='+gender+'&subject='subject';

and

data:{subject : subject , postData : postData},

and I get this array in php:

$subject = json_decode($request['subject']),true);

But I can't get the array in my php. How can I solve this problem? Thanks

0

3 Answers 3

4

You'll need to url-encode the JSON string to make it compatible with the application/x-www-form-urlencoded request you're sending.

Fortunately, jQuery is able to do this for you if you pass it an object of data values.

const name = "John";
const age = 21;
const gender = "m";
const subject = ["math", "geograph"];

$.ajax({
  url: `${baseUrl}/student`,
  method: "POST",
  dataType: "json",
  data: {
    name,
    age,
    gender,
    subject: JSON.stringify(subject),
  }
})

This will produce the following request body

name=John&age=21&gender=m&subject=%5B%22math%22%2C%22geograph%22%5D

On the PHP side you can continue to use...

$subject = json_decode($_POST['subject'], true);

As indicated in the comments below, you can also skip the JSON encoding in which case jQuery will send multiple fields named subject[] so your PHP would have to change to

$subject = $_POST['subject']; // will be an array
Sign up to request clarification or add additional context in comments.

4 Comments

Why bother to json encode subject? You can just use data: { name, age, gender, subject } and $_POST['subject'] will be an array with values math and geograph
If you send data as data: { name, age, gender, subject } it will just be $_POST['subject'].
@Nick right you are, sorry. Can you tell I don't use PHP any more 🤦
Lucky you! :) :)
1

The result of JSON.stringify(subject) is still an array

var subject = ["math","geograph"];
console.log(JSON.stringify(subject )); 

Besides Phil's answer, one option is to using join() to do it

var name= 'John';
var age= 21;
var gender = 'm';

var subject = ["math","geograph"];
var subjects = subject.join(",");
var postData = 'name='+name+'&age='+age+'&gender='+gender+'&subjects='+subjects;
console.log(postData);
// in server side,we can using split() to convert subjects to an array

1 Comment

OP would need to use different PHP code in this case... $subject = explode(',', $_POST['subject'])
-1

What you need to do is converting the data from object to string by using the JSON.stringify like:

var name= 'John'; 
var age= 21;
var gender = 'm';
var subject = ["math","geograph"];

var postData = { name: name, age: age, gender: gender, subject: subject};


$.ajax({
  type:'POST',
  dataType:'json',
  url:baseUrl+'/student',
  data: JSON.stringify(postData), // or JSON.stringify({name, age, gender, subject }),
  // or
  // data: JSON.stringify({ postData, subject }),
}).done(function (data){
    alert('success');
  }
});

then use json_decode in php.

1 Comment

This will send a JSON string with content-type application/x-www-form-urlencoded which is a mismatch and won't be parseable on the server-side

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.