JQuery - Pass twodim array to $.post fails

In a function I create an array and try to post that, using jQuery.post - but the array are never posted.

The array "recipients" are filled with data collected from ".smstag" and then I am trying to post the array to my server, the server actually only responds with a json-encoded array of $_POST.

I console.log "recipients" before posting and see 3 recipients, when the $.post succeedes I console.log(json) and see only the "smsmsg" variable - it looks like I never posted recipients.

(3) [Array(0), Array(0), Array(0)]
0
:
[cellphone: "+4588888888", username: "Mark", id: "5"]
1
:
[cellphone: "+4588888888", username: "Marie", id: "227"]
2
:
[cellphone: "+4588888888", username: "Marie", id: "129"]
length
:
3
__proto__
:
Array(0)

function sendSms(){
  if($("#smsrecipients").find(".smstag").length==0)return;
  if($("#smsmsg").val().length==0)return;
  var recipients=[];
  $("#smsrecipients").find(".smstag").each(function(){
    var u=[];
    u["cellphone"]=$(this).attr("cellphone");
    u["username"]=$(this).attr("username");
    u["id"]=$(this).attr("userid");
    recipients.push( u );
  });
  swal({
  title: '<?php echo _t("Send message now?")?>',
  type: 'question',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: '<?php echo _t("Yes, send it!")?>',
  cancelButtonText: '<?php echo _t("Cancel")?>',
  showLoaderOnConfirm : true,
}).then((result) => {
  console.log(recipients);
  $.post("/ajax/sendsms",{"recipients":recipients,"smsmsg":$("#smsmsg").val()},function(json){
    if(json.success){
      console.log(json);
      return true;
    }
  },"json");
})
}

The JSON result returned from the server :

{success: true, post: {…}}
post
:
smsmsg
:
"Kære #name#↵Du får lige en testbesked!!↵Dette er lige skrevet!!"
__proto__
:
Object
success
:
true
__proto__
:
Object

I can't figure out where I'm going wrong, any help will be appreciated very much!

Best regards, Mark

1 answer

  • answered 2018-01-14 12:42 charlietfl

    javascript arrays are numerically indexed only

    You are trying to use u as an object so make it an object literal to begin with instead of an array

    Change var u=[]; to var u={};