Codeigniter null values ajax request - php

, i'm triying to get some values from database on an ajax request in codeigniter...but json object returns null ([]) when I put console.log...I need help pls !!
JAVASCRIPT
function list_president() {
var section = "1";
$.post(baseurl + 'votos/load_politic', section,
function(data) {
console.log(data);
});
}
CONTROLLER
public function load_politic()
{
if ($this->input->is_ajax_request()) {
$section = $this->input->post('section');
$result = $this->politic->get_president($section);
echo json_encode($result);
}
}
MODEL
public function get_president($section){
$this->db->select("p.POLITIC_NAME, p.POLITIC_LASTNAME, p.POLITIC_SIDE, p.POLITIC_CHARGE");
$this->db->from("politics p");
$this->db->where("SECTION_ID",$section);
$result= $this->db->get();
return $result->result();
}
Thanks for help!!

You aren't sending key/value pair to server...just a value.
So there is no $_POST['section'] which is basically what $this->input->post('section'); is
Try changing
var section = "1";
To
var section = {section: "1"};
You also aren't validating what is sent or checking if $result returns anything

Related

Can't access the json values in my ajax success in codeigniter

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));

Pass javascript variable to php function using ajax in same file without page refresh

I am using PHP function to display geofences. I want to pass javascript variable to php function in same file without page refresh.
function load(id,type){
if(type===2){
window.location.href="basic.php?idd=" + id; // i want to change code here
<?php
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
PHP function is:
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($result)) {
$d[] = $myrow;
}
return $d; //returns result in array
}
javascript window.location.href passes javascript value to php function but it reloads page also.
If you're using jQuery, you can use $.ajax(). It allows you to send data to your server and do something with the response.
Eg:
$.ajax({
type: 'POST',
data: myvar
success: function(Response) { console.log(Response); }
});
will send myvar to your server (with a bit of tweaking of parameters of course) and log whatever the server sends back to your browser console.
Have a read of what you can do with jQuery.
You can do this using jQuery. Basically you don't refresh the page, you just do an async query to the server and you get the response. In the following example the response is showed in alert box.
Your "index" file:
function load(id,type)
{
$.post("basic.php", { idd: idd }, function(data){
alert(data);
});
}
and basic.php
<?php
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($rs)) {
$d[] = $myrow;
}
return $d;
}
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>

retrieve data from .post

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.

getting data from functions when posting with jquery

I'm beginning to hate AJax, I'm finding it really difficult to get any kind of useful information back when posting with jQuery.
I have a script that adds or removes some info when a button is clicked. The jquery posts to a file which calls a function in a class. This part works, but I cant get a success message back to manipulate the front end. Here is my code.
The php works but I keep getting the error JSON.parse: unexpected character which I have googled, but my json looks ok?
jQuery
$('.fave').click(function(){
var favId = $(this).attr('data-user-fave');
var params = {};
params['fave_id'] = favId;
params['fav_flag'] = '1';
$.post('index.php?link=my_applications', params, function(data){
var data = $.parseJSON(data);
if(data.message === 'success'){
alert(data.flag);
}
else{
alert("Fail");
}
});
code in file that jQuery posts to
$profile = new profile();
if($_POST['fav_flag'] == '1'){
$js = $profile->fave_user();
echo json_encode($js);
}
function in class profile
function fave_user(){
$query = "SELECT * FROM `favourite` WHERE user_id = '{$_SESSION['loginArr']['user_id']}' AND fave_id = '{$_POST['fave_Id']}'";
$nr = $GLOBALS['DB']->num_rows($query);
if($nr >= 1){
//exists so remove
$query = "DELETE FROM `favourites` WHERE user_id = '{$_SESSION['loginArr']['user_id']}' AND fave_id='{$_POST['fave_Id']}'";
$GLOBALS['DB']->deleteQuery($query);
$return["message"]="success";
$return["flag"]="del";
return $return;
}
else{
//not a fave so add
$query = "INSERT INTO `favourite` (user_id, fave_id) VALUES ('{$_SESSION['loginArr']['user_id']}', '{$_POST['fave_id']}')";
$GLOBALS['DB']->insertQuery($query);
$return["message"]="success";
$return["flag"]="ins";
return $return;
}
}
I would suggest using $.ajax method: it is more advanced.

How does Ajax work with PHP?

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

Categories