So basically I have a two item array in javascript that is generated based on which link the user clicks. I am trying to send this array to my controller, and then to the model. The model will look at the array and match one of the items to a certain column/row, and will selectively display data.
I am having issues passing the data from AJAX to my controller.
AJAX code (in a .js file)
$('#youmax-video-list-div').append('<div id="testing1"></div>');
$('#concept').click(function(){
console.log(course);
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data:'',
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
});
I am assuming I must do something with the data field, but I dont know the syntax for it.
The console log in chrome comes up with this:
Array[2]
0: "PL8G0kdHFfE3WuyevUDvwSYCZw8mp8LBFA"
1: "PL8G0kdHFfE3V62Jp2ju-PelOaNUkH7xR8"
Controller
function getValues(){
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}
As I said before, I am really only concerned with getting the data to my controller and my model.
The name of the array is "course". However, that doesnt appear to be so in the console.log. Is that just something chrome does?
// chkval be the class for elements for the arrays
AJAX function:
function ajaxSub(goals)
{
var theArray = new Array();
var i=0;
jQuery('.chkval').each(function(){
if(jQuery(this).prop('checked'))
{
theArray[i] = jQuery(this).val();
i++;
}
});
jQuery.ajax({
url: '<?php echo site_url('mycontroller/myfunctions');?>',
type: 'post',
data: {
arr: theArray,
other_id: ''
},
datatype: 'json',
success: function () {
}
});
}
in the controller:
$arr = $this->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}
Same as above answer but in controller run this code:
$arr = $this->input->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}
Related
I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}
I can't read the values send with ajax request, i don't know what im missing.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#send").click(function(e){
e.preventDefault();
var id = 5;
$.ajax({
type:'POST',
url:'/device/',
data:{id:id},
success:function(data){
console.log('Yes' + data);
}
});
});
in the controller device i just dump the input from the ajax call
$data = $request->all();
dd($data);
I can't see the value send via ajax in the console, i only see Yes but not the data.
What im missing ?
use the following line in your controller;
return $data; instead of dd($data);
Just Replace the + with , like below
console.log('Yes' , data);
try this in controller
public function store(Request $request) {
return Response::json($request->all(), 200);
}
dont forget to include
"use Response;
use Illuminate\Http\Request;"
Use This:
$("#send").click(function(e){
e.preventDefault();
var id = 5:
$.ajax({
type:'POST',
url:'{{url('/device')}}',
data:{
'ajax': 1,'id':id,'_token': {{csrf_token}}
},
success:function(data){
console.log('Yes'+data.id);
}
});
});
In the controller use:
public function name()
{
if(Input::get('ajax') == 1)
{
print_r('Ajax is working');die;
}
}
Also make sure, in the route you have post or any and not get for this route.
try this one.
in controller:
return $data;
And simply replace + with, like this:
console.log('Yes' , data);
I want to show tick.png image on clicking save button when data inserted in database successfully. My view file name is insert_your_committee, model is users_model & controller user
Here is my code of all there files:
My Script of my insert_your_commitee file, All console.log show correct result but success function is not working. What is the problem?
<script>
function save_committee($c_id,$m_id,$start_date){
console.log($c_id);
console.log($m_id);
console.log($start_date);
var mid=$('#irnum'+$start_date).val();
console.log("df"+mid);
var url= "<?php echo site_url("user").'/ref_add';?>";
$.ajax({
url: url,
type: "POST",
dataType:'json',
data: {c_id:$c_id,m_id:$m_id,start_date:$start_date,irnum:mid},
success: function(data){
console.log(data);
$('#'+$start_date).show();
$('#btn'+$start_date).hide();
}
});
}
</script>
My Controller
public function ref_add()
{
$this->load->model('Users_model');
$parms=$this->input->post();
$c_id=$this->input->post('c_id');
$m_id=$this->input->post('m_id');
$s_dateparms=$this->input->post('start_date');
$irnum=$this->input->post('irnum');
$data_to_store = array(
'Cid' =>$c_id,
'Mid' =>$m_id,
'Month' => $s_dateparms,
'Year'=>$s_dateparms,
'Ref_Number' =>$irnum,
);
$params=array();
if ($this->users_model->add_ref($data_to_store)) {
$params['status'] = TRUE;
} else {
$params['status'] = false;
}
$return["json"] = json_encode($params);
echo json_encode($return);
}
And Here is my model
function add_ref($data)
{
$this->db->insert('reference', $data);
$report = array();
$report['error'] = $this->db->_error_number();
$report['message'] = $this->db->_error_message();
if($report !== 0){
return true;
}else{
return false;
}
}
I am not completely sure, but in order to get ajax to work, I had to add return false; after the ajax call in the function.
In my case, I was using ajax for login and backend was in codeigniter.
So I am using AJAX to send an array to a controller
AJAX
$('#concept').click(function(){
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data: course,
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
alert("YEAH YOU WAS SUCCESSFUL");
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
course is an javascript array with two strings.
Controller
function getValues(){
$playlist = $this->input->post('course');
$this->load->model('get_db');
$data = $this->get_db->getAll($playlist);//$var inside ()
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}
Model
class Get_db extends CI_Model{
function getAll($pList){
$query=$this->db->query("SELECT * FROM questions WHERE playlistID= '$pList[0]' OR playlistID='$pList[1]'");
return $query->result();
}
}
I have done hardcoding and can confirm that the controller, and model functions work as they should. The problem lies with the 'data' parameter in the ajax I think. I just dont believe the data is being passed to the controller in the correct way. I have endlessly search other questions, and I know there are questions similar to it, but I havent found a solution in this case.
Thank you in advance for any information you can provide :)
You have to echo the JSON encoded data in the Controller instead of returning it. In the Ajax callback, you must then JSON.parse() the result before the $.each(..) call.
Controller
function getValues(){
$playlist = $this->input->post('course');
$this->load->model('get_db');
$data = $this->get_db->getAll($playlist);//$var inside ()
echo json_encode($data);
// $this->output->set_content_type('application/json');
// $this->output->set_output(json_encode($data));
// return $data;
}
Ajax-Call
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data: course,
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
var jsonData = JSON.parse(result);
$.each(jsonData, function(a, b){
htmlStr += b.qText + '<br />';
});
alert("YEAH YOU WAS SUCCESSFUL");
$('#testing1').append(htmlStr);
}
this is the method I want to send data to it
function get_lesson($reshte,$poodeman){
$this->load->model('dropdown_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->dropdown_model->get_lessons($reshte,$poodeman)));
}
and this is the get_lessens() function in the model file.
function get_lessons($reshte = null, $poodeman=NULL){
$this->db->select('rlessid, title');
if($reshte != NULL AND $poodeman!= NULL ){
$this->db->where('reshteid', $reshte);
$this->db->where('poodemanid', $poodeman);
}
$query = $this->db->get('tbllessons_root');
$lessons = array();
if($query->result()){
foreach ($query->result() as $lesson) {
$lessons[$lesson->rlessid] = $lesson->title;
}
return $lessons;
}else{
return FALSE;
}
}
and this is my ajax call at the view file
var reshteid = $('#reshte').val();
var poodemanid = $('#poodemanha').val();
$.ajax({
type:"POST",
url:"http://localhost/crud-grocery/index.php/examples/get_lesson/",//+reshte+"/"+poodeman,
data: "reshte="+reshteid+"&poodeman="+poodemanid,
success: function(lessons)
{
$.each(lessons,function(rlessid,title){
var opt = $('<option />');
opt.val(rlessid);
opt.text(title);
$('#lessons').append(opt);
});
}
});
as you see I am trying to chain options in the form
but The problem comes up when I try to post (send) two parameters to the controller method
any idea?
In your controller, you need to get POST values not as parameters:
//in controller
function get_lessons(){
...
//get POST values
$reshte = $this->input->post('reshte');
$poodeman = $this->input->post('poodeman');
You have to pass data as a javascript object literal:
...
data: {
reshte: reshteid,
poodeman: poodemanid
}
....