Reputation: 2985
I am trying to make an array which then contains mutiple arrays (which are added in the each loop) and then pass the information to ajax to post off.
However, it won't add to the request, and when I try JSON.Stringify on the array, it just returns empty.
What am i doing wrong?
Thanks!
var graphics = new Array();
var customer = "Joe Bloggs";
var email = "[email protected]";
var contactnumber = "12345";
$('.graphic').each(function (i) {
var graphic = new Array();
graphic['name'] = $(this).attr('data-name');
graphic['type'] = $(this).attr('data-type');
graphic['price'] = $(this).attr('data-price');
graphic['model'] = $(this).attr('data-model');
graphic['carcolor'] = $(this).attr('data-carcolor');
graphic['graphiccolor'] = $(this).attr('data-color');
graphic['reg'] = $(this).attr('data-reg');
graphic['note'] = $(this).attr('data-note');
graphics.push(graphic);
});
$.ajax({
type: "POST",
data: {
customer:customer,
email:email,
contactnumber:contactnumber,
graphics:graphics
},
url: "assets/php/index.php",
success: function(msg){
$('.answer').html(msg);
}
});
Upvotes: 1
Views: 72
Reputation: 7310
It looks like you're used to PHP.
When you define an Array:
var graphic = new Array();
You need to treat it as an array:
graphic[0] = "foo";
graphic[1] = "bar";
...and not like an object:
var graphic = {};
graphic['my_property'] = "foobar"
When you do this:
var a = new Array();
a["something"] = 123;
Then a will be an empty array ([]
) but a.something
will contain 123
.
However when you want to stringify a
, and a
is an Array
, it will try to find a stringified representation of that array. And since it is empty, you get []
.
So in order to fix your problem, simply change graphic
so that it is an object. Note that you end up with an array of objects, not an array of arrays.
Upvotes: 2
Reputation: 95027
graphic
inside the .each
is an array, however you are treating it as if it were an object. simply change new Array()
to {}
and it will be more correct, however, still not in an acceptable format. To post that correctly you will need to serialize it as JSON after that.
$('.graphic').each(function (i) {
var graphic = {};
graphic['name'] = $(this).attr('data-name');
graphic['type'] = $(this).attr('data-type');
graphic['price'] = $(this).attr('data-price');
graphic['model'] = $(this).attr('data-model');
graphic['carcolor'] = $(this).attr('data-carcolor');
graphic['graphiccolor'] = $(this).attr('data-color');
graphic['reg'] = $(this).attr('data-reg');
graphic['note'] = $(this).attr('data-note');
graphics.push(graphic);
});
$.ajax({
type: "POST",
data: {customer:customer, email:email, contactnumber:contactnumber, graphics:JSON.stringify(graphics)},
url: "assets/php/index.php",
success: function(msg){
$('.answer').html(msg);
}
});
Upvotes: 2