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";
}
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' );
I have a simple php function as below defined in one of my php file
add_action('wp_ajax_test','test');
add_action('wp_ajax_nopriv_test','test');
function test(){
echo "Hello";
}
I am calling above "test" function using below ajax function call
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
jQuery.post(
myAjax.ajaxurl,
{
action:"test",
success: (response)=>{
console.log('Success:'+ response);
},
error:(response)=>{
console.log('Failure:'+ response);
}
});
});
});
I am expecting console output of "Hello" but I getting below undefined response
Success:undefined
Failure:undefined
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
var params = {action:"test"}
jQuery.post(myAjax.ajaxurl,params,function(data){
if( data ){
console.log ( data );
}
});
});
});
add_action( 'wp_ajax_test','test' );
add_action( 'wp_ajax_nopriv_test','test' );
function test() {
echo "Hello";
die;
}
Try this code and don't forget to die after AJAX call also
make sure you are getting proper AJAX URL in myAjax.ajaxurl
I followed the below video, step by step and it worked.
Probably it had something to do with nonce
AJAX in WordPress using admin-ajax.php
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
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'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});