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]); }); 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. 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 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); 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. 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. 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
Archived
This topic is now archived and is closed to further replies.