Reputation: 41
I am sending an array in php (converted from a string using explode), to a seperate javascript page. I was wondering how do I get into the javascript array and actually retrieve data values.
array in javascript (from php file)-
array(2) {
[0]=>
string(2) "30"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(2) "30"
[1]=>
string(0) ""
}
Here is the ajax call on the javascript page -
$.ajax({
url: "GetTest.php",
type: "POST",
success: function(data){
alert("success");
console.log(data);
},
error: function(data){
alert('failure');
}
});
on the php page -
var_dump((explode(',', $something));
How do I get in here and pull out the "30" value. I am using an ajax call to get this data, and then putting placing this array in a variable called "data", but if I do something like data[0], I get the letter "a" as a response. Any help towards this will be greatly appreciated. Thanks,
Upvotes: 0
Views: 367
Reputation: 2164
If you are returning the array itself, it will not be converted to a JavaScript object. I believe you will just get the string "Array". What you need to do is call json_encode($your_array)
to convert the array to a JavaScript object. Then, PHP will return a JavaScript object that looks like this:
{
"0": "30",
"1": ""
}
You can then call JSON.parse on the response and access the data in that object as you would any other JavaScript object.
Note: If you are using PHP < 5.2 and do not have the JSON PECL extension installed, the json_encode()
function will not be available, and you will need to either write a function to convert an array to JSON or find one that someone else has written.
Upvotes: 3
Reputation: 76433
In pure javascript:
xhr.onreadystatechange = function()//where xhr is your request object
{
if (this.readyState === 4 && this.status === 200)
{
var yourArray = JSON.parse(this.responseText);
console.log(yourArray);//logs the array above, normally
}
};
Be aware that IE, prior to 9 at least, does not come with JSON support as standard, in which case, just google JSON.js and include it in the header.
Also make sure that the array you send is json_encode
'ed before you echo it.
Looking at the code you added, I'd say: replace the var_dump by echo json_encode(explode(',',$someString));
and you're all set
Upvotes: 0
Reputation: 4229
A JavaScript array should look like this...
var myArray = ["30", "0"];
You probably have a string instead of an array if you get an 'a' at index 0.
"array"[0] === "a"
So you need to fix your client side array first.
Upvotes: 0