Jquery ajax call is not calling controller in codeigniter - javascript

I am trying to call my controller function using ajax but it is not calling with input . Here is my ajax call
if(value)
{
$.ajax({
type:"POST",
dataType:"text",
cache:false,
contentType: "application/json; charset=utf-8",
url:"<?php echo base_url('Dashboard/deleteSpeciality'); ?>",
data:{'id':id},
success:function(data){
alert("i am in success");
},
error:function(data){
alert(data);
}
});
}
and here is my controller function. Ajax call is going but input is not. At server side program throws error Id is not defined.
public function deleteSpeciality($id) {
$result= $this->Dashboard_model->getSpeciality($id);
$path=$result[0]->ImagePath;
$this->load->helper("file");
delete_files($path);
unlink($path);
$this->Dashboard_model->deleteSpeciality($id);
return 1;
}

Try this in your controller $id=$_POST['id'] and as you are using Post method so don't pass id as parameter in function.
public function deleteSpeciality() {
$id=$_POST['id']
//code here
}

Try this
public function deleteSpeciality()
{
$id=$this->input->post('id');
// will print the id that was posted from ajax
//echo $id;
$result= $this->Dashboard_model->getSpeciality($id);
$path=$result[0]->ImagePath;
$this->load->helper("file");
delete_files($path);
unlink($path);
$this->Dashboard_model->deleteSpeciality($id);
return 1;
}

Related

Ajax in javascript return undefined

I have this javascript function with ajax calling a .php calling a function inside a class .php, but the console.log is undefined
function SpinTimeTotal(){
$.ajax({
type:"POST",
url: "app/get_SpinTimeTotal.php",
success: function($a){
return $a;
}
});
}
spinTimeTotal = SpinTimeTotal();
console.log(spinTimeTotal); //undefined
calling this php code
<?php
include_once "read_spindata.php";
$a = read_data_spin :: read_Timespin();
?>
calling this function
<?php
class read_data_spin{
public static function read_Timespin(){
try{
$conexion = new PDO("mysql:host=localhost; dbname=dbname", "user", "pass");
} catch (PDOException $ex) {
echo "Conexion fallida". $ex -> getMessage();
die();
}
$spinTimeTotal = $conexion -> query("SELECT spinTimeTotal FROM data_ruleta ORDER BY id DESC limit 1");
return $spinTimeTotal;
}
}
SpinTimeTotal() is an asynchronous function and this statement won't wait until executed.
spinTimeTotal = SpinTimeTotal();
You should instead use deferred objects or promises.
function SpinTimeTotal()
{
var deferred = jQuery.Deferred();
$.ajax(
{
type: "POST",
url: "app/get_SpinTimeTotal.php",
success: function($a)
{
return deferred.resolve($a);
}
});
return deferred.promise();
}
Your actual function call would then be:
$.when(SpinTimeTotal()).then(function(data)
{
console.log(data);
});
You need to echo the result in your php script like
<?php
include_once "read_spindata.php";
$a = read_data_spin :: read_Timespin();
echo $a;
?>
In most cases there will be more to return than just single value. Then JSON is the preferred format:
echo json_encode($resultObject);
And, of course, you need to change your Ajax call too, like:
function SpinTimeTotal(){
$.ajax({
type:"POST",
url: "app/get_SpinTimeTotal.php",
success: function($a){
console.log($a);
}
});
}
Th console.log in your global scope will have been fired before the Ajax success function had done its job. And even then, the returned value cannot be picked up from the global scope.
The only way to "return" a result value from an AJAX function would be into an async function, see here for a working example: What is different between Fetch and jQuery Ajax post?
try $a without $ , just a
function SpinTimeTotal(){
$.ajax({
type:"POST",
url: "app/get_SpinTimeTotal.php",
success: function(a){
return a;
}
});
}

AJAX redirect to another php file and pass javascript variable to that same php file

I am new to Ajax. I have here a function that when a button is clicked, you should be redirected to id.php and at the same time pass the value of clicked_id.
Javascript code:
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
$.post('id.php',{ID:clicked_id},
function(data){
window.alert("here");
window.location='id.php';
});
}
Inside my id.php,
<?php
$clickedID = $_GET['ID'];
echo 'here at id.php';
echo $clickedID;
?>
Now the problem is that ID in id.php cannot be identified.
Please help me. I already tried both $_POST and $_GET.
I believe that the problem here is in the passing of the variable.
there is no need for ajax if you wanna pass the id to the id.php after redirection
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
window.location='id.php?id=' + clicked_id;
}
in id.php you can get the id like this:
<?php $id = $_GET['id'];
function buttonClicked() {
$.ajax({
url: "id.php", //url for php function
type: "POST",
data: {'clicked_id':clicked_id}, // data to sent
dataType: 'json',
success: function (data)
{
}
});
}
And in your id.php file:
$_REQUEST['clicked_id']

How to post a value to a controller function on button click using Ajax and also redirect to new page at the same time?

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.

How to call a codeigniter helper function using JQuery AJAX?

I have a function defined in my helper function in codeigniter that returns the formatted price when val and currency id is passed to it.
if(!function_exists('format_price')){
function format_price($val,$curency_id=NULL){
$CI =& get_instance();
$CI->load->model('currency_model');
if ($curency_id) {
$Result=$CI->currency_model->getcurrency($curency_id);
$dec_place=round($Result['decimal_place']);
$value=number_format((float)$val,$dec_place,'.',',');
return $Result['symbol_left'].$value ." ".$Result['symbol_right'];
}
else{
$Result=$CI->currency_model->getDefaultCurrency();
$dec_place=round($Result['decimal_place']);
$value=number_format((float)$val,$dec_place,'.',',');
return $Result['symbol_left'].$value ." ".$Result['symbol_right'];
}
}
}
What I need is to call this function through ajax in javascript code.
is this possible without a controller, or do I have to make a controller?
You need to make a request via controller, then call that function through that controller, something like:
$("#id").change(function()
{
$.ajax({
type: "POST",
url: base_url + "controller_name/your_function",
data: {val: $("#your_val").val(),currency_id: $("#your_cur").val()},
dataType: "JSON",
cache:false,
success:
function(data){
$("#your_elem").val(data.price);
}
});
Then on your controller:
public function yourfunction()
{
$data = $this->input->post();
$price = format_price($data['val'],$data['currency_id']);
echo json_encode(array('price' => $price));
}
instead of using ajax try like this...
<script type="text/javascript">
$(document).ready(function(){
(function(){
<?php if(helper_function($variable)) { ?>
now your jquery script..........
<?php } ?>
});
});
</script>
customize above code as u want....

ajax request to codeigniter controller from javascript

I am making an ajax request from my codeigniter view in javascript function but nothing happens and the success alert (ok) pops up
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success: alert('ok'),
});
}
This is my controller it is working perfect, when i copy paste the url (used in ajax request) in my browser every thing goes good, controller makes a call to the model and it works perfect
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$this->search_peoplee->delete_notifications($one);
return;
}
View :
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success:function(
console.log("success");
)
});
}
Controller :
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data= $this->search_peoplee->get_userid_from_email($email);
$res=$this->search_peoplee->delete_notifications($data[0]->userid);
if($res){
echo json_encode(array('success'=>true));
}else{
echo json_encode(array('success'=>false));
}
}

Categories