Reputation: 610
I'm trying to fill form fields from database via ajax jquery. I use Codeigniter. i can retrieve and alert database values to an array as this image. alert of the data array my problem is how to access this php array values via javascript? i want to fill form fields from this array using js. appreciate help :)
here is my Javascript
$("#header3").on("click", ".edit_button", function(e) {
var site_path = $('#sitePath').val();
e.preventDefault();
var clickedID = this.id.split('_'); //Split ID string
var DbNumberID = clickedID[1]; //and get number from array
var myData = DbNumberID; //build a post data structure
//getting data for the form from accuse table
$.ajax({
url:site_path +'/queries/get_data_form3',
method:'POST',
data:{myData:myData},
success:function(data12)
{
alert(data12);
}
,
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
})
});
here my controller code
public function get_data_form3(){
$insert_id = $this->input->post('myData');
$this->load->model('queries1');
if( $posts_form3= $this-> queries1 ->getPostsFor_form3i($insert_id) ) {
print_r($posts_form3);
}else{
echo "failed";
}
}
Upvotes: 2
Views: 1793
Reputation: 26258
Instead of print_r($posts_form3);
use:
echo json_encode($posts_form3);
from the get_data_form3(){
function and receive it in ajax like:
success:function(data12)
{
var data = JSON.parse(data12);
}
You can access all the element in data like:
data[0].column
or data[0][column]
Upvotes: 1
Reputation: 720
You need to pass data in JSON format for get data in ajax. Please replace you code with below code.
$("#header3").on("click", ".edit_button", function(e) {
var site_path = $('#sitePath').val();
e.preventDefault();
var clickedID = this.id.split('_'); //Split ID string
var DbNumberID = clickedID[1]; //and get number from array
var myData = DbNumberID; //build a post data structure
//getting data for the form from accuse table
$.ajax({
url:site_path +'/queries/get_data_form3',
method:'POST',
data:{myData:myData},
success:function(data12)
{
var getData = JSON.parse(data12);
console.log(getData);
}
,
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
})
});
And below php code.
public function get_data_form3(){
$insert_id = $this->input->post('myData');
$this->load->model('queries1');
if( $posts_form3= $this-> queries1 ->getPostsFor_form3i($insert_id) ) {
echo json_encode($posts_form3);
}else{
echo "failed";
}
}
Upvotes: 1
Reputation: 12085
Return the data like this on server side instead of print_r($posts_form3);
echo json_encode($posts_form3);
Access the data in client side like this
success:function(data12)
{
var datas = JSON.parse(data12);
console.log(datas[0]['name']);
}
Access the data like this
datas[0]['name']; datas[0]['address']; datas[0]['sex'];
Upvotes: 2