(Wordpress / Ajax) ReferenceError: Can't find variable: ajaxobject - javascript

I'm working with Wordpress + Ajax and even using the proper hooks I get the error "ReferenceError: Can't find variable: ajaxobject". Of course there is some problem with my ajaxurl but I don't understand where since it seems well done to me. Can you help me?
In my functions.php
add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 11, 2 );
function add_frontend_ajax_javascript_file()
{
wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
my jQuery/AJAX file
var itemtitle = $('#itemtitle').val();
var itemdescription = $('#itemdescription').val();
jQuery.ajax({
method: 'post',
url : ajaxobject.ajaxurl, //Why???
dataType: "json",
data: {
'action':'update_portfolio_function',
'pid' : id,
'itemtitle' : itemtitle,
'itemdescription' : itemdescription,
},
success:function(data) {
// This outputs the result of the ajax request
alert("Coooool");
},
error: function(errorThrown){
console.log(errorThrown);
}
});
of course the update_portfolio_function looks like
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
$id = $_REQUEST['pid'];
$title = $_REQUEST['itemtitle'];
$description = $_REQUEST['itemdescription'];
$attachment = array(
'ID' => $id,
'post_title' => $title,
'post_content' => $description
);
// now update main post body
wp_update_post( $attachment );
die();
}
Should I use init or no_priv?

You just need to use ajaxurl instead of ajaxobject.ajaxurl
like below
jQuery.ajax({
method: 'post',
url : ajaxurl,
dataType: "json",

Related

Pass JavaScript variable to PHP function within Ajax call?

I'm trying to create an ajax search form that gets WordPress posts if the search term is found within the post title. This is my PHP function:
function get_records_ajax($query) {
$args = array(
'post_type' => array('record'),
'post_status' => array('publish'),
'posts_per_page' => 999,
'nopaging' => true,
'meta_query' => array(
'key' => 'title',
'value' => $query,
'compare' => 'IN',
)
);
$ajaxposts = get_posts( $args );
echo json_encode( $ajaxposts );
exit;
}
And this is my jQuery function:
jQuery('.rrm_search_form').on('submit', function(e){
e.preventDefault();
let query = jQuery(this).find('.rrm_search_input').val();
console.log('search submitted for ' + query);
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "json",
data: { action : `get_records_ajax(${query})` },
success: function( response ) {
jQuery.each( response, function( key, value ) {
console.log( key, value );
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
});
I've tried lots of different syntax to try and pass the variable within the data action of my ajax call but nothing's working. Any ideas how I might be able to do this?
I assume your ajax URL is fine and loading in the website.
Now all you have to modify your JS scripts and need to add hooks in PHP section. First in your JS script modify the data: line as follows:
data: { action : 'get_records_ajax', query: query },
Also You can add security check if you want. but leave it now.
Secondly, in your PHP file add the following code..
add_action( "wp_ajax_nopriv_get_records_ajax", 'get_records_ajax' );
add_action( "wp_ajax_get_records_ajax", 'get_records_ajax' );
and then in your get_records_ajax receive the query value
function get_records_ajax(){
$query = sanitize_text_field($_POST['query']);
//then your rest code
}
It will return all the post. Now you need to adjust your JS code in the success block :
success: function( response ) {
console.log(response)
//adjust here with your HTML dom elements
}

(Wordpress / AJAX): Update attachment title, description and alt from frontend

Using wordpress with AJAX I'm trying to update attachment meta from frontend. For some reasons I get json response "NaN" or null. This is a form for logged users so I'm not using wp_ajax_nopriv_
In my functions.php
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
$id = $_POST['pid'];
$title = $_POST['itemtitle'];
$description = $_POST['itemdescription'];
$attachment = array(
'ID' => $id,
'post_title' => $title,
'post_content' => $description
);
// now update main post body
wp_update_post( $attachment );
die();
$response = array('pid'=>$id,'title'=>$title);
echo wp_send_json($response);
exit;
}
And in my jQuery / AJAX I have:
function update_info(id, itemtitle, itemdescription)
{
jQuery.ajax({
method: 'post',
url : ajaxurl,
dataType: "json",
data: {
'action':'update_portfolio_function',
'pid' : id,
'itemtitle' : itemtitle,
'itemdescription' : itemdescription,
},
success:function(data) {
alert(data.pid + data.title); //Damn
},
error: function(errorThrown){
console.log(errorThrown);
}
});
//alert("a");
}
As response I want to check if id and title have been submitted correctly. As you can see I'm using an alert to print them. Values are well passed into the jQuery function but I don't think they're received from my php side (or badly processed) since I get "NaN" as response on data.pid and data.title. Can you help me?
EDIT
My request details
My fault. Oversight here:
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
should be
add_action('wp_ajax_update_portfolio_function', 'update_portfolio_function' );
Fixed.

Variations Javascript not working when single_product_content is loaded via Ajax (WooCommerce)

In my WooCommerce Shop Templates I am loading the single-product-content dynamically in the archive-product.php page with Ajax. This part is working.
But the javascript to choose the product variations is missing so I tried to add the script to the html after the successful ajax request.
I could load the script but I still can not choose a product variation. No events are triggered. Seems like I am missing something...
My Javascript:
jQuery('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript () {
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
In functions.php
add_action( 'wp_enqueue_scripts', 'child_add_scripts' );
function child_add_scripts(){
wp_register_script( 'pa_script', get_stylesheet_directory_uri() . '/main.js', array('jquery'), true );
wp_localize_script( 'pa_script', 'singleprojectajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('pa_script');
}
function load_single_product_content () {
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
echo "There were no products found";
}
}
wp_die();
}
add_action('wp_ajax_load_single_product_content', 'load_single_product_content');
add_action('wp_ajax_nopriv_load_single_product_content', 'load_single_product_content');
The WooCommerce script "add-to-cart-variations.js":
https://searchcode.com/codesearch/view/95139130/
Did you try like:
jQuery(document).ready(function($) {
"use strict";
$('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
},
complete: function(){
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript() {
$.getScript("www.yoursitenamehere.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
$.getScript("www.yoursitenamehere.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
});
You used $ for your AJAX, so it's safe to assume you're already inside the document ready environment. So you don't need to use jQuery.
I placed the $.getScript() in the complete ajax method. Plus you need to include the entire url to your page.

Ajax not working wordpress

js file: (walking_log.js)
jQuery.ajax
({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
'action':'myaction'
},
success: function(data)
{
alert('Happy new year 2015 :) ');
},
error: function(data)
{
alert( 'Sorry! No Happy New year 2015 :(' );
}
});
php file:
// Ajax Handler.
function so_enqueue_scripts()
{
$plugin_dir_path = dirname(__FILE__);
$plugin_url = plugins_url();
wp_enqueue_script( 'ajaxHandle', $plugin_url . '/walking-log/js/walking_log.js', array('jQuery') );
wp_localize_script( 'ajaxHandle', 'myAjax', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
}
add_action( 'init', 'so_enqueue_scripts' );
function so_wp_ajax_function()
{
die();
}
path of walking_log.js is right, i have opened it in the browser. I am getting the success failure alert. don't know why. any help would be appreciated.
Edit:
I am getting this on firebug.
"NetworkError: 404 Not Found - http://192.168.1.6/Interaction/exercise-log/%3C?php%20echo%20admin_url(%22admin-ajax.php%22);%20?%3E"
why this is happening?
In js file, This line must be causing the error..
url: '<?php echo admin_url("admin-ajax.php"); ?>',
You are calling a php function admin_url in js file. JS files will not call your php fn.
Your error confirms it .... Encoded url
%3C?php%20echo%20admin_url(%22admin-ajax.php%22);%20?%3E
Decoded URL
<?php echo admin_url("admin-ajax.php"); ?>

AJAX commenting in WordPress

I'm trying to get AJAX commenting working in WordPress. So far I have written a PHP handler and a script.
My script (modified from here):
jQuery(document).ready(function($){
var commentform = $('#commentform');
commentform.prepend('<div id="comment-status"></div>');
var statusdiv = $('#comment-status');
commentform.submit(function(){
//serialize and store form data in a variable
var data=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'POST',
url: formurl,
dataType: 'JSON',
data: data,
error: function(XMLHttpRequest, errorThrown)
{
statusdiv.html('<p class="ajax-error" >Oops, an error occured</p>');
},
success: function(data)
{
statusdiv.html(data);
$('#commentform #comment').val('');
}
});
return false;
});
});
My PHP handler:
function ajaxify_comments( $comment_ID, $comment_status ) {
$comment = get_comment( $comment_ID );
$response = $comment->comment_content;
echo json_encode( $response );
die();
}
add_action( 'comment_post', 'ajaxify_comments', 20, 2 );
My PHP handler, ajaxify_comments(), is hooked to comment_post which fires immediately after the comment is saved to the database. The function gets the comment text and returns a response (the comment text) to my AJAX script. If everything is successful, the comment text is displayed on screen. If unsuccessful, an error message is displayed.
My problem
If I submit a comment, the comment is saved to the database and the comment text is displayed on screen. This bit works! My problem is if I make a second comment without refreshing the page - I always get "Oops, an error occurred". What am I doing wrong?
Update
After #adeneo's suggestion to use the WordPress built in AJAX hooks I have come up with a new script and PHP handler...
Script:
jQuery(document).ready(function($) {
var path = ac.path;
var security = ac.security;
var ajax_url = ac.ajax_url;
var commentform = $('#commentform');
commentform.prepend('<div id="comment-status"></div>');
var statusdiv = $('#comment-status');
commentform.submit(function(){
$.ajax({
type: 'POST',
url: ajax_url,
dataType: 'JSON',
data: {
'action': 'ac',
'security': security
},
success:function(data) {
statusdiv.html(data);
$('#commentform #comment').val('');
},
error: function(data){
statusdiv.html('<p class="ajax-error">Oops, an AJAX error occured</p>');
}
});
return false;
});
});
PHP handler
function ajaxify_comments() {
check_ajax_referer( 'ajax_ac_nonce', 'security' );
$response = 'blah';
echo json_encode( $response );
die();
}
add_action( 'wp_ajax_ac', 'ajaxify_comments' );
For completeness it is worth letting you know that I also have:
wp_enqueue_script( 'ac-script', plugins_url( '/js/script.js', __FILE__ ), array( 'jquery' ), 1.0, true );
$path = get_bloginfo( 'stylesheet_directory' );
// set the nonce security check
$ajax_nonce = wp_create_nonce( 'ajax_ac_nonce' );
wp_localize_script(
'ac-script',
'ac',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'path' => $path,
'security' => $ajax_nonce,
)
);
My question now becomes: How do I make the submitted comment data available to my PHP handler? I guessing I'll need to manually save the comment data to the database? I need this data available in my PHP function first but not sure how to do that?

Categories

Resources