Reputation: 209
How can i pass an array with ajax? My code in view:
$(document).ready(function(){
$('#btn-send').click(function(){
var value = {
'name': $('#name').val(),
'phone': $('#phone').val(),
'mail': $('#mail').val(),
};
$.ajax({
type: 'POST',
url: '<?php echo site_url('customer_add/test'); ?>',
data: value,
success: function(resp){
$('#error').html(resp);
}
});
});
});
My test method:
public function test5(){
$data = $this->input->post["value"];
$name = $data['name'];
echo $name;
}
In params - in the inspect element - there are data but in response, there's nothing to return. What's wrong? Thank's in advance.
Upvotes: 1
Views: 4843
Reputation: 952
First, you can handle your error at the error section of $.ajax
by error: function(xhr) {},
$.ajax({
type: 'POST',
url: '<?php echo site_url('customer_add/test'); ?>',
data: {
name: $('#name').val(),
phone: $('#phone').val(),
mail: $('#mail').val()
},
error: function(xhr) {
alert('error');
},
success: function(resp){
$('#error').html(resp);
}
});
Next, type: 'POST'
means the form would post the fields out by the method POST
.
So that we can catch them by $_REQUEST
or $_POST
.
In Codeigniter, the way to catch the posted fields is $this->input->post('name');
.
There's an error in your syntax.
public function test5(){
$data['name'] = $this->input->post('name');
$data['phone'] = $this->input->post('phone');
$data['mail'] = $this->input->post('mail');
echo $data;
}
Hope it would be help.
Upvotes: 1
Reputation: 101
You send data through ajax and you create a array of value with key:value pair when data send to server using post so you can get this whole array in one single variable using.
public function test5(){
$data = $this->input->post();
$name = $data['name']; echo $name;
$phone = $data['phone']; echo $phone;
$mail = $data['mail']; echo $mail;
}
you dont have to mention value key in $data = $this->input->post["value"];
and the second thing
you are writing wrong syntax $this->input->post["value"];
the write syntax is $this->input->post("value");
but in $this->input->post("value"); case you cant get value because there is no key with value name.
Upvotes: 0