Solarpitch Posted May 14, 2011 Share Posted May 14, 2011 Hi Guys, I'm trying the following.. returning an array from a php function to Ajax success but the alert seems to only display undefined. PHP public function reply() { $item_id = $this->uri->segment(3); $type = $this->uri->segment(4); if($type == 1){ $data['get_news_item'] = $this->Newsletter_model->get_news_item($item_id); $test = array( "Paul", "Mike"); return $test; } } AJAX $.ajax({ type: "POST", url: "<?php echo site_url(); ?>newsletter/reply/"+id+"/"+type, cache: false, success: function (data){ alert(data[0]); // So this should display "Paul"? }); [/code] Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted May 14, 2011 Share Posted May 14, 2011 You need encode the array you're sending to your AJAX script as json. Use json_encode. Quote Link to comment Share on other sites More sharing options...
Solarpitch Posted May 14, 2011 Author Share Posted May 14, 2011 Hi, Just tried that there and it's still displaying as undefined. Quote Link to comment Share on other sites More sharing options...
Solarpitch Posted May 14, 2011 Author Share Posted May 14, 2011 This is what I have.. $test = array( "Paul", "Mike"); return json_encode($test); Quote Link to comment Share on other sites More sharing options...
Zane Posted May 14, 2011 Share Posted May 14, 2011 do you still have this alert(data[0]) That zero shouldn't be there anymore... nor the brackets. Well...maybe try alert(data.0) since it's json encoded. Or you might have to eval it. alert(eval(data)) Quote Link to comment Share on other sites More sharing options...
Solarpitch Posted May 14, 2011 Author Share Posted May 14, 2011 Thanks, but neither work. Still coming up as undefined. I'm puzzled with this one. Quote Link to comment Share on other sites More sharing options...
anupamsaha Posted May 14, 2011 Share Posted May 14, 2011 Please change "return" to "echo" or "print". Example: echo jeson_encode($test); Thanks! Quote Link to comment Share on other sites More sharing options...
Solarpitch Posted May 14, 2011 Author Share Posted May 14, 2011 Ah ok, So I changed to echo and I seem to be getting something through now. The data is coming through as "Paul, Mike" using alert(eval(data)); Is this correct? .. Should I not be able to go alert(data[0]) or similar to get the individual values? Quote Link to comment Share on other sites More sharing options...
anupamsaha Posted May 14, 2011 Share Posted May 14, 2011 In your Ajax construct, add dataType: 'json'. This will enable jQuery to understand the data type that coming from the script. Or you can use $.getJSON instead of $.ajax. See http://api.jquery.com/jQuery.getJSON/ for more help. Then, you can get the data like: data.0 data.1 and so on. Thanks! Quote Link to comment 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.