I have an javascript array variable in my view file , how can i send the array to different controller ?
this is html code:
<button id=<?php echo $key ?> onclick="movebutton(this)" class='li'><?php echo $officers['Officer']['name'] ?> </button>
and this is my javascript code:
function movebutton(elem){
var teamMember=new Array();
if( $(elem).parent().attr("class") == "officers_list" ){
$(elem).detach().appendTo('.add_member');
teamMember.push($(elem));
}
else{
$(elem).detach().appendTo('.officers_list');
teamMember.pop($(elem));
}
You can pass any data to controller using ajax -:
Get values you want to a javascript variable and check a sample ajax
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array(
'controller'=>'controller','action'=>'action'));?>',
data: ({type:variable-value }),
success: function (data){
return true;
// $("#div").html(data);
}
});
To pass data from view to controller:
You can use form but in form your data won't be sent as an array
Using ajax
.
var data = {
val1 = '<?php echo $string ?>';
val2 = '<?php echo $number ?>';
}
$.post( 'controller/action', data , function(response) {
if (response == true) {
// Do this
} else {
// Do that
}
});
Related
I am trying to get data from one php page and pass it to another page using Ajax.
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id=data"
}
});
action.php :
<?php
$test= 1;
?>
data.php :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
<?php
$id = $_GET['id'];
echo $id;
?>
First of all, you need to echo your data in action.php, and second, use data parameter of AJAX request to send data to data.php.
Here's the reference:
jQuery.ajax()
So the organization of pages should be like this:
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php",
data: {id: data},
success: function(data){
// your code
// alert(data);
}
});
}
});
action.php :
<?php
$test = 1;
echo $test;
?>
data.php :
<?php
$id = $_GET['id'];
echo $id;
?>
Try to use $.get() method to get/send data :
$.get("action.php",{}, function(data){
//data here contain 1
$.get("data.php", {id: data}, function(id){
alert(id);
}
});
Just echo $test since just the data printed in page will return as responce to the query request.
action.php :
<?php
$test=1;
echo $test;
?>
Hope this helps.
For example,
Test
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
action.js
$('.dataClass').click(function(){
var value=$(this).attr('data-value');
$.ajax({url:"Ajax_SomePage.php?value="+value,cache:false,success:function(result){
alert("success");
}});
});
Ajax_SomePage.php
<?php
$value = $_GET['value'];
echo $value;
?>
To get data as response in ajax call, you need to echo the result from your php page; action.php page.
echo $test = 1;
In your provided code
$.ajax({
url: "data.php?id=data"
} // closing bracket is missing
you are sending the string data as id to data.php page. Instead you have to append the result with the url using + symbol like shown in the below code.
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id="+data
})
}
});
I'm using json to post data to controller but i can't do some effects if data is inserted to database successfully,
This if statement does not work in this javascript code ?
I mean .like-btn .html() does not work but data inserted in database ?
My experience in Javascript between 0 and 10 :D
Using Codeigniter 3.0.3
Here's my javascript
<script type="text/javascript">
$(document).ready(function() {
$(".like-btn").click(function(event) {
var liker_id = "<?php echo $this->session->userdata('id'); ?>";
var post_id = $(this).attr('post-id');
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('home/AddLike'); ?>",
dataType: 'json',
data: {liker_id: liker_id, post_id: post_id},
success: function(res) {
if (res)
{
$('.like-btn[post-id = '+post_id+']').html('<span class="fa fa-check"></span> Liked');
}
}
});
});
});
</script>
Here's my controller
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
}
And here's my model method
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
return true;
}
}
Just change below on your model:
change return to echo
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
echo true;
}
}
You should debug your code of ajax response. And you should check whether you are getting any response in res variable.
Important
1)In if condition you should use double quotes("") to wrap variable post_id like
$('.like-btn[post-id = "'+post_id+'"]').html...
2) Another thing is you should return "true" as string not as boolean and check with string in ajax success block.
Solved add this line at the end of controller method
echo true;
code after edit
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
echo true;
}
Hi I pass an array from php to another to used it on a javascript function using json, but not return nothing, gives me "null" all time.
php code
function getParents($id_child){
include "conexion.php";
$query = $conexion->query('SELECT person_id FROM children WHERE children_id='.$id_child.';');
$query->execute();
while ($res = $query->fetch()) {
$id_parents[] = $res[0]; //family_id
}
return $id_parents;
echo json_encode($id_parents);
}
getParents($_POST['id_child']);
Php who takes the json:
<?php
$json_data=json_encode($id_parents);
?>
function sacarPadres(id_child){
$.ajax({
data: {"id_child" : id_child,
},
url: 'php/functions_sql.php',
type: 'post',
success: function(output) {
}
});
var an_obj= "<?php echo $json_data;?>";
alert(an_obj); // always null
}
<div id="form">
<FORM NAME=form1>
<INPUT TYPE='button' NAME='myFamily' value='add new family' onclick="sacarPadres(70);">
</FORM>
After return type everything is vanish
just remove return type
//return $id_parents;
echo json_encode($id_parents);
Updated
function getParents($id_child){
include "conexion.php";
$query = $conexion->query('SELECT person_id FROM children WHERE children_id='.$id_child.';');
$query->execute();
while ($res = $query->fetch()) {
$id_parents[] = $res[0]; //family_id
}
return json_encode($id_parents);
}
echo $val=getParents($_POST['id_child']);
Ajax
$.ajax({
data: {"id_child" : id_child,
},
url: 'php/functions_sql.php',
type: 'post',
success: function(output) {
alert(output);//alert here
}
});
The return statement causes the program to exit the function. All statements after return will not be executed. Move return to the end of the function or remove at all.
I am trying to let jQuery dynamically add html to my page. Unfortunately, I don't receive a response from my server. My JS code sends a GET request, which contains a parameter (bodypart). The server should return a response including the results from the database, but the response is empty.
What causes this problem?
JAVASCRIPT:
function getData() {
var sPanelHeading = '<div class="col-lg-3"><div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">Symptomen van ' + bodypart + '</h3></div>';
$( "#abc" ).append(sPanelHeading);
$.ajax({
url: 'controller.php',
data: 'bodypart=Autism',
dataType: 'json',
}).done(function(data) {
$( "#abc" ).append('<div class="panel-body" style="overflow-y: scroll;"><span class="list-group-item"><b>Vaak voorkomende symptomen</b></span></div><div class="list-group">');
for (var c in data) {
$("#abc").append('<span class="list-group-item">');
$("#abc").append(c);
$("#abc").append('</span">');
}
}).always(function(data) {
console.log(data);
});
}
PHP:
<?php
require_once( 'config.php' );
$bodypart = $_GET['bodypart'];
$sql = "SELECT c_name FROM condition WHERE c_name = '$bodypart'";
$result = $conn->query($sql);
$json_response = array();
if ($result->num_rows > 0) {
while($row = mysql_fetch_assoc($query)) {
$json_response[] = $row;
}
print json_encode($json_response);
}
$conn->close();
?>
1st : instead of
data: 'bodypart=Autism',
use
data: {'bodypart':'Autism'},
2nd
echo json_encode($json_response);
Basics of $.ajax
$.ajax({
url: 'controller.php',
type: 'GET',
data: {'bodypart':'Autism'},
dataType: 'json',
success : function(data){
alert(data);
}
});
in php
<?php
$bodypart = $_GET['bodypart'];
echo $bodypart;
?>
output should alert Autism .. if this Ok you can complete your stuff .. if something went wrong .. check your php file path
i am trying to get a row of data from database using ajax in codeigniter.
Here is the javascript function-
$(function(){
$("button[name='program_view_details']").click(function(e){
e.preventDefault();
var program_id=$(this).attr('id');
$.ajax({
url: "<?php echo base_url();?>program_management/get_program_data",
type: "POST",
dataType: "html",
data: "program_id="+program_id,
success: function(row)
{
alert(row.program_name);
}
});
});
I am not sure if the datatype and post is correct or not.
Here is my controller function-
public function get_program_data( ){
$program_id = $this->input->post('program_id');
$this->load->model('program_management_model');
$data['programs']= $this->program_management_model->get_program_specific($program_id);
echo $data;
}
Here is the model-
function get_program_specific($program_id){
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
return $query->result();
}
I am searching the way of returning the row from controller to javascript. But the alert() is showing "undefined" in the success. Please anyone tell me the whole way through. Thanks in advance.
$data['programs']= $this->program_management_model->get_program_specific($program_id);
The $data which you are echoing in the controller is basically an array[] and programs is an array which is present in $data. Either echo the $data in controller using the
foreach(){}
or echo the $query array in your model. That will do the trick.And in ajax success call just append the data to the element in which you want to show the result.
Change names as per your page.
in your script:
$.ajax({
url: '<?php echo base_url();?>managealerts_edit/editalerts',
type: "POST",
data: {'id': edit_id},
cache: false,
dataType: "json",
success: function(row){
//alert(row.sub);
$('#edit').show();
$('#sub').val(row.sub);
$('#mess').val(row.mess);
}
});
in your model:
$query = $this->db->query("SELECT fld_id, fld_course_id,fld_sub,fld_mess from tbl_alerts where fld_id='".$det."' ");
if ($query->num_rows() > 0)
{
$row = $query->row_array();
$data=array("sub" => $row['fld_sub'], "mess" => $row['fld_mess']);
echo json_encode($data);
}
in your controller:
$det = $this->input->post('id');
//$alertsres['tbl_alerts'] = $this->managealerts_m->select_editalerts($det);
$this->managealerts_m->select_editalerts($det);`
in model
function get_program_specific($program_id){
$temp=array();
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
$temp= $query->row_array();
echo $temp['program_name'];
}
in controller change the line
$data['programs']= $this->program_management_model->get_program_specific($program_id);
with
$this->program_management_model->get_program_specific($program_id);
and finally in javascript
alert(row);
please let me know if you face any problem.