I used to create an array in js
var data = new Array();
data['id'] = self.iframeFields.id.val();
data['name'] = self.iframeFields.name.val();
data['location'] = self.iframeFields.location.val();
data['about'] = self.iframeFields.about.val();
data['company'] = self.iframeFields.company.val();
data['website'] = self.iframeFields.website.val();
but passing var data returns null value
but data['id'] return value.
What did I do wrong?
EDIT:
After nrabinowitz‘s answer, i was using
if ($.isArray( data )){
ajax({
url: myurl,
data: {
method: "updateProfile",
data: data
},
normalizeJSON: true,
success: function( response ){
// Check to see if the request was successful.
if (response.success){
alert(response);
} else if (onError){
// The call was not successful - call the error function.
alert(response);
}
}
});
}
as it is an object not an array,
it was not returning nothing,
Removing
if ($.isArray( data )){ }
solves the issue.
In Javascript, you want an object, not an array:
You’re expecting the array to work like an associative array in PHP, but Javascript arrays don’t work that way. I’m assuming you’re setting these values by key, and then trying to iterate through the array with something like a
forloop – but while you can set values by key, because in Javascript an array is just another object, these values won’t be available in standard array iteration, and the length of the array will still be 0.EDIT: You note that you’re using jQuery’s
.ajax()function to post the data to the server. The.ajax()method expects an object containing key/value pairs, and sends them to the server as a GET or POST parameters. So in your case, if you’re using an object as I describe above, your server will receive the parameters"id","name", etc in the$_POSTarray – not a"data"parameter.I suspect, though I haven’t tested this, that using
var data = new Array();wouldn’t work at all, because of the way jQuery serializes the data passed to.ajax()– even though an array is also an object, jQuery checks if it’s an array and treats it differently:So it wouldn’t use the key/value pairs you set at all – you would be passing an empty array and no parameters would be passed to the server.
So the right approach here:
var data = {};$_POST['id'],$_POST['name'], etc.