0

I am posting a multidimensional array from JS using Ajax call and I dont received it in PHP:

   $.ajax({
    type: 'post',
    url: 'external_submit.php',
    dataType: "json",
    data: {
      edit_rfid_changes_submit: edit_rfid_changes_submit,
      edited_rfid_arr: edited_rfid_arr
   }

I am 100% sure I have done this before and it always succeeded, why doesn't work this time is beyond me!

EDIT:

this is how I am creating the array:

  var edited_rfid_arr = [];
  for (var i = 0; i < input_fields.length; i++) {       
      let obj = [];
      let rfid = input_fields[i].value;
      let id = input_fields[i].attributes['data-rfid_id'].value;
      obj['rfid'] = rfid;
      obj['id'] = id;
      edited_rfid_arr.push(obj);      
  }
5
  • Show your PHP code. Commented Jan 14, 2021 at 21:30
  • 1
    Your value of edited_rfid_arr is not valid. In JS, you can only use key: value in objects, not arrays. It should be [{rfid: "45456", id: "69"}, ... Commented Jan 14, 2021 at 21:33
  • In PHP, you should then be able to access them as $_POST['edited_rfid_arr'][$i]['rfid'] and $_POST['edited_rfid_arr'][$i]['id'] Commented Jan 14, 2021 at 21:34
  • @Barmar pelase check the edited question, I mistakenly typed a wrong format of the array before. Now the question is corrected Commented Jan 14, 2021 at 21:39
  • 1
    Use let obj = {}. Commented Jan 14, 2021 at 21:40

1 Answer 1

1

You should make obj a plain object, not an array. Although you can add named properties to arrays (since arrays are just a kind of object), the properties are ignored when jQuery serializes the array.

So change the variable declaration to:

let obj = {};

Or you could get rid of the obj variable entirely, and just do:

edited_rfid_arr.push({rfid, id});

And you can get rid of the entire loop by using map():

var edited_rfid_arr = input_fields.map(field => 
    ({rfid: field.value, id: field.attributes['data-rfid_id'].value}));
Sign up to request clarification or add additional context in comments.

Comments

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.