I want to get data(time) by comparing userid and date against a post. But for testing I am simply calling php function by ajax. I made a separate php file (myscript.php) in which I made a function and echo something like that.
function my_action(){
echo "dasdasasdaaddad";
$date = $_POST['date'];
echo $date;
return $date;
}
Now when I click on a button I get the date and userid.
global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));
add_action( 'the_content', 'my_action_javascript' );
function my_action_javascript() {
$current_user = wp_get_current_user();
$uid = $current_user->ID;
?>
<script type="text/javascript" >
jQuery(".date").click(function(){
clicked = this;
var dates= jQuery(clicked).closest("ul").find(".getdate").val();
var item= jQuery(this).closest("li.lia");
var date = jQuery(item).find("input.getdate").val();
//var dates = jQuery(item).find("input.getdate").val();
alert(date);
jQuery.ajax({
type:"post",
url: "<?php $current_url;?>/myscript.php",
data : {
'action': 'my_action',
'date': date,
'userid': "<?php echo $uid?>"
},
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
success: function(data) {
successmessage = 'Data was succesfully captured';
$("label#successmessage").text(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("label#successmessage").text(successmessage);
},
});
});
</script>
<?php
}
I gave the URL of that file in ajax url. Now it should print data from myscript.php file but I am getting this result in response from ajax.
Got this from the server:0
I have checked the network also and it seems good to me.
ajax is getting userid and date but response is 0.Don't know why?
on
myscript.php page remove function my_action().. because you are not calling this.
if you want to call this before that use my_function();
<?php
my_function();
function my_action(){
echo "dasdasasdaaddad";
$date = $_POST['date'];
echo $date;
return $date;
}
?>
You are not calling your my_action function in myscript.php file. Call your function you will get the your desired result.
<?php
function my_action(){
echo "dasdasasdaaddad";
$date = $_POST['date'];
echo $date;
return $date;
}
my_action();
?>
Related
I know that there are many similar questions here and feel that I really have tried all the others, replacing the answers code into mine, testing and retesting... still no further and have been doing this for so many hours... [trying to pass a js var, into wordpress]
...really appreciate any help anyone can give.
In the console, I get a 400 error...
//functions file:
//getting vars from ajax
function our_tutorial(){
$testing = 'not set';
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
}//end is set
return $testing;
}//end function
add_action('wp_ajax_php_tutorial', 'our_tutorial');
add_action( 'wp_ajax_nopriv_php_tutorial', 'our_tutorial' ); // for non logged in users
js file: [extracted from a function, rest of the function working as it should be, tested and retested]
///....
var test = '667'
var jaxscript = 'https://example.com/wp-admin/admin-ajax.php'; //absolute ref for testing
$.ajax({
url: ajaxscript,
data: {
'action': 'php_tutorial',
'php_test': test
},
success: function(data){
console.log("Happy");
}
});
///....rest of function and closing function '}'
First, change
var jaxscript
to
var ajaxscript
var test = '667'
var ajaxscript = 'http://testing.local/wp-admin/admin-ajax.php'; //absolute ref for testing
$.ajax({
url: ajaxscript,
data: {
'action': 'php_tutorial',
'php_test': test
},
success: function(data){
console.log(data);
}
});
And use echo in place of return and use wp_die(); before closing function
function our_tutorial(){
$testing = 'not set';
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
}
echo json_encode($testing);
wp_die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');
add_action( 'wp_ajax_nopriv_php_tutorial', 'our_tutorial' );
hi is it possible to retrieve data from a PHP function using Ajax?.
i want my url in ajax to point in one of my functions. please see my code below.
like this:
<?php
class employee{
public function __construct(){
}
public function fName($fName){
echo $fName;
}
public function lName($lName){
echo $lName;
}
}
?>
<div id="fName"></div>
<script type="text/javascript">
$.ajax({
type: 'POST',
url: "classes.php", <!-- HERE I want to target the fname function-->
success: function(result){
fname.html(result);}
});
</script>
what im doing so far is create a new php page which contain code like this.
<?php
$employee = new employee();
$employee->fName();
then ill point the ajax url to that new php page.
Assuming this code works as written in your question
<?php
$employee = new employee();
$employee->fName();
you can pass a parameter to your PHP script then decided which function is to be called like so:
jQuery:
$.ajax({
type: 'GET',
url: "classes.php?func=fname",
success: function(result) {
$("fname").html(result);
}
});
PHP - classes.php:
<?php
$employee = new employee();
$func = #$_GET["func"];
switch($func) {
case "fname":
echo $employee->fName();
break;
case "lname":
echo $employee->lName();
break;
default:
break;
}
The url property has to be a url .. in your case it perhaps will point to "/classes.php" , assuming the file is on document root of the webserver
The function fName needs to be called by the code present in that url.
so your file "/classes.php" should look like this
<?php
class Employee {
protected fName;
protected lName;
function __construct($f, $l) {
$this->fName = $f;
$this->lName = $l;
}
public function getFName(){
return $this->fName ;
}
public function getLName(){
return $this->lName ;
}
}
$employee = new Employee("John" , "Doe");
echo $employee ->fName();
I want to call a php function but it doesn't seem to work correctly.
Here is my setup:
1. Setup works
file.js:
refresh("file.php");
function refresh(php_file_path){
var file_path = php_file_path;
$.post( file_path, {"action": "bla" },
function( data ) {
console.log(data);
},"json");
}
file.php:
if (isset($_POST['action'])) {
$data = "Test";
echo json_encode($data);
}
output in console:
"Test"
This works!
when I change the file.php so that a function is called in the if-statement, I get nothing back.
2. Setup doesn't work
file.js:
refresh("file.php");
function refresh(php_file_path){
var file_path = php_file_path;
$.post( file_path, {"action": "bla" },
function( data ) {
console.log(data);
},"json");
}
file.php:
if (isset($_POST['action'])) {
$data = myfunc();
echo json_encode($data);
}
function myfunc(){
echo "Testfunc";
}
output in console:
nothing
Is there anybody who get's the mistake? Thanks!
You can't assign myFunc to a variable if it doesn't return something
if (isset($_POST['action'])) {
$data = myfunc();
echo json_encode($data);
}
function myfunc(){
return "Testfunc";
}
I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this
I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>