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....
Related
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;
}
});
}
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']
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;
}
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 cant pass the variable to my controller function.please help
<input type="button" id="mydate" name="mydate" value="<?php echo $dat;?>" class="monthYearPicker" />
script:
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: $(this).val()
},
success: function (msg) {
console.log(msg);
}
});
});
how will i take this javascript variable var textBoxVal = $(this).val() in my controller function.
controller:
public function selectallbudget(){
$mydate= $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
With the help of ajax you can do it.
FIRST:
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$.ajax({
url: base_url + "controller_name/function_name", // define here controller then function name
method: 'POST',
data: { date: dateValue }, // pass here your date variable into controller
success:function(result) {
alert(result); // alert your date variable value here
}
});
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
--------------------------------
SECOND: if you want to load any html code then you use this method otherwise above first method
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$( "#mydate" ).load(
base_url + "controller_name/function_name", // define here controller then function name
{ date: dateValue }, // pass here your date variable into controller
function(){
// write code on success of load function
}
);
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
Your code is almost okay. There is only one change in your controller code:
Controller:
public function selectallbudget(){
//$mydate= $_POST['val']; This is not PHP this is codeigniter
$mydate = $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
Please make use of ajax. This problem has already been discussed here. Please refer it.
Pass Javascript Variables tp PHP Controller in Code Igniter
What you're doing wrong here is $(this).val() to pass on the input's value.
The this object's scope keeps on changing, and is quite different when you try to access in
data: {
val: $(this).val()
}
It's rather trying to access the current object at hand.
Solution's pretty simple though (since you're already initialising textBoxVal to the input's value.
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: textBoxVal
},
success: function (msg) {
console.log(msg);
}
});
});