Wordpress ajax database calls - php

I am struggling with getting ajax to work, if someone can guide me, it'd be greatly appreciated.
I am building this as a plugin.
I have a file named courselinkscript.js and contains this
jQuery(document).ready(function($){
jQuery(".courselist").change(function () {
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'getLinkedCourses' }
//where/what do I put here to work with the data I received.
})
});
});
Then in my main php file named course-listing.php I have this
function getLinkedCourses() {
global $wpdb;
$results = $wpdb->get_results( 'SELECT list.ID, list.course, list.cost, list.length, link.CourseID FROM `wp_course_list` AS list INNER JOIN `wp_course_link` as link ON (list.ID=link.LinkID) WHERE link.CourseID = 1', OBJECT );
echo json_encode($results);
wp_die();
}
function wpb_adding_scripts() {
wp_register_script('courselinkscript', plugins_url('courselinkscript.js', __FILE__), array('jquery'),'1.0', true);
wp_enqueue_script('courselinkscript');
wp_localize_script( 'courselinkscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_my_list', 'getLinkedCourses' );
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
My calls to ajax don't work as I don't understand what needs to be done to initalise it. Any help is appreciated.

Use the below mentioned code. It should work.
function getLinkedCourses() {
global $wpdb;
$results = $wpdb->get_results( 'SELECT list.ID, list.course, list.cost, list.length, link.CourseID FROM `wp_course_list` AS list INNER JOIN `wp_course_link` as link ON (list.ID=link.LinkID) WHERE link.CourseID = 1', OBJECT );
echo json_encode($results);
wp_die();
}
function wpb_adding_scripts() {
wp_register_script('courselinkscript', plugins_url('courselinkscript.js', __FILE__), array('jquery'),'1.0', true);
wp_enqueue_script('courselinkscript');
wp_localize_script( 'courselinkscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_getLinkedCourses', 'getLinkedCourses' );
add_action( 'wp_ajax_nopriv_getLinkedCourses', 'getLinkedCourses' );
// add_action( 'wp_ajax_my_list', 'getLinkedCourses' );
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
Replace your javascript with the below code:
jQuery(document).ready(function($){
jQuery(".courselist").change(function () {
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'getLinkedCourses' },
//where/what do I put here to work with the data I received.
success: function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj);
},
});
});
});

Related

How to get ACF Field Value with AJAX

little help please, it is WP site,
I have hidden section on page, and when user scroll to it popup shows asking for password, and when user enter password I must compare it with password from ACF field.
I tried several examples getting this done but i cant get anything... I could not find any clear examples of that on stackowerflow, or step by step examples, there are few of them that are not clear to me, I am kinda beginer
EDIT:
function.php
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/global.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action('wp_ajax_nopriv_get_acf_field_ajax', 'my_action');
add_action('wp_ajax_get_acf_field_ajax', 'my_action');
function my_action() {
$result = get_field('password', 'option');
echo json_encode($result);
// wp_send_json($result);
}
global.js
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: { action: 'my_action' },
success: function (data) {
console.log(data);
}
});
i got POST http://my-local-website.com/wp-admin/admin-ajax.php error 400 bad request
You have to register and localize a script file in your theme function.php.
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
After localizing your JS file, you can use my_ajax_object object in your JS file:
var form_data = new FormData();
form_data.append('action', 'get_acf_field_ajax');
form_data.append('pass', password);
form_data.append('user_id', 141);
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: form_data,
success: function(response){
console.log(response.success);
}
});
then you have to write your ajax callback function.
<?php
add_action('wp_ajax_nopriv_get_acf_field_ajax', 'my_action');
add_action('wp_ajax_get_acf_field_ajax', 'my_action');
function my_action() {
$response = array();
$user_id = $_POST['user_id'];
$user_pass = $_POST['pass'];
$acf_pass = get_field('acf_pass', 'user_'. $user_id );
if($user_pass == $acf_pass ){
$response['success'] = true;
}else{
$response['success'] = false;
}
wp_send_json($response);
}
?>
try out this rough code and modify as per your need.
This is how I manage to do it:
JS File:
$('.pwd').on('click', function () {
var pwd = prompt('Please enter your password:', '');
if (pwd != null && pwd != '') {
var password = pwd;
$.ajax({
url: example_ajax_obj.ajaxurl,
data: {
'action': 'example_ajax_request',
'password': password,
},
success: function (data) {
console.log(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
return false;
});
function example_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'example-ajax-script',
get_template_directory_uri() . '/js/global.js',
array( 'jquery' )
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'example-ajax-script',
'example_ajax_obj',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' );
function example_ajax_request() {
$acf_pass = get_field('password', 'option');
// The $_REQUEST contains all the data sent via ajax
if ( isset( $_REQUEST ) ) {
$password = $_REQUEST['password'];
if ( $password == $acf_pass ) {
$password = 'YESSSSSSS';
}else{
$password = 'NOOOOOO';
}
echo $password;
}
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

WordPress admin-ajax.php throwing 400 bad request

add_action( 'wp_footer', function () { ?>
<script type='text/javascript' id='ajax'>
const ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
async function httpRequest(url = '', data = {}, method = 'POST') {
const response = await fetch(url, { method: method,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cache-Control': 'no-cache',
},
body: new URLSearchParams(data)
});
return response.text();
}
document.querySelector('#roll-title-btn').addEventListener('click', async function() {
const searchTerm = document.getElementById('roll-title');
if (searchTerm.value.trim().length) {
const result = await httpRequest(ajaxUrl, { action: 'filter_ajax', 'roll-title': searchTerm.value });
console.log(result);
}
})
</script>
<?php } );
add_action( 'wp_ajax_nopriv_filter_ajax', 'filter_ajax' );
add_action( 'wp_ajax_filter_ajax', 'filter_ajax' );
function filter_ajax() {
echo "TESTING";
wp_die();
}
Whenever I am trying to send an HTTP request it is throwing 400 bad requests and prints 0 as result. Trying to implement a filter plugin but the above code snippets aren't working at all. I have tried multiple solutions from StackOverflow but none worked.
Here I am sharing my working code which I was developed by today so you can check here.
//First I enqueue script using action in function.php file
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
//Then I localize custom js for admin ajax
wp_localize_script( 'custom-js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
//I choose action and javascript object "my_ajax_object"
//Now I create custom.js as per mentioned above path
$(function(){
$('#capture').click(function(){
//capture is button id.
//here is the ajax call
var value = '123';
jQuery.ajax({
type: "post",
dataType: "HTML",
url: my_ajax_object.ajax_url,
data : {action: "my_ajax_object","value":value},
success: function(msg){
console.log(msg);
}
});
});
});
//Now I wrote ajax function
add_action( 'wp_ajax_nopriv_my_ajax_object', 'my_ajax_object' );
add_action( 'wp_ajax_my_ajax_object', 'my_ajax_object' );
function my_ajax_object()
{
$value = $_POST['value'];
$response = '<p>value is '.$value.'<p>';
return $response;
wp_die();
}

AJAX Wordpress ACF update with button click id

I using ACF wordpress to update acf field for user to populate with button id click.
I am getting Error as admin-ajax.php with 400
Error POST https://domainname/wp-admin/admin-ajax.php 400 ()
Wordpress code on template
<button class="get_project" id="1479" name="urbtnid" data-postid="147">Get project</button>
<button class="get_userbtn" value="<?php echo get_current_user_id() ?>" id="get_userbtn" ><?php echo get_current_user_id() ?></button>
**
JQUery AJAX Code
**
jQuery(function($){
$('.get_project').click(function() {
var stdid = jQuery('#get_userbtn').attr('value');
var stdbtnid = this.id;
jQuery.ajax({
url: my_ajax_object.ajax_url,
type : 'post',
data: dataString,
success : function( response ) {
console.log(response);
}
});
})
});
**
Function.php code
**
function my_enqueue_ajax_save() {
wp_register_script( 'ajax-script', get_template_directory_uri() . '/pradeep-js-css/my-ajax-id-save-script.js', array('jquery') , false, true );
wp_enqueue_script( 'ajax-script' );
wp_localize_script( 'ajax-script', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_ajax_save' );
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action(){
$postid = $_POST['stdid1'];;
$fieldname = 'last_question_viewed';
$fieldvalue = $_POST['stdbtnid1'];
update_post_meta($postid, $fieldname, $fieldvalue);
echo $postid;
wp_die($fieldname = '', $fieldvalue = '', $postid = '');
}
Updated jquery with action
jQuery(function($){
var stdid = jQuery('#get_userbtn').attr('value');
var stdbtnid = this.id;
var dataString = 'stdid1=' + stdid + '&stdbtnid1=' + stdbtnid;
$('.get_project').click(function() {
var data = {
action: "my_action",
stdid: stdid,
stdbtnid1: stdbtnid
};
jQuery.ajax({
url: my_ajax_object.ajax_url,
type : 'post',
data: data,
success : function( response ) {
console.log(response);
}
});
})
});

Ajax call from frontend not working with wordpress

Call to Ajax not working from frontend in WordPress,All i want to the data from db based on id,this is what i have tried so far.
//Frontend view
<a href="javascript:void(0)" onclick="getDetails(<?=$index;?>)" >
<?php echo $value ?>
</a>
//Functions.php
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/js/ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action('wp_ajax_nopriv_more_posts', 'get_more_posts');
function get_more_posts(){
// How to get id here to query for the database
echo "Hello World";
exit();
}
// Ajax scripts File
function getDetails(id)
{
jQuery.ajax({
url: more_posts.ajax_url,
type: "GET",
data: {
action: 'more_posts'
},
dataType: "html",
success: function(response){
alert(response);
}
});
}
I am getting this error
reference error more_posts is not defined
//Frontend view
<a href="javascript:void(0)" onclick="getDetails(<?=$index;?>)" >
<?php echo $value ?>
</a>
//Functions.php
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/js/ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action('wp_ajax_nopriv_more_posts', 'get_more_posts');
function get_more_posts(){
// How to get id here to query for the database
echo "Hello World";
echo $_GET['id'];
exit();
}
// Ajax scripts File
function getDetails(id)
{
var id = id;
jQuery.ajax({
url: url: my_ajax_object.ajax_url,
type: "GET",
data: {
action: 'get_more_posts',
id: id,
},
dataType: "html",
success: function(response){
alert(response);
}
});
}
This should work! You dont need absolute path or var with 'href', url: my_ajax_object.ajax_url, is enough as you already added admin-ajax.php with wp_enqueue_script. Thanks
You mistake in
url: more_posts.ajax_url
Because you localize script name is my_ajax_object
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
try this
url: my_ajax_object.ajax_url

wordpress ajax call keep on running after calling once

I made a wordpress ajax call code in which when i click on a button the the function runs properly and returns the value first time as it should but after that the ajax call to admin-ajax.php keepon running as i can see from developer tools . My code is
add_action( 'wp_ajax_arete_bp_endorse', 'arete_bp_endorse_ajax' );
add_action( 'wp_ajax_nopriv_arete_bp_endorse', 'arete_bp_endorse_ajax' );
function arete_bp_endorse_ajax(){
global $wpdb;
$result['type'] = "works";
echo $result;
wp_die();
}
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/example/js/example.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
the example.js file code
jQuery(document).on("click",".endorse-bt", function (event){
event.preventDefault();
var type= jQuery(this).attr("data");
var option= jQuery(this).parents("li").attr("data-endorsed-item-name");
var profile_id=jQuery(this).parents("li").attr("data-prf-id");
var login_id=jQuery(this).parents("li").attr("data-lg-id");
jQuery.ajax({
dataType : "json",
url : myAjax.ajaxurl,
type: 'POST',
data:{action: "arete_bp_endorse", type : type, option: option, profile_id: profile_id, login_id: login_id},
success: function( response ){
//Do something with the result from server
alert(response.type);
}
});
});

Categories