Sometimes you want to get PHP array values into JavaScript as an array. Mostly when you are using ajax. In Ajax, we pass PHP data into ajax request and multiple data generate as response which is in array But array format of PHP and JavaScript are different.
So, Today I am going to explain how you pass PHP data and convert into a JavaScript array.
So, Let’s understand code:
1 2 3 4 5 6 7 8 9 10 11 | //PHP $new_arr = array(); foreach($exist_array as $key =>$value) { $new_arr.='"'.$key.'":"'.$value.'",'; } $new_arr=substr($exist_array,0,-1); echo $new_arr="{".$new_arr."}"; |
Here, I have used foreach loop and convert into JavaScript json encode format.
Read: JavaScript Ticker for Database Values
1 2 3 4 5 6 7 8 9 | //Javascript var result_set=$.parseJSON(response); var result_array=[]; for(i in result_set){ result_array.push(result_set[i]); } |
Here, I have decoded JSON encoded values return in ajax response and generate the JavaScript array.
Read about: Convert 12-hour datetime to 24-hour datetime in JavaScript
you can check using $.isArray()
function,see
1 2 3 | console.log($.isArray(result_array)); |
we’re done.I hope that you like this trick.I’m hoping that you’ve found this tutorial useful.
Don’t hesitate to use this code and post your comments if you need help. As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (4)