Jump to content

Archived

This topic is now archived and is closed to further replies.

Solarpitch

Return an array to Ajax success with PHP

Recommended Posts

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]

Share this post


Link to post
Share on other sites

Hi,

 

Just tried that there and it's still displaying as undefined.

Share this post


Link to post
Share on other sites

This is what I have..

 


	$test = array( "Paul", "Mike");

	return json_encode($test);

Share this post


Link to post
Share on other sites

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))

Share this post


Link to post
Share on other sites

Thanks, but neither work. Still coming up as undefined. I'm puzzled with this one.  :confused:

Share this post


Link to post
Share on other sites

Please change "return" to "echo" or "print".

 

Example:

echo jeson_encode($test);

 

Thanks!

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites

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!

 

 

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.