Wordpress Jquery MySQL Plugin - javascript

So, I'm working on a plugin that leverages jquery and mysql to dynamically update dropdown boxes.
When the page first loads, the dropdown box should be populated with data selected from mysql. But nothing, apart from the empty dropdown box rendering to the page, works. And no error messages are issued.
What am I overlooking here?
plugins/myplugin/myplugin.php
<?php
/**
* Plugin Name: Test
* Plugin URI:
* Description: This plugin performs dynamic region updates into select boxes in WordPress
* Version: 1.0.0
* Author: Me
* Author Email:
* License: GPL2
*/
function getregions_scripts() {
wp_enqueue_script(
'getregions-script',
plugin_dir_url(__FILE__) . "assets/getregions.js",
array('jquery'),
'1.0',
true
);
wp_localize_script(
'getregions-script', // this needs to match the name of our enqueued script
'gymRegions', // the name of the object
array('ajaxurl' => admin_url('admin-ajax.php')) // the property/value
);
}
add_action( 'wp_enqueue_scripts', 'getregions_scripts' );
add_action( 'wp_ajax_showcountries', 'showcountries_callback' );
add_action( 'wp_ajax_no_priv_showcountries', 'showcountries_callback' );
function showcountries_callback() {
include_once("pdo_mysql.php");
pdo_connect("localhost","user","password");
pdo_select_db("wpdb");
$action=$_POST["action"];
if($action=="showcountries"){
$showcountry = pdo_query("Select country_data from wp_usertable");
if (!$showcountry) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $showcountry;
die($message);
}else{
foreach($showcountry as $row){
echo '<option value=".$row[country_code].">.$row[country_name].</option>';
}
}
}
else if($action=="showregions"){
$country_id= $_POST["country_id"];
$showregion = pdo_query("Select region_code, region_name from regiontbl
WHERE country_id=?", pdo_real_escape_string($country_id));
if (!$showregion) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $regionquery;
die($message);
}else{
foreach($showregion as $row){
echo '<option value=".$row[region_code].">.$row[region_name].</option>';
}
}
}
}
function showcountries_frontend() {
$the_html = '
<form id="MyForm">
<div style="float: left">
<select id="CountryList" onchange="getRegion()" size="20"></select>
<select id="RegionList" size="20" onchange="getMap()"></select>
</div>
<div id="cityList" style="float: right"></div>
</form>';
return $the_html;
}
add_shortcode("sc_frontend", "showcountries_frontend");
?>
plugins/myplugin/assets/getregions.js
function initialize($) {
.......
feedData($);
}
jQuery(document).ready(function ($) { initialize($); });
function feedData($) {
jQuery(document).ready(function ($) {
var serialized = $('#MyForm').serialize();
$.ajax({
cache: false,
type: "POST",
async: false,
url: "gymRegions.ajaxurl",
data:{action=showcountries, serialized},
success: function (data) {
$('#CountryList').append(data);
},
error: function (data, status, error) {
console.log(data);
console.log(status);
console.log(error);
}
});
});
}

There's a lot going on here that needs to be addressed.
Your ajax call is looking for a location to make the call to; however, you are passing this value:
url: "gymRegions.ajaxurl",
So, the resulting 404 is based on that string: 192.168.0.50/index.php/testing-2/gymRegions.ajaxurl
Localizing a script
In order to pass the location of your plugin directory to your javascript file, you will need to localize the scrip. This can be done in wordpress using the following:
wp_enqueue_( 'getregions-script', plugin_dir_url(__FILE__) . "assets/getregions.js", array('jquery'), '1.0', true);
wp_localize_script( 'getregions-script', 'gymRegions', array('ajaxurl' => plugin_dir_url(__FILE__) . 'assets/getregions-ajax.php'));
This will allow you to call gymRegions.ajaxurl without quotes in your ajax call.
Make your ajax file
Now that this has been completed, you can create a new php file in your plugin: assets/getregions-ajax.php. This file will house your current showcountries_callback function content (does not need to be a function). Whatever is on this page will be executed.
To include wp, I usually use something like this:
header('Content-Type:application/json');
header("X-Robots-Tag: noindex, nofollow", true);
/* find and load wp to avoid duplicating class */
if (file_exists('../../../../wp-load.php')) :
require_once('../../../../wp-load.php');
else:
require_once('../../../../../wp-load.php');
endif;
After this, I will require my class or execute any code.
JSON encode output
Finally, consider JSON encoding your output. Instead of echo-ing everything instantly create an $html variable and at the end of your file:
echo json_encode($html, JSON_PRETTY_PRINT);
Go one step at a time
This may be a little confusing at first but taking it one step at a time will help. Don't try to eat it all in one bite, just focus on getting 'hello world' to return from your ajax call and then build from there.
There may be other issues but this should at least get you started down the right path.

Remove console.log
Then the data will not be get

Related

PHP variables resetting after passing javascript variables through AJAX post

I'm trying to make some SQL queries using PHP in Wordpress, to auto populate and check values on a gravity form against the existing database.
To do that however, I'm going to need to pass some javascript variables to php, then use that to interact and pull that data back to the form. As someone with minimal web dev background, easier said then done.
My main issue is with an AJAX call that properly carries over a value, but only to the action function. All other calls will show null (I assume due to scoping, but globals don't seem to help).
The main relevant PHP is in a custom plugin as follows:
$address = 0;
function my_enqueue() {
wp_register_script( 'lead-scheduler', null);
wp_enqueue_script( 'lead-scheduler', plugins_url( '/lead_ajax.js', __FILE__ ), array('jquery') );
wp_localize_script( 'lead-scheduler', 'leadajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'jquery' );
wp_register_script( 'lead_ajax', null);
wp_enqueue_script( 'lead_ajax' );
}
add_action( 'init', 'my_enqueue' );
function handle_request(){
//Check post address, then apply to global variable
echo $_POST['address'] . "\n";
global $address;
$address = $_POST['address'];
echo $address . "\n";
wp_die("RIP");
}
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
function functionCaller() {
if (is_page ('')) {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function(){
var addressField = document.getElementById('input_22_2');
var temp;
//Set up event listener
addressField.onchange = addressCheck;
function addressCheck(){
//Get foreign script
$.getScript("/wp-content/plugins/lead-scheduler/lead_ajax.js", function(){
//Wait until done to execute console.log
$.when(adrCheck()).done(function(){
console.log("Logging: " + "<?php global $address; echo $address ?>");
});
});
}
});
});
</script>
<?php
}
}
add_action('wp_head', 'functionCaller'); ?>
The AJAX call comes from a JS file that I call to:
//AJAX
function adrCheck(){
jQuery(document).ready( function() {
console.log("called")
var addressField = document.getElementById('input_22_2').value;
jQuery.ajax({
type : "post",
url : leadajax.ajax_url,
data : {action: "handle_request", address: addressField},
success: function(response) {
console.log(response)
},error: function(response){
console.log(response);
}
})
})
}
The call seems to work, as the echo in handle_request() works fine. But calling that variable anywhere else returns null. $.when.done doesn't seem to do much, nor does anything synchronous.
I'm sure there's something super elementary that I'm missing, but I can't seem to find it.

Wordpress loadmore button does not work. $wp_query not returning last post loop query

-- Edit 1 --
Found out some new things. I'm adding them on top since they might be more relevant than the code below.
I've rerun the scripts a few times. I now get different findings actually.
Running var_dump($wp_query->query); right after $the_query = new WP_Query($queryArgs);In the first render of the post loop gives me the query vars of the page the loop is rendered on. Calling it with ajax it reruns the same part of the code, right? So than it returns empty.
My thoughts:
Pages is called, runs funtions.php.
Runs the part of the wp_enqueue_script('rtt_scripts');
This is the moment it gets the current $wp_query values. Which are the values of the page.
Than renders the page with the post loop.
This is the moment the post loop runs $the_query = new WP_Query($queryArgs);
On press of the load more the ajax than calls it to rerun the post loop. With the query vars set with wp_enqueue_script('rtt_scripts');
This made me think. Am I running the code in a wrong order? Are the query vars for ajax set on the wrong moment? Other thought. Should I focus on how to get the query vars on the first post loop to the ajax query vars?
-- End Edit --
I’m having trouble with a load more button in Wordpress. The code below is the basic code I have right now.
As far as I can see this should be a working code :) Problem is though that this doesn’t work.
My problem is that I don’t know where to start debugging. Closest I know where the problem lies is this:
In rtt_loadmore_ajax_handler() there is the var $queryArg
When var_dumping the var $queryArg in both rtt_post_grid() and rtt_loadmore_ajax_handler()
It gives different results. Here I would expect the same results. In the Ajax call it returns the arguments
of the current rendered page and not of the post query on this page.
Would the global $wp_query; be the problem? And how do I go from here?
The basic post code:
function rtt_post_grid()
{
$queryArgs = Array(
"post_type" => Array(
'news',
'agenda'
),
'posts_per_page' => 4,
'post_status' => 'publish',
'paged' => 1
);
// post grid wrap
echo '<div id="rtt_posts_wrap" >';
rtt_post_grid_query($queryArgs);
echo '</div>';
// load more button
echo '<form>';
echo '<button id="rtt_loadmore" class=" button">Load more post</button> ';
echo '<input type="hidden" name="action" value="loadmore" />'; // this line might be obsolete
echo '</form>';
}
function rtt_post_grid_query($queryArgs)
{
// The Query
$the_query = new WP_Query($queryArgs);
// The Loop
if ($the_query->have_posts()) {
echo '<ul>';
while ($the_query->have_posts()) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
echo 'no posts found';
}
}
Setting the JS:
if(!has_action('rtt_post_grid_script_and_styles')) {
add_action('wp_enqueue_scripts', 'rtt_post_grid_script_and_styles', 1);
function rtt_post_grid_script_and_styles()
{
global $wp_query;
wp_register_script('rtt_scripts', plugin_dir_url( __FILE__ ) . 'js/script.js', array('jquery'), time());
wp_enqueue_script('rtt_scripts');
wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode($wp_query->query_vars), // everything about your loop is here
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
));
wp_enqueue_script('rtt_scripts');
}
}
The JS/Ajax:
jQuery(function($){
$(window).ready(function() {
$('#rtt_loadmore').click(function () {
$.ajax({
url: rtt_loadmore_params.ajaxurl,
data: {
'action': 'loadmore', // the parameter for admin-ajax.php
'query': rtt_loadmore_params.posts, // loop parameters passed by wp_localize_script()
'page': rtt_loadmore_params.current_page, // current page
},
dataType: 'json',
type: 'POST',
beforeSend: function (xhr) {
$('#rtt_loadmore').text('Bezig met laden...'); // some type of preloader
},
success: function (data) {
if (data) {
$('#rtt_loadmore').text('More posts');
$('#rtt_posts_wrap').append(data.content); // insert new posts
rtt_loadmore_params.current_page++;
if (rtt_loadmore_params.current_page == rtt_loadmore_params.max_page){
$('#rtt_loadmore').hide(); // if last page, HIDE the button
}
} else {
$('#rtt_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
});
});
The Ajax handler:
add_action('wp_ajax_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
function rtt_loadmore_ajax_handler(){
$postData = $_POST;
// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';
ob_start();
rtt_post_grid_query($queryArgs);
$output = ob_get_contents();
ob_end_clean();
global $the_query;
echo json_encode( array(
'posts' => serialize( $the_query->query_vars ),
'max_page' => $the_query->max_num_pages,
'found_posts' => $the_query->found_posts,
'content' => $output
) );
die;
}
So, I've figured it out. I'll explain for it might be useful to somebody else.
The reason it did not work is because the code above is more useful in a template. But I use it in a shortcode. The wp_localize_script() was run on rendering the page and not on running the shortcode. That's why it didn't had the right variables.
I've moved the code below inside the shortcode. Right after the new WP_query:
// The Query
$the_query = new WP_Query($queryArgs);
// The Loop
if ($the_query->have_posts()) {
wp_enqueue_script_ajax_vars($the_query);
Than passed the new query
function wp_enqueue_script_ajax_vars($the_query)
{
wp_register_script('rtt_scripts', plugin_dir_url(__FILE__) . 'js/script.js', array('jquery'), time());
wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode($the_query->query_vars), // everything about your loop is here
'query_vars' => json_encode($the_query->query),
'current_page' => $the_query->query_vars['paged'] ? $the_query->query_vars['paged'] : 1,
'max_page' => $the_query->max_num_pages,
));
wp_enqueue_script('rtt_scripts', '', '', '', true); // note the last 'true' this sets it inside the footer
}
Resulting in wp_localize_script() creating the variable in the footer. It was in the header before. But by getting it within the shortcode, sending the new query arguments and putting them inside the footer (since the header is already rendered by then) I have set the JS var for Ajax.
Add the two order arguments to $queryArgs.
// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';
$queryArgs['orderby'] = 'date'; // add this to order by date
$queryArgs['order'] = 'DESC'; // add this to display the most recent

WordPress Custom Plugin button onclick call php function

My plugin shows 2 input fields and a button wherever you put the placeholder in WP. After clicking the button it calls a js function which should start a php function using AJAX but somehow i get the error message: "reference error myAjax is not defined"
wsn-plugin.php
function wpb_new_company(){
echo '<input type="text" class="form-control" id="companyName" placeholder="Firmenname">';
echo '<input type="text" class="form-control" id="companyYear" placeholder="Jahr">';
echo '<button onclick="myAjax();" id="btnNewCompany" type="submit" class="btn btn-primary">Erstellen</button>';
}
script.js (which handles all the events)
function myAjax() {
alert("myAjax gestartet");
$.ajax({
type: "POST",
url: 'localhost/wp/wp-content/plugins/wsn-plugin/wsn-plugin.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
alert("myAjax ausgeführt");
}
and again wsn-plugin.php which should then run some function
if($_POST['action'] == 'call_this') {
echo "i reached it";
}
Changed
function wpb_adding_scripts() {
wp_register_script('wsn_script', plugins_url('script.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('wsn_script');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
and js script:
function myAjax() {
alert("myAjax gestartet");
$.ajax({
type: "POST",
url: '/wp/wp-content/plugins/wsn-plugin/wsn-plugin.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
alert("myAjax ausgeführt");
}
no chrome shows the error message:
localhost says fatal error uncaught error call to undefined function add_action() in wsn-plugin.php:16
It sounds like you did not load your javascript file from your plugin using wp_register_script() and wp_enqueue_script().
EDIT: There are other issues here but I ignored them since they were not the cause of the error you got. You will want to read https://codex.wordpress.org/AJAX_in_Plugins and pay special attention to the section "Separate JavaScript File". That should get you sending the data to the correct URL and being able to process it.
just for completion what i did to reach my goal was. I put some comments in front of the code lines. However I'm not certain if they are correct but at the moment they help at least me to understand it a little bit better.
my plugin php file:
//reference to the backend ajax framework
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'test', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
// to reference the ajax call to this function
add_action( 'wp_ajax_nopriv_call_this', 'new_company_variable_transfer' );
function new_company_variable_transfer() {
echo 'Did we get here?';
wp_die();
}
result div
function wpb_new_company(){
echo '<input type="text" class="form-control" id="companyName" placeholder="Firmenname">';
echo '<input type="text" class="form-control" id="companyYear" placeholder="Jahr">';
echo '<button onclick="callAjax()" id="btnNewCompany" type="submit" class="btn btn-primary">Erstellen</button>';
echo '<div id="result">Hier steht das resultat</div>';
}
//to be able to put it on any page with the shortcode [new_company]
add_shortcode('new_company', 'wpb_new_company');
and the simple ajax call in the script file
function callAjax(){
$.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{action:'call_this'},
success:function(response) {
alert(response);
$("#result").html(response);
}
});
}
And to show you the result visually the pictures of the steps
Unfortunately because of the stack overflow code correction i cannot post pictures here...
At the end you can see it changed the text to the variable we get from the php file

wp_enqueue_script not working on AJAX called php file

I've got a complicated little problem here.
I'm building a WordPress plugin where I select a "parent" post (of a custom type that I made called 'step') and then an AJAX function shows a new select bar with all of the children of that parent. I do this by outputting the new and elements in the PHP file that's called in the AJAX function. This works, but now I want to repeat the process to run a function from the same JQuery file when this new outputted element is added to the page. (See Javascript code)
Main php plugin file (in a folder within the plugin directory):
<?php
/*
Plugin Name: n8jadams Step by Step Plugin (WIP)
Plugin URI:
Description:
Author: Nathan James Adams
Author URI: http://nathanjamesadams.com
Version: 0.0.1a
*/
//Exit if accessed directly
if(!defined('ABSPATH')) {
exit;
}
//My custom post type, it works fine
require_once(plugin_dir_path(__FILE__).'n8jadams-step-funnel-cpt.php');
require_once(plugin_dir_path(__FILE__).'n8jadams-ajax.php');
//Add my javascript
function n8jadams_init_javascript() {
wp_register_script('n8jadams_javascript', plugin_dir_url(__FILE__).'n8jadams-scripts.js', array('jquery'),'1.1', false);
wp_enqueue_script('n8jadams_javascript');
}
add_action('wp_enqueue_scripts', 'n8jadams_init_javascript');
//Adds a plugin menu to the wordpress sidebar
function n8jadams_add_plugin_menu() {
add_menu_page('', 'Steps Settings', 4, 'steps-settings', 'n8jadams_steps_settings', '');
}
add_action('admin_menu', 'n8jadams_add_plugin_menu');
//The actual function for the menu page
function n8jadams_steps_settings() {
//Access the database and the tables we want
global $wpdb;
$posts = $wpdb->prefix.'posts';
//Get the user id
$user = wp_get_current_user();
$userid = $user->ID;
//Initialize javascript (it works here!)
n8jadams_init_javascript();
/* Get all the parents */
$parentsquery = "
SELECT `ID`, `post_title`
FROM $posts
WHERE `post_author` = $userid
AND `post_parent` = 0
AND `post_status` = 'publish'
AND `post_type` = 'step'
";
$parentsarray = $wpdb->get_results($parentsquery);
?>
<h4>My Forms:</h4>
<select id="parentselect">
<option id="-1"> - Select Your Step Form - </option>
<?php
//output the parents
for($i=0;$i<sizeof($parentsarray);$i++) {
echo '<option id="'.$parentsarray[$i]->ID.'">'.$parentsarray[$i]->post_title.'</option>';
}
?>
</select>
<div id="displayChildren"></div>
<?php
}
?>
Javascript (n8jadams-scripts.js):
(function($){
$('#parentselect').change(function(s) {
var thisID = s.target[s.target.selectedIndex].id;
var outputDisplay = document.getElementById('displayChildren');
if(thisID != '-1') {
$.ajax({
type: 'POST',
url: 'admin-ajax.php',
data: {
action: 'n8jadams_get_children',
id: thisID
},
success: function(response){
if(response == "") {
outputDisplay.textContent = "This form has no children. Add them in the sidebar menu of this step form.";
} else {
outputDisplay.innerHTML = response;
}
},
error: function(errorThrown) {
alert(errorThrown);
}
});
} else {
outputDisplay.textContent = '';
}
});
// I want this function to work
/*
$('#childselect').change(function(t) {
console.log("test");
});
*/
})(jQuery);
PHP file called by AJAX (n8jadams-ajax.php):
<?php
function n8jadams_get_children() {
//Get the id of the parent
$parent_post_id = $_POST['id'];
//Sanitize the input (Added after question was answered)
$parent_post_id = preg_replace("/[^0-9]/","",$parent_post_id);
//Access database
global $wpdb;
$posts = $wpdb->prefix.'posts';
$user = wp_get_current_user();
$userid = $user->ID;
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
//Retrieve the children associated with this parent
$childrenarray = $wpdb->get_results($childrenquery);
//Initialize Javascript (it doesn't work here!)
n8jadams_init_javascript();
if(!empty($childrenarray)) { ?>
<h4>My Steps:</h4>
<select id="childselect">
<option id="-1"> - Select Your Step - </option>
<?php
//output the children of the parent
for($i=0;$i<sizeof($childrenarray);$i++) {
echo '<option id="'.$childrenarray[$i]->ID.'">'.$childrenarray[$i]->post_title.'</option>';
} ?>
</select>
<?php wp_die();
}
}
add_action('wp_ajax_n8jadams_get_children', 'n8jadams_get_children');
add_action('wp_ajax_nopriv_n8jadams_get_children', 'n8jadams_get_children');
?>
Screenshot of Plugin Menu
I cannot figure out why my javascript file isn't working in the PHP file that's called by AJAX. Maybe the vast wisdom of the StackOverflow can help me. Thanks for the help in advance. :)
You are hooking into wp_enqueue_scripts, which is only run for the frontend of Wordpress (the part the average visitor sees). If you want to load a script into wp-admin, the backend of Wordpress, use the admin_enqueue_scripts action.
Since this code does not work in /wp-admin/, you don't need to use admin_enqueue_scripts. I guess the whole problem would be that you are attaching a handler to $('#childselect'), while no such element exists on the page at that time. Use deferring with $(..).on(..):
$(document).on('change', '#childselect', function(e) {
//Black magic
});
Side note: As already mentioned in the comments, the following part contains an unsanitised variable which will allow an attacker to perform sql injections.
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
Use WP_Query if at all possible. If this is only used from the backend of Wordpress, don't use wp_ajax_nopriv_*, because users that are not logged in into your site have no right to use that anyway.

Wordpress ajax theme. Ajax does not work. No new data in table in db

I cant understand why my code does not work.
I have a tabel wp_subscibe with id, user_id and post_id. I want after click on button to add this data to my db by ajax. Please, look at my code.
This is my html in single.php:
<button type="submit" name="subscribe" id="subscribe">Subscribe</button>
<input id="postId" type="hidden" value="<?php the_ID(); ?>" />
My subscribe.js:
onSubscribe: function() {
var $onSubscr = $('#subscribe');
$onSubscr.on('click', function() {
var $el = $(this),
post_id = $('#postId').val(),
$.ajax({
type:"POST",
url: admin_url.ajaxurl,
dataType:"json",
//data : 'action=subscribeOn&post_id='+post_id
data: {
action: 'subscribeOn',
post_id: post_id
},
cache: false
});
return false;
});
}
And functions.php:
wp_register_script( 'subscribe', THEME_DIR . '/js/subscribe.js', array(), '', false );
wp_enqueue_script( 'subscribe' );
wp_localize_script( 'subscribe', 'admin_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
function subscribeOn() {
global $wpdb, $user_id, $post_id;
$user_id = get_current_user_id();
$post_id = $_POST['post_id'];
// $table_name = $wpdb->prefix . "subscribe";
$wpdb->insert("wp_subscribe", array( 'user_id'=>$user_id, 'post_id'=>$post_id), array('%s','%s'));
}
add_action( 'wp_ajax_nopriv_subscribeOn', 'subscribeOn' );
add_action('wp_ajax_subscribeOn', 'subscribeOn)');
Can anybody tell me where is my problem? Nothing happens in wp_subscribe in db. I try so many ways, but nothing works.
For debug of javascript you need to get used to using the console (for chrome, right click on the page and "inspect element" you will see console on the top of the pop up. This will list any errors or outputs from js.
A common mistake with jQuery and wordpress is to use $ without defining it, so you need $='jQuery'; before you can use the $ operator to refer to jQuery or substitute the use of $ for the word jQuery. Look up no conflict jQuery for more information.
Another common error in wp ajax and localize script is ajaxurl. For the moment enter in the static value which is www.yourserver.com/wp-admin/admin-ajax.php in most set ups, the wp-admin folder could be somewhere else on your server of course. You should test using console.log(admin_url.ajaxurl); the output will appear in the console mentioned earlier.
Updated code (dont wrap in a function and assign to a variable, just use it as is.
$=jQuery;
$(document).on('click', '#subscribe', function() {
var post_id = $('#postId').val();
$.ajax({
type:"POST",
url: '/wp-admin/admin-ajax.php', // common error is ajax.url undefined (insert your home url into the start of the string, we will eliminate any possibility of mistake by using a static url.
//dataType:"json",
//data : 'action=subscribeOn&post_id='+post_id
data: {
action: 'subscribeOn',
post_id: post_id
},
success: function(data) {
console.log(data); //this writes any output from the server into the console, so if theres a respose you know ajaxurl and jquery is more or less correct, so its good to return something whilst testing...
},
cache: false
});
});
now for the server. When testing you should return something (any data you output using echo var_dump etc will be returned and as we added a command in our browser code to output this to the console we can check for it there.
function subscribeOn() {
global $wpdb, $user_id, $post_id;
$user_id = get_current_user_id();
$post_id = $_POST['post_id'];
// we insert this to test the jQuery settings are correct. if one of the below does not appear in the console, we have issues in jQuery.
if($post_id):
echo $post_id;
else:
echo 'no post id is being submitted check selectors';
endif;
$success= $wpdb->insert("wp_subscribe",
array( 'user_id'=>$user_id, 'post_id'=>$post_id),
array('%s','%s')
);
if($success):
echo 'successfully inserted';
else:
echo 'not inserted, is the table name correct, etc? does the function work elsewhere?';
endif;
}
add_action( 'wp_ajax_nopriv_subscribeOn', 'subscribeOn' );
add_action('wp_ajax_subscribeOn', 'subscribeOn)');
hopefully this will sort it. If it does hit the correct icon beside this answer :)
I found the right way myself. it was just because one bracket after subscribeOn!
add_action('wp_ajax_subscribeOn', 'subscribeOn)');

Categories

Resources