I'm using codeigniter, I had a problem to process a data using jQuery $.post function. I want to send a value such as subjectid to ajax_get_subject_credit function and retrieve another field within same database table. The result shows on another text field. Here is my code.
View:
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(data){
$('#chours' + id).val(data); });
This get a value from drop-down and I want to make a text field automatic populate from drop-down. #chours is a text field ID.
Controller:
function ajax_get_subject_credit($result)
{
$this->db->select('subjectid, subjectcredit');
$query = $this->db->get('ref_subject');
$result = $query->result_array();
$query->free_result();
$subjectid = array();
foreach($result as $row)
{
$result = $result + array($row['subjectid'] => $row['subjectcredit']);
}
return $result;
}
Modified In Controller
I also tried using this statement in controller for direct calling the field but still no success :
function ajax_get_subject_credit($subjectid)
{
$this->db->select('subjectid, subjectcredit');
$this->db->where('subjectid',$subjectid);
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
echo $credithour;
}
I am going to provide a general example here
in view file
$.post('<?php echo site_url("test/test"); ?>', {'id':1}, function(response){
if(response.success)
{
alert(response.message);
} else
{
alert('Something went wrong!!');
}
}, 'json');
in controller Test.php
function test()
{
$id = $this->input->post('id');
//do additional stuff
$result = 'i am coming right out of controller!! ';
echo json_encode(array('success' => true, 'message' => $result));
}
Dont use return to return value to AJAX. use echo
change this,
return $result;
to
echo $result;
If you want your method to return an array that the javascript can use to populate a dropdown, you probably don't want to return a string.
Try something like this:
function ajax_get_subject_credit()
{
$query = $this->db->select('subjectid, subjectcredit')->get('ref_subject');
$result = $query->result();
$out = array();
foreach($result as $row) {
$out[$row->subjectid] = $row->subject_credit;
}
header('Content-Type: application/json');
echo json_encode($out);
}
This will return a JSON array to your view, which your javascript method can use to populate the dropdown with values and labels.
Here is my Result:
In View :
function subjectid_change(id, subjectid){
//Set value
setValue(id, subjectid);
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(response){
if(response.success)
{
$('#chours' + id).val(response.value);
} else
{
alert('Something went wrong!!');
}
}, 'json'); }
And my controller :
function ajax_get_subject_credit()
{
//Get Post Value
$subjectid = $this->input->post('subjectid');
//Select subjectid,subjectcredit FROM
$this->db->select('subjectid, subjectcredit');
//Where subjectid = 'subjectid'
$this->db->where('subjectid',$subjectid);
//Database name
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
$result = $credithour;
echo json_encode(array('success' => true, 'value' => $result));
}
Thanks to everybody who helped me.
Related
Alright, this is probably super simple but I've been breaking my head over this all day and I cannot get it to work.
I have a page that displays a list of users from a mysql query. On this page it should also be possible to add users. To do this, I'm sending an AJAX call to process.php which does some validation and sends an error if there is one. If there is no error, I want AJAX to update the page.
The problem is, that if there are no errors (a user has been added), I want to return the updated userlist. This means storing the output of my getUsers(); function in an array, which isn't possible.
How can I achieve this?
p.s. I realise this is crappy code and I should be using OOP/PDO, but this isn't for a production environment and it works. So I'll leave it like this for the time being.
users.php
<article>
<ul>
<?php getUsers(); ?>
</ul>
</article>
<form id="addUserForm">
...
<input type="hidden" name="addUser">
</form>
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if (response.success) {
$("article ul).html(response.data);
} else {
$(".errorMessage).html("<p>" + response.error + </p>");
}
}
});
});
functions.php
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
function addUser($email, $password)
{
global $db;
$result = mysqli_query($db, "INSERT INTO users ... ");
return $result
}
process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}
}
Your getUsers() function is printing and not returning the data to json connstructor
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
it has to be something like this
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
$list = "";
while($row = mysqli_fetch_assoc($query))
{
$list. = "<li>" . $row["user_firstname"] . "</li>";
}
return $list;
}
And there is a syntax error in the following line
if (addUser($email, $password)
close it with ")"
You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
to
ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)
What this does is captures the output and stores it into a varable $usersList which you can then return as a string.
You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.
More information about php's output buffer here
Are you trying to get the error returned by ajax or you want to have custom error? (e.g. string returned by your php script). If you're referring to ajax error you should have this:
EDIT: Since you mentioned you want a custom error returned by process.php
Process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}else{
echo 1;
}
//I added else echo 1;
}
Your ajax will be:
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if(response != 1){
$("article ul").html(response.data);
}else{
alert('Custom error!');
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
BTW you're missing ) in your posted code if (addUser($email, $password))
This is how I do:
try{dataObj = eval("("+response+")");}
catch(e){return;}
alert(dataObj->example_key);
now guys i know this is a simple error but no matter what i try i cant access the json values whenever i use alert after parse json it shows me undefined
why is it caused ?
here is my code
script
function getfriend_requests()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/getallfriends"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
alert(json);
$.each(json,function(key,data)
{
alert(data.object);
});
}
});
}
now the controller
public function getallfriends()
{
$id=$this->input->post('id');
$this->load->model('Pmodel');
$data['senders']=$this->Pmodel->get_all_user_friends_sender($id);
$data['recievers']=$this->Pmodel->get_all_user_friends_reciever($id);
echo json_encode($data);
}
now the model
public function get_all_user_friends_sender($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.senders_id = user_data.id');
$this->db->join('user', 'user_friend.senders_id = user.id');
$this->db->where('user_friend.senders_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
public function get_all_user_friends_reciever($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.recievers_id = user_data.id');
$this->db->join('user', 'user_friend.recievers_id = user.id');
$this->db->where('user_friend.recievers_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
now when i try to return the value with result_array iy shows me undefined value but if i use $row_array it return only single value from each model.
can you tell me where i am going wrong?
You have array of objects in json response so in success function try like this..
$.each(json,function(key,data)
{
alert(data.key);//where key is key of pointing object
});
In your controller try to change
echo json_encode($data);
to
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);
I have problem in ajax posting. i try to get category when select parent category in drop down.but data is post.
my business controller
public function getcat($id)
{
echo "sdfad";
$cr=new Categoryrepo();
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($cr->getcatbyparentid($id)));
}
my category model
public function getcatbyparentid($id)
{
$this->db->select('id,name');
$this->db->from('category');
$this->db->where('parent',$id);
return $query=$this->db->get();
}
my ajax code
$(document).ready(function(){
$("#parent").change(function(){
var id=$('#parent').val();
alert(id);
$.ajax({
type:"POST",
url:"<?php echo base_url()?>business/getcat/"+id,
success: function(data)
{
alert(data);
}
});
});
});
please help me how to solve it
now it working ......
Json return proper data like [{"id":"8","name":"mobile"},{"id":"10","name":"mno`"}].
now Questions is how to bind this data in drop down list..
Try this:
Model:
public function getcatbyparentid($id){
$this->db->select('id,name');
$this->db->from('category');
$this->db->where('parent',$id);
// just return query! In controller we will handle it.
return $query;
}
Controller:
$this->load->model("Categoryrepo");
$html = $this->Categoryrepo->getcatbyparentid($id);
$content = "<select name='yourName'>";
foreach($html->result() as $row){
$content .= '<option value="'. $row->column_name1 .'">' . $row->column_name2 . "</option>";
}
$content .= "</select>";
$result = array('status' => 'ok', 'content' => $content);
echo json_encode($result);
Modify your model function as below:
public function getcatbyparentid($id)
{
$this->db->select('id,name');
$this->db->where('parent',$id);
$query=$this->db->get('category');
if($query->num_rows() == 0)
{
return FALSE;
}
else
{
return $query->result() // or return $query->row() <if you want only one value to be return>
}
}
I have a jQuery function that gets data from a form and puts it as a string (for now) into an #content.
$(document).ready(function() {
$('form').submit(function() {
var results = $(this).serialize();
var url = '<php? echo JURI::base(); ?>index.php?option=com_mls&task=ListData&' + results;
$('#content').html(url);
return false;
});
});
So, I know how to build the query string from the form.
I have a task in my controller that runs a mySQL query string from the URL.
function ListData()
{
error_reporting(E_ALL);
$db =& JFactory::getDBO();
$sort = JRequest::getVar('sort');
...some other stuff...
$query = [some big nasty thing]
$db->setQuery($query);
$array = $db->loadRowList();
return $array;
}
So I know how to query the mySQL DB and get an array().
Then, I have a PHP script that pulls the array data into HTML format:
<?php
$array = $this->disparray;
foreach($array as $key => $value){
$mlsnum = $value['1'];
...some other data gets....
echo '<div>' . $mlsnum . '</div>';
}
?>
Here's where I'm stuck. I don't know how to get the URL query from jQuery to the controller task and then get the array() returned by that task into the PHP script which would build the HTML and then get AJAX/jQuery to put that data into #content.
Action is going on in 3 steps.
First ajax call view.raw.php then you load/add/delete some data from model, and customize it as you want. Then you print it in JSON format - send it back to ajax, and then ajax put that into html.
$(document).ready(function() {
var url = '<php? echo JURI::base(); ?>index.php?option=com_mls&task=ListData&format=raw&' + results;
$.ajax({
url: url,
dataType: 'json',
success: function(json) {
if (json['output']) {
$('#content').html(json['output']);
}
if (json['redirect']) {
location = json['redirect'];
}
}
});
});
this will communicate with
/com_mls/(default_view)/view.raw.php
in there, you should probably do something like
class mlsView_your_view... extends JView
{
public function display($tpl = null) {
$task = JRequest::getCmd('task', 0);
// see what should we do now
switch( $task ){
case 'ListData':
$data = $this->get_data();
break;
}
// Get the document object.
$document = JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
// Change the suggested filename.
//JResponse::setHeader('Content-Disposition','attachment;filename="resp.json"');
// Output the JSON data.
echo json_encode($data);
}
function get_data() {
// load model
$model = $this->getModel('ajax');
// get data from model
$data = $model->getSomeData();
if( is_null($data) ){
return array( 'error' => 'missing data.');
}
$data['output'] = $model->prepareData($data);
return array( $data );
}
....etc....
}