Solarpitch Posted November 4, 2012 Share Posted November 4, 2012 Hey Guys, Just trying to pass a php array to a Javascript function but I keep getting undefined. I'm sure my syntax is slightly incorrect. PHP ... $arr = array(); $arr[0] = $this->load->view('video',); $arr[1] = "A String"; return json_encode($arr); // this returns to the below Javascript $.POST responce. Javascript ... $.post('http://mysite.com//api/ajaxApiCall', 'val=' + val, function (response) { alert(response[0]); alert(response[1]); }); Quote Link to comment https://forums.phpfreaks.com/topic/270276-passing-a-php-array-to-javascript/ Share on other sites More sharing options...
awjudd Posted November 4, 2012 Share Posted November 4, 2012 You need to JSON.parse the array coming back. It reads in from the AJAX call a string, so it doesn't know that it is actually supposed to be an array. Quote Link to comment https://forums.phpfreaks.com/topic/270276-passing-a-php-array-to-javascript/#findComment-1390114 Share on other sites More sharing options...
Solarpitch Posted November 4, 2012 Author Share Posted November 4, 2012 (edited) When I try do that: obj = JSON.parse(response); alert(obj.count); I just get this error. Dunno why :-\ SyntaxError: JSON.parse: unexpected end of data obj = JSON.parse(response); Edited November 4, 2012 by Solarpitch Quote Link to comment https://forums.phpfreaks.com/topic/270276-passing-a-php-array-to-javascript/#findComment-1390203 Share on other sites More sharing options...
Solarpitch Posted November 4, 2012 Author Share Posted November 4, 2012 It actually works when I replace the return with echo. Quote Link to comment https://forums.phpfreaks.com/topic/270276-passing-a-php-array-to-javascript/#findComment-1390220 Share on other sites More sharing options...
trq Posted November 5, 2012 Share Posted November 5, 2012 Funny that. Quote Link to comment https://forums.phpfreaks.com/topic/270276-passing-a-php-array-to-javascript/#findComment-1390243 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.