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;
}
});
}
Related
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 need some help setting up DB marker retrieval. I got a bit confused on what exactly to pass back. Here is what I have so far:
data returned:
["Chatswood NSW AU","Chippendale NSW AU"]
JS:
var opdata = [];
function markers() {
$.post("id.php", {id: <?php echo $id; ?>})
.done(function(data) {
//data is array returned
opdata = data; //Tried this
$(opdata) = data; //Tried this
opdata.push(data); //Tried this
$.each(data, function(i) { //Tried this
opdata.push(data[i]);
});
});
console.log(opdata); //Shows [] empty array regardless what i do
}
PHP:
$arr = array();
while ( $selectData -> fetch() ) {
$arr[] = $address;
}
echo json_encode($arr);
How do I go about retrieving data? None of the above is working.
This is driving me nuts.. should i just $.ajax instead?
The call to .done is asynchronous, meaning that .done finishes right away, BEFORE the ajax call is made, and console.log is called right after, even if the http call is not finished yet.
Based on your use case and context you can choose between 3 options to return opdata back to the caller function:
///// OPTION 1: synchronous call
function markersUsingSynchronousCallToAjax() {
var opdata = [];
$.ajax({
type: "POST",
url: "id.php",
async: false, // disable asynchronous call to ajax
data: {id: <?php echo $id; ?>},
success: function(data) {
opdata = data;
}
})
return opdata;
}
var opdata = markersUsingSynchronousCallToAjax();
console.log("using a synchronous ajax call", opdata);
///// OPTION 2: callback
function markersUsingCallback(callback) {
$.post("id.php", {id: <?php echo $id; ?>})
.done(function(data) {
callback(data);
});
}
markersUsingCallback(function(opdata){
console.log("using a callback", opdata);
});
///// OPTION 3: promise
function markersUsingPromise(callback) {
return $.post("id.php", {id: <?php echo $id; ?>});
}
markersUsingPromise().done(function(opdata){
console.log("using a promise", opdata);
});
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....
I'm trying to pass some variables to a php file with ajax
$(document).ready(function(){
$("button").click(function(){
var id = this.id;
var name=this.name;
console.log(id+" "+name);
$.ajax({
type: 'GET',
url: 'utility.php',
dataType: 'text',
data: {id: id, name: name},
success: console.log('aa'),
//error: function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown ); },
//complete: alert(id+' '+name)
}); // Ajax Call
}); //event handler
}); //document.ready
<?php
warning('getting something');
if($_GET['id'] && $_GET['name']){
$id=$_GET['id'];
$name=$_GET['name'];
if($id=='delete'){
my_remove($name);
}
if($id=='modify'){
retrieve($name);
my_remove($name);
modify($name);
}
}
else {
warning('unable to get information');
}
function my_remove($name){
warning('deleting');
//mysqli_query($con,"DELETE FROM `book`.`".$page."` WHERE `".$page."`.`name` =\'".$name."\'");
//echo "<script type='text/javascript'>alert('$name');</script>";
}
function modify($name){
warning('modified');
}
function retrieve($name){
warning('fetching');
}
function warning($message){
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
The .js part seems to run smoothly, it sets the name and id as it should and returns a success message, but nothing else happens, not even the alert('getting something') which should run regardless of parameters.
Printing out the data gives [object Object] which I'm not even sure what it means.
Please help!
you're using GET not POST so under the line
if($_GET['id'] && $_GET['name']){
should be get, not post as you have it
$id=$_GET['id'];
$name=$_GET['name'];
since your php script runs in the background with your ajax call, I don't think the alert code in that page will work. Instead try returning the plain text to the ajax function and alert it there
$(document).ready(function(){
$("button").click(function(){
var id = this.id;
var name=this.name;
console.log(id+" "+name);
$.ajax({
type: 'GET',
url: 'utility.php',
dataType: 'text',
data: {id: id, name: name},
}).done(function(text){
alert(text);
}); // Ajax Call
}); //event handler
}); //document.ready
and your php file like this.I changed your warning function
<?php
warning('getting something');
if($_GET['id'] && $_GET['name']){
$id=$_GET['id'];
$name=$_GET['name'];
if($id=='delete'){
my_remove($name);
}
if($id=='modify'){
retrieve($name);
my_remove($name);
modify($name);
}
}
else {
warning('unable to get information');
}
function my_remove($name){
warning('deleting');
//mysqli_query($con,"DELETE FROM `book`.`".$page."` WHERE `".$page."`.`name` =\'".$name."\'");
//echo "<script type='text/javascript'>alert('$name');</script>";
}
function modify($name){
warning('modified');
}
function retrieve($name){
warning('fetching');
}
function warning($message){
echo $message;
}
?>