0

I am trying to send javascript array to php via ajax, but it is not sending, here is my code

var ArrayAmounts = new Array();
ArrayAmounts["P1"] = "16150";

$.ajax({
    url:"myajax",
    cache:'false',
    type:'POST',
    data:{Arr:ArrayAmounts},
    success: function(data){
        console.log(data);
    },error: function(xhr, AjaxOptions, ThrownError){
        ShowMessage(xhr.responseText);
    }
});

but when I am making array like this:

 var ArrayAmounts = new Array();
 ArrayAmounts[0] = "16150";

it is passing the array, but I want the key as alphanumeric. please help.

2
  • its an array not an object if you assing to it index it will happen.i think you need object literals Commented Jan 4, 2018 at 9:47
  • 2
    use an object if you want keys to be alphanumeric Commented Jan 4, 2018 at 9:48

4 Answers 4

5

So you don't need an array here, you'll need to use an object like this :

var Amounts = {};
Amounts["P1"] = "16150";

$.ajax({
    url:"myajax",
    cache:'false',
    type:'POST',
    data:{Arr: Amounts},
    success: function(data){
        console.log(data);
    },error: function(xhr, AjaxOptions, ThrownError){
        ShowMessage(xhr.responseText);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

should be data : { Arr : Amounts }, not data : { Arr : ArrayAmounts }, or even simpler, data : Amounts, but yes, that's the way to go
@JeremyThille Done, Rohit did it.
0

Your problem is related to the kind of data you are sending because as the documentation says:

"It is converted to a query string, if not already a string. It's appended to the url for GET-requests. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting"

Official documentation for more details

Comments

0

you can declare the array like this: var ArrayAmounts = new Array(); ArrayAmounts = ["16150"]; and then your ajax call work normally

Comments

0

Use like this

var ArrayAmounts = {};
ArrayAmounts.P1 = "16150";

var dataArray = {Arr: ArrayAmounts};

$.ajax({
  url:"myajax",
  cache:'false',
  type:'POST',
  data: dataArray ,
  success: function(data){
    console.log(data);
  },error: function(xhr, AjaxOptions, ThrownError){
    ShowMessage(xhr.responseText);
 });

1 Comment

same as Serge K. ans

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.