How to get a row from database using ajax in codeigniter - javascript

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.

Related

Ajax Post and retrieve multiple variables

I need help on how to post and retrieve multiple variables using Ajax Post. I actually needed to retrieve the posted variables for SQL query. See below the Ajax Code where i needed to include variable names selschool, selprogram, selsession to the post
<script>
$("#session").change(function()
{
$("#loding2").show();
var id=$(this).val();
var dataString = 'id='+ id;
var selschool=document.getElementById("selectedschool").val();
var selprogram=document.getElementById("selectedprogram").val();
var selsession=document.getElementById("selectedsession").val();
$("#semester").find('option').remove();
$("#class").find('option').remove();
document.getElementById("selectedclass").value= " ";
document.getElementById("selectedsemester").value= " ";
$.ajax
({
type: "POST",
url: "get_class.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding2").hide();
$("#class").html(html);
}
});
});
</script>
Also see below PHP script where i wanted to use the posted variable for the query;
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
// Todo: I actually needed something like where session SELECT * FROM class where session_id=$id and program_id="selprogram" and school_id="selschool"
$stmt = $DB_con->prepare("SELECT * FROM class where session_id=$id ");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select Class :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
}
?>
Let me explain the solution
consider the ajax call to demo.php
$.ajax({
url: 'demo.php',
type: 'post',
data: {
'name': 'abc',
'phone': '1234567899'
}, //data is in json form
success: function(res) {
console.log(JSON.parse(res)); //parsing because we will pass the data from demo.php in encoded form you will get it.
}
});
now in demo.php you will access data as $_POST['name'] and $_POST['phone']. lets pass the same to ajax call. will store it in array and will pass it.
<?php
$Arr = [];
$Arr[0] = $_POST['name'];
$Arr[1] = $_POST['phone'];
echo json_encode($Arr);
?>
like this, we can pass data to ajax and can pass the data from PHP file to request.
Hope that you got the result. Thank you.

for each ajax post to another file

So i have a for each function that prints the "local" column from this database:
https://i.imgur.com/IzKOzkt.png
It is working all good till here, this is what i get:
https://i.imgur.com/WH7d4uh.png
Now i want to send variables by post, when the user clicks on different menu items, i've tried everything, but i cant get it to work. Here is my code:
<?php
$query = "SELECT * FROM credenciais_sensores where ambiente = '1'";
$results = mysqli_query($conn, $query);
foreach ($results as $result){
$local = $result['local'];
$local = substr($local,0,7);
echo "<li><a class='clsPostData' data-oxiid='".$result['oxi_sensorid']."' data-oxikey='".$result['oxi_apikey']."' data-redoxid='".$result['redox_sensorid']."' data-redoxkey='".$result['redox_apikey']."' href='#'>".$local."</a></li>";
}
?>
This is working fine, the menu is being printed as i want, but now i cant get to post the data i want, like the "oxi_sensorid", etc... Here is my javascript:
<script type="text/javascript">
$(function(){
$('.clsPostData').click(function(e){
e.preventDefault();
var objPost = {};
objPost.oxiid = $(this).data('oxiid');
objPost.oxikey = $(this).data('oxikey');
objPost.redoxid = $(this).data('redoxid');
objPost.redoxkey = $(this).data('redoxkey');
$.ajax({
url: 'getObjects.php',
type: 'post',
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});
});
});
</script>
And my getObjects.php file:
<?php
$oxiid = $_POST["oxiid"];
$oxikey = $_POST["oxikey"];
$redoxid = $_POST["redoxid"];
$redoxkey = $_POST["redoxkey"];
$response["message"] = "Grettings from php, we receive your data: ".$oxiid . $oxikey . $redoxid . $redoxkey;
echo json_encode($response);
?>
But i'm always getting the popup saying "undefined" when i click on any menu item... Any help?
I think the problem there is you need to set the dataType to json. Try adding dataType: 'json' after type: 'post' on your ajax code:
$.ajax({
url: 'getObjects.php',
type: 'post',
dataType: 'json', // add this
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

Receive multiple value from php file via ajax call

Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.

how to capture array in ajax page when sent through JSON object

i am sending an array from one page to another through ajax.i used JSON object for this purpose.I am able to send but i am not able to capture in the ajax page.Please help me how to capture the array values.
javascript:
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "ajaxpage.php",
data: {data : jsonString},
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
PHP page:
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
please help me in this regard.
I am stuck up here
If you want to decode the JSON into an associative array, you should specify that in json_decode:
Replace
$data = json_decode(stripslashes($_POST['data']));
With
$data = json_decode(stripslashes($_POST['data']), true);
See json_decode reference for more information
Also, is dataString possibly already a JSON string?
I think this is what you want, I have tried and it works
in your php:
<?php
$data = ($_POST['data']);
foreach($data as $d){
echo stripslashes($d);
}
?>
in your jsvascript/jquery:
<script>
$(document).ready(function(){
$('a').on('click',function(){
var dataString = {
'id':'1',
'name':'peter parker',
'age':'unknown',
'role':'spiderman'
}
$.ajax({
url: "<?php echo $this->webroot;?>test_1.php",
data: {'data':dataString},
type: "POST",
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
})
})
</script>
in your html
Click Me
<div id="test"></div>

Categories

Resources