I want to write the dropdown-change into to an ACF field.
i have a ninja table with a dropdown and i added this code on dropdown:
<?php
wp_register_script( 'custom-acf-js', get_template_directory_uri() . '/library/scripts/script-js.js', ['acf-input'], '1.0.0', true);
wp_enqueue_script('custom-acf-js');
function feldUpdate($selector,$value,$post_id){
update_field('bewerber_einstufen', $value , $post_id );
};
//feldUpdate('bewerber_notiz','eingeladen', 192);
?>
<script type="text/javascript">
// Ninja Table Loaded initially
jQuery(document).on('ninja_table_loaded', function (event, $table, settings) {
console.log('ninja_table_loaded');
let changeButton = document.querySelectorAll('select');
var acfVersion = acf.get('acf_version');
//alert(acfVersion);
for(let i=0; i < changeButton.length; i++){
changeButton[i].addEventListener("change",function(){
let rowidparent = this.parentElement.parentElement;
let rowid = (rowidparent.querySelector("p").innerHTML);
console.log(rowid);
//feldUpdate('bewerber_notiz','eingeladen', rowid);
});
};
});
</script>
So how can i write the javascript code (variables) into my php function.
Kind regards, Daniel
You cannot call a PHP function directly with JavaScript like that. PHP is executed by the server and JavaScript is executed by the browser (in this context anyway)
To achieve what you want here you need to use Ajax. Which is the front-end making a http request to the server and then the server will call your PHP function and return an appropriate response.
Creating the Ajax endpoint for WordPress
<?php
// functions.php
add_action('wp_ajax_call_feld_update', 'feldUpdateCallback');
add_action('wp_ajax_nopriv_call_feld_update', 'feldUpdateCallback'); // nopriv for unauthenticated users
/**
* Ajax call for updating bewerber_einstufen field
*
* #return void
*/
function feldUpdateCallback(): void {
}
So now you have an ajax endpoint you can call from your JavaScript. Now you need to setup the front end and have WordPress create a nonce for you, which is essentially the way you ensure the request came from the front-end of your own website.
<script type="text/javascript">
var wp_nonce = '<?= wp_create_nonce('updating-field-nonce'); ?>';
var ajax_url = '<?= admin_url('admin-ajax.php'); ?>';
// Ninja Table Loaded initially
jQuery(document).on('ninja_table_loaded', function (event, $table, settings) {
// your code was here
});
</script>
Now the JavaScript variable wp_nonce will have have the nonce stored in it and the ajax_url will have the url for ajax stored in it. This is normally achieved with wp_localize_script however this is a simplified example for you.
Now you can create your ajax request like so
jQuery(document).on('ninja_table_loaded', function (event, $table, settings) {
console.log('ninja_table_loaded');
let changeButton = document.querySelectorAll('select');
var acfVersion = acf.get('acf_version');
//alert(acfVersion);
for(let i=0; i < changeButton.length; i++){
changeButton[i].addEventListener("change",function(){
let rowidparent = this.parentElement.parentElement;
let rowid = (rowidparent.querySelector("p").innerHTML);
console.log(rowid);
// ajax request
jQuery.ajax({
type: "POST",
url: ajax_url,
data: {
action: 'call_feld_update', // the action is set when you added wp_ajax_ at the beginning of this answer.
postId: rowid,
value: 'eingeladen',
nonce: wp_nonce
},
success: function (response) {
console.log(response);
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
};
});
With that, WordPress will call the feldUpdateCallback function when the ajax request is sent. Now we update the PHP function that was created before so it can deal with that request...
// functions.php
/**
* Ajax call for for updating bewerber_einstufen field
*
* #return void
*/
function feldUpdateCallback(): void {
// nonce - The key you set when sending the request from ajax
// updating-field-nonce - The parameter for the wp_create_nonce function
if (!wp_verify_nonce($_REQUEST['nonce'], 'updating-field-nonce')) {
// The string we received does not match the nonce that was set on the front by WP
die('nonce validation failed');
}
// now you can deal with the request...
feldUpdate(
'bewerber_notiz',
sanitize_text_field($_REQUEST['value']), // https://developer.wordpress.org/reference/functions/sanitize_text_field/
sanitize_text_field($_REQUEST['postId'])
);
die('successful');
}
Related
Hi I am following a tutorial on Ajax calls in wordpress. The example has all the code in functions.php but I want to be more organised and include the javascript in a js file.
Here is what I have so far
functions.php
//The PHP
function example_ajax_request() {
// The $_REQUEST contains all the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// This bit is going to process our fruit variable into an Apple
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now let's return the result to the Javascript function (The Callback)
echo $fruit;
}
// Always die in functions echoing AJAX content
die();
}
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
and in the Javascript file test.js:
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
// This is the variable we are passing via AJAX
var fruit = 'Banana';
// This does the ajax request (The Call).
$( ".banana" ).click(function() {
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'fruit' : fruit // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$(".banana").text(data);
window.alert("here");
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
How can: 'action':'example_ajax_request', // This is our PHP function below
be accessed from the functions.php file?
jquery.js?ver=1.12.4-wp:4
POST https://xyz/update.php 500 (Internal Server Error)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
myFunction # 6011c7fbf.min.js?ver=1600216310:3
onclick # (index):453
I am getting a 500 error above from the console. What I dont know is whether the error is in my PHP in trying to update the row or elsewhere.
PHP below is contained inside my update-file.php file
function function_1() {
global $wpdb;
$wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
}
JAVASCRIPT contained on the page
function myFunction() {
jQuery.ajax({
type: 'post',
url: '/wp-content/themes/yummy/update-file.php',
success: function(data){
// callback function
}
});
alert("I've been clicked!!");
}
HTML
Go!
EDIT 1
As per suggestions I have updated as such:
JAVASCIPT
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
action: 'function_1',
success: function(data){
// callback function
}
});
Thinking the above was not correct I also tried :
jQuery.ajax({
type: 'post',
url: my_ajax.https://myurl.com/wp-content/themes/yummy/update-waitinglist.php, // this is the location of the update php below
action: 'function_1',
success: function(data){
// callback function
}
});
PHP below is contained inside my update-file.php file
add_action('wp_ajax_function_1', 'myfunctionname'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'myfunctionname'); // non logged in user can make a call
function myfunctionname() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
die($results);
}
ADDED TO FUNCTIONS FILE
wp_localize_script('myfunctionname', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
With the EDIT 1 in place, I also get an error - Notice: wp_localize_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the wait list_update handle. Please see Debugging in WordPress for more information. www.xyz.com/wp-includes/functions.php on line 5225 . I must have misunderstood something in the suggestion.
EDIT 2 Got everything else working but the button doesnt seem to update anything.
PHP from functions file -
function my_scripts() {
wp_enqueue_script( 'waitlist_update_call', get_template_directory_uri().'/assets/js/waitlist_update_call.js', array('jquery'), null, true );
wp_localize_script('waitlist_update_call', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
echo getcwd();
//calls Waitinglist data and creates table
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action('wp_ajax_waitlist_update_function', 'waitlist_update_function'); // logged in user can make a call
function waitlist_update_function() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'mytablename' SET `currentstatus` =
'myupdate1' WHERE ID = '1'"));
die($results);
}
JS
// JavaScript Document
function update() {
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
// add your action inside data object
data: {
action: 'waitlist_update_function'
},
success: function(data){
// callback function
}
});
}
HTML
Go!
The issue should be with the URL, it must be absolute I think.
jQuery.ajax({
//....
url: 'http://yourwebsite.com/wp-content/themes/yummy/update-waitlist.php'
// ...
The WordPress way
You must enqueue your JS file script.js before with same handle
and then localize after it
Localize the script to pass generic data. We will pass the ajax_url with my_ajax object.
functions.php
wp_localize_script('your-script-handle', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
Then in your script file, you can use the my_ajax object to get the AJAX URL. Define a action function_1 which will be executed when this AJAX call is requested.
script.js
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
data: {
action: 'function_1',
}
success: function(data){
// callback function
}
});
Define a function and attach it with Ajax action that will query the database & returns the result.
functions.php
add_action('wp_ajax_function_1', 'function_to_execute_some_query'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'function_to_execute_some_query'); // non logged in user can make a call
function function_to_execute_some_query() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'wp_wpdatatable_4' SET `currentstatus` =
'myupdate1' WHERE wdt_ID = '1'"));
die($results);
}
I update vote count on the content of a post, but I also have a widget that has counts of votes on each post. When the user clicks on the vote on a post, the vote counts
in each post of the widget does not get updated.
I wrote an AJAX function that calls function through actions like so
// AJAX function file ajax-vote-on-post.js
function voteOnPost(postId) {
jQuery.ajax({
type: 'POST',
url: voteonpostajax.ajaxurl,
data: {
action: 'addvote-to-post',
postid: postId
},
success: function(data, textStatus, XMLHttpRequest) {
var votecontainerid = '#vote-count-' + postId;
jQuery(votecontainerid).html('');
jQuery(votecontainerid).append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
I properly registered the ajax file to be called by WP in a Widget file that contains other functions and PHP codes.
...
// function in the PHP file that is called.
function addvote-to-post(){
$result = '';
// get vote count from DB
$post_ID = $_POST['postid'];
$votepostcount = get_post_meta($post_ID, '_votepostcount', true) != '' ? get_post_meta($post_ID, '_votepostcount', true) : '0';
// Code that updates the DB in WordPress does other things
...
// Output count on the DOM
$votecountnew = $votepostcount + 1;
$result = '<div class="vote-count-'.$post_ID.'" >'.$votepostcountNew.'</div>'
// update_all_count_for_post($post_ID, $votecountnew);
die($result);
}
The page load slowly and how best to update the DOM without using an extra function.
class MyVotePostWidget extends WP_Widget {
// Widget Front End
public function widget {
// HTML code to display posts with votes
}
}
I have to select a file locally and use it in a python script.
I can't get the filename in order to have it in my ajax script that i use to call a php function.
This is my javascript, called onclick over Ok button:
function myAjax () {
$.ajax( { type : 'POST',
data : {},
url : 'action.php',
success: function ( data ) {
alert( data );
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
},
complete: function (data) {
setImg();
}
});
}
This is the php script used to call python script:
<?
function bb(){
$out = shell_exec( 'python heatmap.py');
echo "ok";
$fp = fopen('log.txt', 'w');
fwrite
($fp, $out);
fclose($fp);
}
bb();
?>
I have to take filename from Browse button and send it to ok button, where the python is called.
What is the correct way to exchange data from input="file" html, javascript and php?
I'm making a lot of assumptions here as the question is not entirely clear...
But presumably you're wanting the name of a file that has been selected from the OS. In JS you can do this using the following.
var fileName, oForm = document.getElementById('my-file');
oForm.onchange = function(){
fileName = this.files[0].name;
}
Then in your AJAX call, add the fileName variable to your data property.
data : {"filename":fileName},
And then in your PHP access it via the $_POST variable. So...
echo $_POST['filename'];
I am trying to read from a database some data but without waiting for the page to load, so I created an ajax post that starts sending data when page is ready, now after ajax completes I need to read the values from another file. The problem is that after the ajax completes, json that is reading the data is running indefinite.
JQUERY
<?php $url = $_GET['url']; ?>
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0(document).ready(function () {
var domain = '<?php echo $url; ?>';
$.ajax({
type: 'POST',
url: 'lib/ajax.php',
data: {
action: 'get_all_seo_details', // function that collects data
domain: domain // the domain that is being send to the function in order to get data
},
success: function (data) {
// doesn't need to echo anything only to insert the data, which it done properly
}
});
// Below is the second part of the script that starts when ajax stops
$(document).ajaxStop(function () {
$.getJSON('lib/get-details.php', function(data) {
var twitter_followers = data.twitter_followers;
$('#twitter-followers').html(twitter_followers);
});
// data is being read correctly but it loops repeatedly in the console without finishing
});
});
PHP - get-details.php, reading the data from database after getting inserted with ajax
if (!isset($_SESSION)) {
sec_start();
}
global $db;
$domain = isset($_SESSION['domain']) ? $_SESSION['domain'] : '';
if ($domain == '') {
$domain = $db->query("SELECT * FROM seo_data");
} else {
$domain = $db->query("SELECT * FROM seo_data WHERE domain = '$domain'");
}
$domain_now = $domain->fetch_assoc();
$twitter_followers = (int) $domain_now['twitter_followers'];
echo json_encode(array('twitter_followers' => $twitter_followers));
I'm not sure but when the first AJAX request stops
$(document).ajaxStop(function (){....
starts a new one with
$.getJSON('lib/get-details.php', function(data) { ...
When this second one ends, maybe
$(document).ajaxStop(function (){....
is called again which starts again the 2nd request and so on