Home > OS >  Passing JavaScript array with multiple values to PHP via ajax
Passing JavaScript array with multiple values to PHP via ajax

Time:10-21

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

CodePudding user response:

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=["math","geograph"]

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related