I am trying to update and get the updated row at a time from database in ajax call
JS in ready function
$("button[name='teacher_lock_exam']").on(ace.click_event, function () {
var current_exams_id = $(this).attr('id');
bootbox.confirm("Are you sure you want to lock the exam? <br/><br/>" +
"Locked exam cannot be modified until exam committee unlock it.", function (result) {
if (result) {
lock_exam(current_exams_id);
bootbox.alert("Your Exam has been Locked !<br/><br/> Contact with Exam committee to modify that exam again.");
}
});
});
function lock_exam(current_exams_id) {
$.ajax({
url: "teacher_internal_exam_management/lock_exam/" + current_exams_id,
type: "POST",
dataType: "json",
success: function (row) {
alert('success');
alert(row[0].access_status);
}
});
}
My teacher_internal_exam_management controller
public function lock_exam($current_exams_id)
{
$this->load->model('teacher_internal_exam_management_model');
$this->teacher_internal_exam_management_model->lock_exam($current_exams_id);
echo (json_encode($this->teacher_internal_exam_management_model->get_exam_details($current_exams_id)));
}
My teacher_internal_exam_management_model Model
function lock_exam($current_exam_id, $data)
{
$this->db->query("update current_exams set access_status = 'locked' where current_exams_id='".$current_exam_id."'");
}
function get_exam_details($exam_id)
{
$query = $this->db->query("select * from current_exams
where
current_exams_id = '" . $exam_id . "'
");
return $query->result();
}
Now the ajax call is updating the data but the row is not returned by the echo in the controller.Means the success function of ajax is not running. Why this is not working? Is there any problem in the code?
The very last line of your model:
return $query->result();
http://ellislab.com/codeigniter/user-guide/database/results.html
This function returns the query result as an array of objects, or an empty array on failure.
This is returning an array of objects.
You have to convert it appropriately -
return $query->result_array();
According to the php manual at http://www.php.net/manual/en/class.mysqli-result.php, I do not see a result() method for the type mysqli_result. I think you need to use
return $query->fetch_all();
instead of
return $query->result();
Related
I have a button Next that changes the page -
<a class="disabled" href="step">
<button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>
Also, when this button is clicked, I have an Ajax function that sends data to a controller function -
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: a,
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
And I'm using this to receive the value from Ajax -
public function CreateData() {
$data = $this->input->post('data');
return $data;
}
When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -
public function step()
{
$data = $this->CreateData();
if(!empty($data)){
print_r($data); exit;
}
else {
echo "blank"; exit;
}
$this->load->view('step2');
}
However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?
Your javascript should be something like this
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: {my_data: a},
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
Notice the data property. I have changed it to an object containing the variable a.
Now you should be able to retrieve this in your php function using
public function CreateData() {
$data = $this->input->post('my_data');
return $data;
}
Adr's answer solved part of the problem. In order to actually store and access the data, storing it in the session instead of a variable did the trick -
public function CreateData() {
$data = $this->input->post();
$this->session->unset_userdata('createData');
$this->session->set_userdata('createData', $data);
}
This prevented the $data variable from being overwritten when called the second time.
I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).
I need to get last insert id from controller to ajax success function......
I want to customize product and when user press add to cart ajax is executed and design is going to insert on database....
And after inserting in database i m getting last insert id.....on insert...
but need last insert id....when user press on add to cart button in hidden field...
here is my Ajax code.
$('#store').click(function(){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
//successfully added..here i am getting last insert id...
// and i want to pass that in hidden variable.....
// on view page.....
}
else {
document.getElementById('succes-message').innerHTML = 'You Design has not Been Saved';
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
});
my CI controller
public function saveData(){
if($this->input->post('action') == 'store') {
$views = $this->input->post('views');
$id = $this->product_model->save($views);
$data = array('cust_id'=>$id);
$this->session->set_userdata($data);
if($id !=''){
header('Content-Type: application/json');
echo json_encode($id);
}
}
}
$this->db->insert_id() returns the last id.
After your insertion operation in model, use following code
$this->db->insert_id();
this will give you id where last insert done.
Documentation
In my code I am returning an php array containing records of 7 Students. With jquery ajax() I want to print these records on success function.
DB table Students
+---------------------------+
| name | fathername | Email |
+---------------------------+
submit.php
$query=mysql_query("SELECT * from Students LIMIT 0,6");
$row= array();
$row=mysql_fetch_array($query);
return json_encode($row);
index.php
<script>
$(function(){
$("#form1").submit(function(event){
event.preventDefault();
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
$('.FatherName').text(result["fathername"]);
$('.Email').text(result["email"]);
});
}
});
});
});
</script>
<div class="StudentName"></div>
<div class="FatherName"></div>
<div class="Email"></div>
EDIT
I tried to return only 1 result from php and it works i.e.
echo json_encode(mysql_fetch_array($query));
When I return all 6 records the jquery function dont execute i.e.
while($result=mysql_fetch_array($query))
{
echo json_encode($result);
}
There's difference between PHP arrays and JS arrays, you can't simply pass the PHP array to your javascript, so instead you should first json_encode it and send it to js.
This will convert your PHP array to JSON array, eg:
array(3) {
[0]=>
string(3) "foo"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
to
string(33) "{"0":"foo","2":"baz","3":"blong"}"
So try -
return json_encode($row);
and then when you catch the response, use parseJSON:
result = jQuery.parseJSON(result);
$.each(result,function(){
$('.StudentName').text(result.name);
$('.FatherName').text(result.fathername);
$('.Email').text(result.email);
});
Edit:
Another thing, instead of return json_encode($row); write echo json_encode($row);
Edit 2
(to send all 6 records)
$final = array();
while($result=mysql_fetch_array($query))
{
array_push($final,$result);
}
echo $final;
function success(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
looks problematic. There doesn't really seem to be a reason to loop over the result, as you assign all of its contents to the same elements in the page.
However, assuming that result is an array of objects (like SQL queries usually produce it), then it should be
function(result){
$.each(result,function(obj) {
// missing parameter!!! ^^^
$('.StudentName').text(obj["name"]);
// access that here: ^^^
Also do a console.log(result) or simply browse the request URL to check whether the PHP scripts yields the expected response.
Here is an example of parsing JSON that may help you - http://jsfiddle.net/Su6QR/
Given that example, change your AJAX function -
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
var members = $.parseJSON(result);
$.each(members, function() {
var newStudent = '<span>' + this['name'] + '</span>';
var newFather = '<span>' + this['father'] + '</span>';
var newEmail = '<span>' + this['email'] + '</span>';
$('.StudentName').append(newStudent);
$('.FatherName').append(newFather);
$('.Email').append(newEmail);
});
}
});
This should return all of the data and place them into the divs that you have created. The formatting will not be what you want, but you should be able to fix that pretty easily.
This might help you.
Your AJAX
$("#form1").click( function(e){
var Somename = { };
$.each($('#form1').serializeArray(), function() {
Somename [this.name] = this.value;
});
e.preventDefault();
$.ajax({
type: "GET",
url: "submit.php",
data: { upddt_empID: upddt_empID, somevariable: "YES" },
success: function(data) {
alert('Successfull');
}
});
Your PHP
if(isset( $_REQUEST['somevariable'] ) )
{
$selItem = YourFunctionName( $_REQUEST['Somename ']['here your textbox id'], $_REQUEST['Somename ']['here your textbox id'],'yourtablename');
}
Your Query
function YourFunctionName(tablename)
{
$qry = "SELECT * FROM $tablename";
$result = mysql_query($qry);
return $result;
}
I want to populate my div minimal_table through ajax onchange event based on the chosen dropdown value. The <div class="minimal_table"> is the area of my page that I want to update every time I choose a value from my dropdown form. However, after my contents load, it returns no values from my database. I have checked the value being passed in my javascript using alert but it returns a right value. I also notice that it seems like it doesn't return true in the other_function.php if(isset($val_id))line even if I already chosen a value in the dropdown. Can somebody help me point out what is the wrong of my codes and what I am lacking? Thanks a lot. Here are my codes:
my_courses.php (ajax part)
$(':input').change(function(event){
event.preventDefault();
$('.minimal_table').html('<img src="../images/loading_trans.gif" style="position:relative; margin:350px; margin-top:250px;" />');
alert($(this).val());
var val_id = $(this).val();
var postData = {'val_id':val_id};
$.ajax({
url: "../includes/other_functions.php",
async: false,
type: "POST",
data: postData,
dataType: "html",
success: function(data){
setTimeout(function(){
$('.minimal_table').html(data);
},2000);
console.log(data);
},
});
});
other_functions.php
<?php
function ajax_request_val(){
$val_id = $_POST['val_id'];
$field = "course_type";
if(isset($val_id)){
$plans = db::getTable('plan',$field,$val_id);
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event',$field,$val_id);
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
else{
$plans = db::getTable('plan');
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event');
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
}
?>
databaseconnect.php
public static function getTable($tableName,$field='',$type_id='') {
if (!self::$db) self::connect();
if(!empty($type_id)){
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '` WHERE `'. $field .'` = `'. $type_id .'`;');
}
else{
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '`;');
}
}
Output:
Initial load
Loading the form dropdown menu search
Choosing value from dropdown returns right value indicated by an alert
After content load (returns no value on the div mini_table)
In other_functions.php you define the function ajax_request_val().
As far as I can see, there is no call to that function within the same file, so when you call it with Ajax, you just define the function and never call it.
You make an ajax call to other_functions.php but that file only contains a function that is never called.
There are lots of ways to approach this and tidy it up a bit but to fix the problem quickly you could try putting this at the top of other_functions.php:
if(isset($_POST['ajax'])){ echo ajax_request_val(); }
and then change the data in your ajax call as follows
var postData = {val_id:val_id, ajax:1 }