how will i pass a javascript variable to codeigniter controller function - javascript

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

Related

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.

Js: pass button id to the same page

<script type="text/javascript">
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
</script>
I need to pass my clicked button id to the same index.php page, without page refreshing and work with that id value.My code is wrong, because page is rendered second time.
Here is my php code:
<?php
$category=$user_home->runQuery("SELECT DISTINCT category FROM products");
$category->execute();
$categoryArray=$category->fetchAll(PDO::FETCH_ASSOC);
foreach($categoryArray as $listID){
?>
<input type="button" id="<?php echo $listID['category']?>" class="Categories" value="<?php echo $listID["category"]?>"/><br>
<?
}
?>
Call preventDefault method inside the button click event handler to prevent default button behaviour ("page is rendered second time"):
...
$(".Categories").click(function (e) {
e.preventDefault();
...
There is a syntax error in your code
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId: catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
You have to pass data in valid literal object format. {"property_name": "property_value"}.
Change: data: { catId } to data: { "catId": catId }
For server side:
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>
I think I need to post my variable to another page and then return it.I dont know how to do it in same page.This variant with exit(0) is bad because all variables inside if statement after exit(0) will be deleted.
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>

Difficulties using AJAX to pass input value to controller

I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}

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....

Passing variable value from one function to another in autocomplete with AJAX call

I have a problem in using autocomplete jQuery with AJAX call.
When user types something in input field, I post that value with AJAX to controller where I get the values from database and then all these values to the JavaScript in success message. But after that, I'm having problem to use these JSON values for autocomplete. How to fix that?
The view file
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$("#tags").autocomplete({
source: function( request, response ) {
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/search_con/user' ;?>",
data: {'userA': request.term},
success: function(msgs)
{
var a = ["Central Palms Hotel","Hotel Monalisha","asghgjfddas","My hotel added","asdfsdf","asdsadsa"];
response(a);
// alert(msgs);
}
});
}
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
and the controller
public function user(){
$userPart = $_POST['userA'];
$result = $this->searchdb->search($userPart) ;
$list = array();
foreach ($result as $finaldata) {
$data= $finaldata->name;
array_push($list, $data);
}
echo json_encode($list);
}
Now my problem is that when i remove static variable a and use msgs for response nothing is shown in autocomplete data and when alert msgs i get the same data as in variable a. is there any mistake in my json?
You don't need to have separate function to fetch the data for autocomplete, can be done like this
$(function () {
$("#tags").autocomplete({
source: function (request, response) {
$.post("<?php echo base_url().'index.php/search_con/user' ;?>", {
userA: request.term
}, response);
}
});
});
And because of the async nature of ajax you cant do this
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/search_con/user' ;?>",
data: dataString,
success: function (msgs) {
data = msgs;
}
});
alert(data); // undefined

Categories