Jump to content

Return an array to Ajax success with PHP


Solarpitch

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]

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?

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!

 

 

Archived

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

×
×
  • 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.